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() && !Subtarget->isTargetELF() &&
609 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
610 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
613 if (Subtarget->is64Bit()) {
614 setExceptionPointerRegister(X86::RAX);
615 setExceptionSelectorRegister(X86::RDX);
617 setExceptionPointerRegister(X86::EAX);
618 setExceptionSelectorRegister(X86::EDX);
620 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
621 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
623 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
624 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
626 setOperationAction(ISD::TRAP, MVT::Other, Legal);
627 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
629 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
630 setOperationAction(ISD::VASTART , MVT::Other, Custom);
631 setOperationAction(ISD::VAEND , MVT::Other, Expand);
632 if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
633 // TargetInfo::X86_64ABIBuiltinVaList
634 setOperationAction(ISD::VAARG , MVT::Other, Custom);
635 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
637 // TargetInfo::CharPtrBuiltinVaList
638 setOperationAction(ISD::VAARG , MVT::Other, Expand);
639 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
642 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
643 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
645 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
646 MVT::i64 : MVT::i32, Custom);
648 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
649 // f32 and f64 use SSE.
650 // Set up the FP register classes.
651 addRegisterClass(MVT::f32, &X86::FR32RegClass);
652 addRegisterClass(MVT::f64, &X86::FR64RegClass);
654 // Use ANDPD to simulate FABS.
655 setOperationAction(ISD::FABS , MVT::f64, Custom);
656 setOperationAction(ISD::FABS , MVT::f32, Custom);
658 // Use XORP to simulate FNEG.
659 setOperationAction(ISD::FNEG , MVT::f64, Custom);
660 setOperationAction(ISD::FNEG , MVT::f32, Custom);
662 // Use ANDPD and ORPD to simulate FCOPYSIGN.
663 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
664 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
666 // Lower this to FGETSIGNx86 plus an AND.
667 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
668 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
670 // We don't support sin/cos/fmod
671 setOperationAction(ISD::FSIN , MVT::f64, Expand);
672 setOperationAction(ISD::FCOS , MVT::f64, Expand);
673 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
674 setOperationAction(ISD::FSIN , MVT::f32, Expand);
675 setOperationAction(ISD::FCOS , MVT::f32, Expand);
676 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
678 // Expand FP immediates into loads from the stack, except for the special
680 addLegalFPImmediate(APFloat(+0.0)); // xorpd
681 addLegalFPImmediate(APFloat(+0.0f)); // xorps
682 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
683 // Use SSE for f32, x87 for f64.
684 // Set up the FP register classes.
685 addRegisterClass(MVT::f32, &X86::FR32RegClass);
686 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
688 // Use ANDPS to simulate FABS.
689 setOperationAction(ISD::FABS , MVT::f32, Custom);
691 // Use XORP to simulate FNEG.
692 setOperationAction(ISD::FNEG , MVT::f32, Custom);
694 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
696 // Use ANDPS and ORPS to simulate FCOPYSIGN.
697 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
698 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
700 // We don't support sin/cos/fmod
701 setOperationAction(ISD::FSIN , MVT::f32, Expand);
702 setOperationAction(ISD::FCOS , MVT::f32, Expand);
703 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
705 // Special cases we handle for FP constants.
706 addLegalFPImmediate(APFloat(+0.0f)); // xorps
707 addLegalFPImmediate(APFloat(+0.0)); // FLD0
708 addLegalFPImmediate(APFloat(+1.0)); // FLD1
709 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
710 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
712 if (!TM.Options.UnsafeFPMath) {
713 setOperationAction(ISD::FSIN , MVT::f64, Expand);
714 setOperationAction(ISD::FCOS , MVT::f64, Expand);
715 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
717 } else if (!TM.Options.UseSoftFloat) {
718 // f32 and f64 in x87.
719 // Set up the FP register classes.
720 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
721 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
723 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
724 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
725 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
726 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
728 if (!TM.Options.UnsafeFPMath) {
729 setOperationAction(ISD::FSIN , MVT::f64, Expand);
730 setOperationAction(ISD::FSIN , MVT::f32, Expand);
731 setOperationAction(ISD::FCOS , MVT::f64, Expand);
732 setOperationAction(ISD::FCOS , MVT::f32, Expand);
733 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
734 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
736 addLegalFPImmediate(APFloat(+0.0)); // FLD0
737 addLegalFPImmediate(APFloat(+1.0)); // FLD1
738 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
739 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
740 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
741 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
742 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
743 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
746 // We don't support FMA.
747 setOperationAction(ISD::FMA, MVT::f64, Expand);
748 setOperationAction(ISD::FMA, MVT::f32, Expand);
750 // Long double always uses X87.
751 if (!TM.Options.UseSoftFloat) {
752 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
753 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
754 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
756 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
757 addLegalFPImmediate(TmpFlt); // FLD0
759 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
762 APFloat TmpFlt2(+1.0);
763 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
765 addLegalFPImmediate(TmpFlt2); // FLD1
766 TmpFlt2.changeSign();
767 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
770 if (!TM.Options.UnsafeFPMath) {
771 setOperationAction(ISD::FSIN , MVT::f80, Expand);
772 setOperationAction(ISD::FCOS , MVT::f80, Expand);
773 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
776 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
777 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
778 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
779 setOperationAction(ISD::FRINT, MVT::f80, Expand);
780 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
781 setOperationAction(ISD::FMA, MVT::f80, Expand);
784 // Always use a library call for pow.
785 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
786 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
787 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
789 setOperationAction(ISD::FLOG, MVT::f80, Expand);
790 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
791 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
792 setOperationAction(ISD::FEXP, MVT::f80, Expand);
793 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
795 // First set operation action for all vector types to either promote
796 // (for widening) or expand (for scalarization). Then we will selectively
797 // turn on ones that can be effectively codegen'd.
798 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
799 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
800 MVT VT = (MVT::SimpleValueType)i;
801 setOperationAction(ISD::ADD , VT, Expand);
802 setOperationAction(ISD::SUB , VT, Expand);
803 setOperationAction(ISD::FADD, VT, Expand);
804 setOperationAction(ISD::FNEG, VT, Expand);
805 setOperationAction(ISD::FSUB, VT, Expand);
806 setOperationAction(ISD::MUL , VT, Expand);
807 setOperationAction(ISD::FMUL, VT, Expand);
808 setOperationAction(ISD::SDIV, VT, Expand);
809 setOperationAction(ISD::UDIV, VT, Expand);
810 setOperationAction(ISD::FDIV, VT, Expand);
811 setOperationAction(ISD::SREM, VT, Expand);
812 setOperationAction(ISD::UREM, VT, Expand);
813 setOperationAction(ISD::LOAD, VT, Expand);
814 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
815 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
816 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
817 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
818 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
819 setOperationAction(ISD::FABS, VT, Expand);
820 setOperationAction(ISD::FSIN, VT, Expand);
821 setOperationAction(ISD::FSINCOS, VT, Expand);
822 setOperationAction(ISD::FCOS, VT, Expand);
823 setOperationAction(ISD::FSINCOS, VT, Expand);
824 setOperationAction(ISD::FREM, VT, Expand);
825 setOperationAction(ISD::FMA, VT, Expand);
826 setOperationAction(ISD::FPOWI, VT, Expand);
827 setOperationAction(ISD::FSQRT, VT, Expand);
828 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
829 setOperationAction(ISD::FFLOOR, VT, Expand);
830 setOperationAction(ISD::FCEIL, VT, Expand);
831 setOperationAction(ISD::FTRUNC, VT, Expand);
832 setOperationAction(ISD::FRINT, VT, Expand);
833 setOperationAction(ISD::FNEARBYINT, VT, Expand);
834 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
835 setOperationAction(ISD::MULHS, VT, Expand);
836 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
837 setOperationAction(ISD::MULHU, VT, Expand);
838 setOperationAction(ISD::SDIVREM, VT, Expand);
839 setOperationAction(ISD::UDIVREM, VT, Expand);
840 setOperationAction(ISD::FPOW, VT, Expand);
841 setOperationAction(ISD::CTPOP, VT, Expand);
842 setOperationAction(ISD::CTTZ, VT, Expand);
843 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
844 setOperationAction(ISD::CTLZ, VT, Expand);
845 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
846 setOperationAction(ISD::SHL, VT, Expand);
847 setOperationAction(ISD::SRA, VT, Expand);
848 setOperationAction(ISD::SRL, VT, Expand);
849 setOperationAction(ISD::ROTL, VT, Expand);
850 setOperationAction(ISD::ROTR, VT, Expand);
851 setOperationAction(ISD::BSWAP, VT, Expand);
852 setOperationAction(ISD::SETCC, VT, Expand);
853 setOperationAction(ISD::FLOG, VT, Expand);
854 setOperationAction(ISD::FLOG2, VT, Expand);
855 setOperationAction(ISD::FLOG10, VT, Expand);
856 setOperationAction(ISD::FEXP, VT, Expand);
857 setOperationAction(ISD::FEXP2, VT, Expand);
858 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
859 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
860 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
861 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
862 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
863 setOperationAction(ISD::TRUNCATE, VT, Expand);
864 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
865 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
866 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
867 setOperationAction(ISD::VSELECT, VT, Expand);
868 setOperationAction(ISD::SELECT_CC, VT, Expand);
869 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
870 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
871 setTruncStoreAction(VT,
872 (MVT::SimpleValueType)InnerVT, Expand);
873 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
874 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
875 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
878 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
879 // with -msoft-float, disable use of MMX as well.
880 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
881 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
882 // No operations on x86mmx supported, everything uses intrinsics.
885 // MMX-sized vectors (other than x86mmx) are expected to be expanded
886 // into smaller operations.
887 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
888 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
889 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
890 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
891 setOperationAction(ISD::AND, MVT::v8i8, Expand);
892 setOperationAction(ISD::AND, MVT::v4i16, Expand);
893 setOperationAction(ISD::AND, MVT::v2i32, Expand);
894 setOperationAction(ISD::AND, MVT::v1i64, Expand);
895 setOperationAction(ISD::OR, MVT::v8i8, Expand);
896 setOperationAction(ISD::OR, MVT::v4i16, Expand);
897 setOperationAction(ISD::OR, MVT::v2i32, Expand);
898 setOperationAction(ISD::OR, MVT::v1i64, Expand);
899 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
900 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
901 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
902 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
903 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
904 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
905 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
906 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
907 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
908 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
909 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
910 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
911 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
912 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
913 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
914 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
915 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
917 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
918 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
920 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
921 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
922 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
923 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
924 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
925 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
926 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
927 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
928 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
929 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
930 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
931 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
934 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
935 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
937 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
938 // registers cannot be used even for integer operations.
939 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
940 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
941 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
942 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
944 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
945 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
946 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
947 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
948 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
949 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
950 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
951 setOperationAction(ISD::SMUL_LOHI, MVT::v4i32, Custom);
952 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
953 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
954 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
955 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
956 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
957 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
958 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
959 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
960 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
961 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
962 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
963 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
964 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
965 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
967 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
968 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
969 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
970 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
972 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
973 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
974 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
975 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
976 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
978 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
979 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
980 MVT VT = (MVT::SimpleValueType)i;
981 // Do not attempt to custom lower non-power-of-2 vectors
982 if (!isPowerOf2_32(VT.getVectorNumElements()))
984 // Do not attempt to custom lower non-128-bit vectors
985 if (!VT.is128BitVector())
987 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
988 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
989 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
992 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
993 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
994 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
995 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
996 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
997 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
999 if (Subtarget->is64Bit()) {
1000 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1001 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1004 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1005 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1006 MVT VT = (MVT::SimpleValueType)i;
1008 // Do not attempt to promote non-128-bit vectors
1009 if (!VT.is128BitVector())
1012 setOperationAction(ISD::AND, VT, Promote);
1013 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
1014 setOperationAction(ISD::OR, VT, Promote);
1015 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
1016 setOperationAction(ISD::XOR, VT, Promote);
1017 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
1018 setOperationAction(ISD::LOAD, VT, Promote);
1019 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
1020 setOperationAction(ISD::SELECT, VT, Promote);
1021 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1024 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1026 // Custom lower v2i64 and v2f64 selects.
1027 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
1028 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
1029 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
1030 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
1032 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1033 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1035 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1036 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1037 // As there is no 64-bit GPR available, we need build a special custom
1038 // sequence to convert from v2i32 to v2f32.
1039 if (!Subtarget->is64Bit())
1040 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
1042 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1043 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
1045 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
1047 setOperationAction(ISD::BITCAST, MVT::v2i32, Custom);
1048 setOperationAction(ISD::BITCAST, MVT::v4i16, Custom);
1049 setOperationAction(ISD::BITCAST, MVT::v8i8, Custom);
1052 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1053 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1054 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1055 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1056 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1057 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1058 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1059 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1060 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1061 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1062 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1064 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1065 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
1066 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1067 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
1068 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
1069 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
1070 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
1071 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
1072 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
1073 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
1075 // FIXME: Do we need to handle scalar-to-vector here?
1076 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1078 setOperationAction(ISD::VSELECT, MVT::v2f64, Custom);
1079 setOperationAction(ISD::VSELECT, MVT::v2i64, Custom);
1080 setOperationAction(ISD::VSELECT, MVT::v4i32, Custom);
1081 setOperationAction(ISD::VSELECT, MVT::v4f32, Custom);
1082 setOperationAction(ISD::VSELECT, MVT::v8i16, Custom);
1083 // There is no BLENDI for byte vectors. We don't need to custom lower
1084 // some vselects for now.
1085 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
1087 // i8 and i16 vectors are custom , because the source register and source
1088 // source memory operand types are not the same width. f32 vectors are
1089 // custom since the immediate controlling the insert encodes additional
1091 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1092 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1093 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1094 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1096 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1097 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1098 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1099 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1101 // FIXME: these should be Legal but thats only for the case where
1102 // the index is constant. For now custom expand to deal with that.
1103 if (Subtarget->is64Bit()) {
1104 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1105 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1109 if (Subtarget->hasSSE2()) {
1110 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1111 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1113 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1114 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1116 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1117 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1119 // In the customized shift lowering, the legal cases in AVX2 will be
1121 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1122 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1124 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1125 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1127 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1130 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1131 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1132 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1133 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1134 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1135 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1136 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1138 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1139 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1140 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1142 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1143 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1144 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1145 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1146 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1147 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1148 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1149 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1150 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1151 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1152 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1153 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1155 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1156 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1157 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1158 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1159 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1160 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1161 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1162 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1163 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1164 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1165 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1166 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1168 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1169 // even though v8i16 is a legal type.
1170 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1171 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1172 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1174 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1175 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1176 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1178 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1179 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1181 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1183 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1184 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1186 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1187 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1189 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1190 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1192 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1193 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1194 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1195 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1197 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1198 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1199 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1201 setOperationAction(ISD::VSELECT, MVT::v4f64, Custom);
1202 setOperationAction(ISD::VSELECT, MVT::v4i64, Custom);
1203 setOperationAction(ISD::VSELECT, MVT::v8i32, Custom);
1204 setOperationAction(ISD::VSELECT, MVT::v8f32, Custom);
1206 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1207 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1208 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1209 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1210 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1211 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1212 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1213 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1214 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1215 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1216 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1217 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1219 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1220 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1221 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1222 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1223 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1224 setOperationAction(ISD::FMA, MVT::f32, Legal);
1225 setOperationAction(ISD::FMA, MVT::f64, Legal);
1228 if (Subtarget->hasInt256()) {
1229 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1230 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1231 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1232 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1234 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1235 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1236 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1237 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1239 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1240 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1241 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1242 // Don't lower v32i8 because there is no 128-bit byte mul
1244 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1245 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1246 setOperationAction(ISD::MULHU, MVT::v16i16, Legal);
1247 setOperationAction(ISD::MULHS, MVT::v16i16, Legal);
1249 setOperationAction(ISD::VSELECT, MVT::v16i16, Custom);
1250 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1252 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1253 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1254 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1255 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1257 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1258 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1259 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1260 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1262 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1263 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1264 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1265 // Don't lower v32i8 because there is no 128-bit byte mul
1268 // In the customized shift lowering, the legal cases in AVX2 will be
1270 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1271 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1273 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1274 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1276 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1278 // Custom lower several nodes for 256-bit types.
1279 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1280 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1281 MVT VT = (MVT::SimpleValueType)i;
1283 // Extract subvector is special because the value type
1284 // (result) is 128-bit but the source is 256-bit wide.
1285 if (VT.is128BitVector())
1286 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1288 // Do not attempt to custom lower other non-256-bit vectors
1289 if (!VT.is256BitVector())
1292 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1293 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1294 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1295 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1296 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1297 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1298 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1301 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1302 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1303 MVT VT = (MVT::SimpleValueType)i;
1305 // Do not attempt to promote non-256-bit vectors
1306 if (!VT.is256BitVector())
1309 setOperationAction(ISD::AND, VT, Promote);
1310 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1311 setOperationAction(ISD::OR, VT, Promote);
1312 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1313 setOperationAction(ISD::XOR, VT, Promote);
1314 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1315 setOperationAction(ISD::LOAD, VT, Promote);
1316 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1317 setOperationAction(ISD::SELECT, VT, Promote);
1318 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1322 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1323 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1324 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1325 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1326 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1328 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1329 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1330 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1332 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1333 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1334 setOperationAction(ISD::XOR, MVT::i1, Legal);
1335 setOperationAction(ISD::OR, MVT::i1, Legal);
1336 setOperationAction(ISD::AND, MVT::i1, Legal);
1337 setLoadExtAction(ISD::EXTLOAD, MVT::v8f32, Legal);
1338 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1339 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1340 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1341 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1342 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1344 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1345 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1346 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1347 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1348 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1349 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1351 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1352 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1353 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1354 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1355 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1356 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1357 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1358 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1360 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1361 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1362 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1363 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1364 if (Subtarget->is64Bit()) {
1365 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1366 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1367 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1368 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1370 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1371 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1372 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1373 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1374 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1375 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1376 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1377 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1378 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1379 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1381 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1382 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1383 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1384 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1385 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1386 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1387 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1388 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1389 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1390 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1391 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1392 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1393 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1395 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1396 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1397 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1398 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1399 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1400 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1402 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1403 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1405 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1407 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1408 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1409 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1410 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1411 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1412 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1413 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1414 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1415 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1417 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1418 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1420 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1421 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1423 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1425 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1426 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1428 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1429 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1431 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1432 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1434 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1435 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1436 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1437 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1438 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1439 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1441 if (Subtarget->hasCDI()) {
1442 setOperationAction(ISD::CTLZ, MVT::v8i64, Legal);
1443 setOperationAction(ISD::CTLZ, MVT::v16i32, Legal);
1446 // Custom lower several nodes.
1447 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1448 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1449 MVT VT = (MVT::SimpleValueType)i;
1451 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1452 // Extract subvector is special because the value type
1453 // (result) is 256/128-bit but the source is 512-bit wide.
1454 if (VT.is128BitVector() || VT.is256BitVector())
1455 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1457 if (VT.getVectorElementType() == MVT::i1)
1458 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1460 // Do not attempt to custom lower other non-512-bit vectors
1461 if (!VT.is512BitVector())
1464 if ( EltSize >= 32) {
1465 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1466 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1467 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1468 setOperationAction(ISD::VSELECT, VT, Legal);
1469 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1470 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1471 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1474 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1475 MVT VT = (MVT::SimpleValueType)i;
1477 // Do not attempt to promote non-256-bit vectors
1478 if (!VT.is512BitVector())
1481 setOperationAction(ISD::SELECT, VT, Promote);
1482 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1486 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1487 // of this type with custom code.
1488 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1489 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1490 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1494 // We want to custom lower some of our intrinsics.
1495 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1496 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1497 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1498 if (!Subtarget->is64Bit())
1499 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1501 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1502 // handle type legalization for these operations here.
1504 // FIXME: We really should do custom legalization for addition and
1505 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1506 // than generic legalization for 64-bit multiplication-with-overflow, though.
1507 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1508 // Add/Sub/Mul with overflow operations are custom lowered.
1510 setOperationAction(ISD::SADDO, VT, Custom);
1511 setOperationAction(ISD::UADDO, VT, Custom);
1512 setOperationAction(ISD::SSUBO, VT, Custom);
1513 setOperationAction(ISD::USUBO, VT, Custom);
1514 setOperationAction(ISD::SMULO, VT, Custom);
1515 setOperationAction(ISD::UMULO, VT, Custom);
1518 // There are no 8-bit 3-address imul/mul instructions
1519 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1520 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1522 if (!Subtarget->is64Bit()) {
1523 // These libcalls are not available in 32-bit.
1524 setLibcallName(RTLIB::SHL_I128, nullptr);
1525 setLibcallName(RTLIB::SRL_I128, nullptr);
1526 setLibcallName(RTLIB::SRA_I128, nullptr);
1529 // Combine sin / cos into one node or libcall if possible.
1530 if (Subtarget->hasSinCos()) {
1531 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1532 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1533 if (Subtarget->isTargetDarwin()) {
1534 // For MacOSX, we don't want to the normal expansion of a libcall to
1535 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1537 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1538 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1542 if (Subtarget->isTargetWin64()) {
1543 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1544 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1545 setOperationAction(ISD::SREM, MVT::i128, Custom);
1546 setOperationAction(ISD::UREM, MVT::i128, Custom);
1547 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1548 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1551 // We have target-specific dag combine patterns for the following nodes:
1552 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1553 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1554 setTargetDAGCombine(ISD::VSELECT);
1555 setTargetDAGCombine(ISD::SELECT);
1556 setTargetDAGCombine(ISD::SHL);
1557 setTargetDAGCombine(ISD::SRA);
1558 setTargetDAGCombine(ISD::SRL);
1559 setTargetDAGCombine(ISD::OR);
1560 setTargetDAGCombine(ISD::AND);
1561 setTargetDAGCombine(ISD::ADD);
1562 setTargetDAGCombine(ISD::FADD);
1563 setTargetDAGCombine(ISD::FSUB);
1564 setTargetDAGCombine(ISD::FMA);
1565 setTargetDAGCombine(ISD::SUB);
1566 setTargetDAGCombine(ISD::LOAD);
1567 setTargetDAGCombine(ISD::STORE);
1568 setTargetDAGCombine(ISD::ZERO_EXTEND);
1569 setTargetDAGCombine(ISD::ANY_EXTEND);
1570 setTargetDAGCombine(ISD::SIGN_EXTEND);
1571 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1572 setTargetDAGCombine(ISD::TRUNCATE);
1573 setTargetDAGCombine(ISD::SINT_TO_FP);
1574 setTargetDAGCombine(ISD::SETCC);
1575 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1576 setTargetDAGCombine(ISD::BUILD_VECTOR);
1577 if (Subtarget->is64Bit())
1578 setTargetDAGCombine(ISD::MUL);
1579 setTargetDAGCombine(ISD::XOR);
1581 computeRegisterProperties();
1583 // On Darwin, -Os means optimize for size without hurting performance,
1584 // do not reduce the limit.
1585 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1586 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1587 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1588 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1589 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1590 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1591 setPrefLoopAlignment(4); // 2^4 bytes.
1593 // Predictable cmov don't hurt on atom because it's in-order.
1594 PredictableSelectIsExpensive = !Subtarget->isAtom();
1596 setPrefFunctionAlignment(4); // 2^4 bytes.
1599 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1601 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1603 if (Subtarget->hasAVX512())
1604 switch(VT.getVectorNumElements()) {
1605 case 8: return MVT::v8i1;
1606 case 16: return MVT::v16i1;
1609 return VT.changeVectorElementTypeToInteger();
1612 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1613 /// the desired ByVal argument alignment.
1614 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1617 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1618 if (VTy->getBitWidth() == 128)
1620 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1621 unsigned EltAlign = 0;
1622 getMaxByValAlign(ATy->getElementType(), EltAlign);
1623 if (EltAlign > MaxAlign)
1624 MaxAlign = EltAlign;
1625 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1626 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1627 unsigned EltAlign = 0;
1628 getMaxByValAlign(STy->getElementType(i), EltAlign);
1629 if (EltAlign > MaxAlign)
1630 MaxAlign = EltAlign;
1637 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1638 /// function arguments in the caller parameter area. For X86, aggregates
1639 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1640 /// are at 4-byte boundaries.
1641 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1642 if (Subtarget->is64Bit()) {
1643 // Max of 8 and alignment of type.
1644 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1651 if (Subtarget->hasSSE1())
1652 getMaxByValAlign(Ty, Align);
1656 /// getOptimalMemOpType - Returns the target specific optimal type for load
1657 /// and store operations as a result of memset, memcpy, and memmove
1658 /// lowering. If DstAlign is zero that means it's safe to destination
1659 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1660 /// means there isn't a need to check it against alignment requirement,
1661 /// probably because the source does not need to be loaded. If 'IsMemset' is
1662 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1663 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1664 /// source is constant so it does not need to be loaded.
1665 /// It returns EVT::Other if the type should be determined using generic
1666 /// target-independent logic.
1668 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1669 unsigned DstAlign, unsigned SrcAlign,
1670 bool IsMemset, bool ZeroMemset,
1672 MachineFunction &MF) const {
1673 const Function *F = MF.getFunction();
1674 if ((!IsMemset || ZeroMemset) &&
1675 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1676 Attribute::NoImplicitFloat)) {
1678 (Subtarget->isUnalignedMemAccessFast() ||
1679 ((DstAlign == 0 || DstAlign >= 16) &&
1680 (SrcAlign == 0 || SrcAlign >= 16)))) {
1682 if (Subtarget->hasInt256())
1684 if (Subtarget->hasFp256())
1687 if (Subtarget->hasSSE2())
1689 if (Subtarget->hasSSE1())
1691 } else if (!MemcpyStrSrc && Size >= 8 &&
1692 !Subtarget->is64Bit() &&
1693 Subtarget->hasSSE2()) {
1694 // Do not use f64 to lower memcpy if source is string constant. It's
1695 // better to use i32 to avoid the loads.
1699 if (Subtarget->is64Bit() && Size >= 8)
1704 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1706 return X86ScalarSSEf32;
1707 else if (VT == MVT::f64)
1708 return X86ScalarSSEf64;
1713 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1717 *Fast = Subtarget->isUnalignedMemAccessFast();
1721 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1722 /// current function. The returned value is a member of the
1723 /// MachineJumpTableInfo::JTEntryKind enum.
1724 unsigned X86TargetLowering::getJumpTableEncoding() const {
1725 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1727 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1728 Subtarget->isPICStyleGOT())
1729 return MachineJumpTableInfo::EK_Custom32;
1731 // Otherwise, use the normal jump table encoding heuristics.
1732 return TargetLowering::getJumpTableEncoding();
1736 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1737 const MachineBasicBlock *MBB,
1738 unsigned uid,MCContext &Ctx) const{
1739 assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1740 Subtarget->isPICStyleGOT());
1741 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1743 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1744 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1747 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1749 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1750 SelectionDAG &DAG) const {
1751 if (!Subtarget->is64Bit())
1752 // This doesn't have SDLoc associated with it, but is not really the
1753 // same as a Register.
1754 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1758 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1759 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1761 const MCExpr *X86TargetLowering::
1762 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1763 MCContext &Ctx) const {
1764 // X86-64 uses RIP relative addressing based on the jump table label.
1765 if (Subtarget->isPICStyleRIPRel())
1766 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1768 // Otherwise, the reference is relative to the PIC base.
1769 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1772 // FIXME: Why this routine is here? Move to RegInfo!
1773 std::pair<const TargetRegisterClass*, uint8_t>
1774 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1775 const TargetRegisterClass *RRC = nullptr;
1777 switch (VT.SimpleTy) {
1779 return TargetLowering::findRepresentativeClass(VT);
1780 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1781 RRC = Subtarget->is64Bit() ?
1782 (const TargetRegisterClass*)&X86::GR64RegClass :
1783 (const TargetRegisterClass*)&X86::GR32RegClass;
1786 RRC = &X86::VR64RegClass;
1788 case MVT::f32: case MVT::f64:
1789 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1790 case MVT::v4f32: case MVT::v2f64:
1791 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1793 RRC = &X86::VR128RegClass;
1796 return std::make_pair(RRC, Cost);
1799 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1800 unsigned &Offset) const {
1801 if (!Subtarget->isTargetLinux())
1804 if (Subtarget->is64Bit()) {
1805 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1807 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1819 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1820 unsigned DestAS) const {
1821 assert(SrcAS != DestAS && "Expected different address spaces!");
1823 return SrcAS < 256 && DestAS < 256;
1826 //===----------------------------------------------------------------------===//
1827 // Return Value Calling Convention Implementation
1828 //===----------------------------------------------------------------------===//
1830 #include "X86GenCallingConv.inc"
1833 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1834 MachineFunction &MF, bool isVarArg,
1835 const SmallVectorImpl<ISD::OutputArg> &Outs,
1836 LLVMContext &Context) const {
1837 SmallVector<CCValAssign, 16> RVLocs;
1838 CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
1840 return CCInfo.CheckReturn(Outs, RetCC_X86);
1843 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1844 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1849 X86TargetLowering::LowerReturn(SDValue Chain,
1850 CallingConv::ID CallConv, bool isVarArg,
1851 const SmallVectorImpl<ISD::OutputArg> &Outs,
1852 const SmallVectorImpl<SDValue> &OutVals,
1853 SDLoc dl, SelectionDAG &DAG) const {
1854 MachineFunction &MF = DAG.getMachineFunction();
1855 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1857 SmallVector<CCValAssign, 16> RVLocs;
1858 CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
1859 RVLocs, *DAG.getContext());
1860 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1863 SmallVector<SDValue, 6> RetOps;
1864 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1865 // Operand #1 = Bytes To Pop
1866 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1869 // Copy the result values into the output registers.
1870 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1871 CCValAssign &VA = RVLocs[i];
1872 assert(VA.isRegLoc() && "Can only return in registers!");
1873 SDValue ValToCopy = OutVals[i];
1874 EVT ValVT = ValToCopy.getValueType();
1876 // Promote values to the appropriate types
1877 if (VA.getLocInfo() == CCValAssign::SExt)
1878 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1879 else if (VA.getLocInfo() == CCValAssign::ZExt)
1880 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1881 else if (VA.getLocInfo() == CCValAssign::AExt)
1882 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1883 else if (VA.getLocInfo() == CCValAssign::BCvt)
1884 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1886 assert(VA.getLocInfo() != CCValAssign::FPExt &&
1887 "Unexpected FP-extend for return value.");
1889 // If this is x86-64, and we disabled SSE, we can't return FP values,
1890 // or SSE or MMX vectors.
1891 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1892 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1893 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1894 report_fatal_error("SSE register return with SSE disabled");
1896 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1897 // llvm-gcc has never done it right and no one has noticed, so this
1898 // should be OK for now.
1899 if (ValVT == MVT::f64 &&
1900 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1901 report_fatal_error("SSE2 register return with SSE2 disabled");
1903 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1904 // the RET instruction and handled by the FP Stackifier.
1905 if (VA.getLocReg() == X86::ST0 ||
1906 VA.getLocReg() == X86::ST1) {
1907 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1908 // change the value to the FP stack register class.
1909 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1910 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1911 RetOps.push_back(ValToCopy);
1912 // Don't emit a copytoreg.
1916 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1917 // which is returned in RAX / RDX.
1918 if (Subtarget->is64Bit()) {
1919 if (ValVT == MVT::x86mmx) {
1920 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1921 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1922 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1924 // If we don't have SSE2 available, convert to v4f32 so the generated
1925 // register is legal.
1926 if (!Subtarget->hasSSE2())
1927 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1932 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1933 Flag = Chain.getValue(1);
1934 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1937 // The x86-64 ABIs require that for returning structs by value we copy
1938 // the sret argument into %rax/%eax (depending on ABI) for the return.
1939 // Win32 requires us to put the sret argument to %eax as well.
1940 // We saved the argument into a virtual register in the entry block,
1941 // so now we copy the value out and into %rax/%eax.
1942 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1943 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1944 MachineFunction &MF = DAG.getMachineFunction();
1945 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1946 unsigned Reg = FuncInfo->getSRetReturnReg();
1948 "SRetReturnReg should have been set in LowerFormalArguments().");
1949 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1952 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1953 X86::RAX : X86::EAX;
1954 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1955 Flag = Chain.getValue(1);
1957 // RAX/EAX now acts like a return value.
1958 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1961 RetOps[0] = Chain; // Update chain.
1963 // Add the flag if we have it.
1965 RetOps.push_back(Flag);
1967 return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
1970 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1971 if (N->getNumValues() != 1)
1973 if (!N->hasNUsesOfValue(1, 0))
1976 SDValue TCChain = Chain;
1977 SDNode *Copy = *N->use_begin();
1978 if (Copy->getOpcode() == ISD::CopyToReg) {
1979 // If the copy has a glue operand, we conservatively assume it isn't safe to
1980 // perform a tail call.
1981 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1983 TCChain = Copy->getOperand(0);
1984 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1987 bool HasRet = false;
1988 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1990 if (UI->getOpcode() != X86ISD::RET_FLAG)
2003 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
2004 ISD::NodeType ExtendKind) const {
2006 // TODO: Is this also valid on 32-bit?
2007 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2008 ReturnMVT = MVT::i8;
2010 ReturnMVT = MVT::i32;
2012 MVT MinVT = getRegisterType(ReturnMVT);
2013 return VT.bitsLT(MinVT) ? MinVT : VT;
2016 /// LowerCallResult - Lower the result values of a call into the
2017 /// appropriate copies out of appropriate physical registers.
2020 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2021 CallingConv::ID CallConv, bool isVarArg,
2022 const SmallVectorImpl<ISD::InputArg> &Ins,
2023 SDLoc dl, SelectionDAG &DAG,
2024 SmallVectorImpl<SDValue> &InVals) const {
2026 // Assign locations to each value returned by this call.
2027 SmallVector<CCValAssign, 16> RVLocs;
2028 bool Is64Bit = Subtarget->is64Bit();
2029 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2030 DAG.getTarget(), RVLocs, *DAG.getContext());
2031 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2033 // Copy all of the result registers out of their specified physreg.
2034 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2035 CCValAssign &VA = RVLocs[i];
2036 EVT CopyVT = VA.getValVT();
2038 // If this is x86-64, and we disabled SSE, we can't return FP values
2039 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2040 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2041 report_fatal_error("SSE register return with SSE disabled");
2046 // If this is a call to a function that returns an fp value on the floating
2047 // point stack, we must guarantee the value is popped from the stack, so
2048 // a CopyFromReg is not good enough - the copy instruction may be eliminated
2049 // if the return value is not used. We use the FpPOP_RETVAL instruction
2051 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2052 // If we prefer to use the value in xmm registers, copy it out as f80 and
2053 // use a truncate to move it from fp stack reg to xmm reg.
2054 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2055 SDValue Ops[] = { Chain, InFlag };
2056 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2057 MVT::Other, MVT::Glue, Ops), 1);
2058 Val = Chain.getValue(0);
2060 // Round the f80 to the right size, which also moves it to the appropriate
2062 if (CopyVT != VA.getValVT())
2063 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2064 // This truncation won't change the value.
2065 DAG.getIntPtrConstant(1));
2067 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2068 CopyVT, InFlag).getValue(1);
2069 Val = Chain.getValue(0);
2071 InFlag = Chain.getValue(2);
2072 InVals.push_back(Val);
2078 //===----------------------------------------------------------------------===//
2079 // C & StdCall & Fast Calling Convention implementation
2080 //===----------------------------------------------------------------------===//
2081 // StdCall calling convention seems to be standard for many Windows' API
2082 // routines and around. It differs from C calling convention just a little:
2083 // callee should clean up the stack, not caller. Symbols should be also
2084 // decorated in some fancy way :) It doesn't support any vector arguments.
2085 // For info on fast calling convention see Fast Calling Convention (tail call)
2086 // implementation LowerX86_32FastCCCallTo.
2088 /// CallIsStructReturn - Determines whether a call uses struct return
2090 enum StructReturnType {
2095 static StructReturnType
2096 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2098 return NotStructReturn;
2100 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2101 if (!Flags.isSRet())
2102 return NotStructReturn;
2103 if (Flags.isInReg())
2104 return RegStructReturn;
2105 return StackStructReturn;
2108 /// ArgsAreStructReturn - Determines whether a function uses struct
2109 /// return semantics.
2110 static StructReturnType
2111 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2113 return NotStructReturn;
2115 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2116 if (!Flags.isSRet())
2117 return NotStructReturn;
2118 if (Flags.isInReg())
2119 return RegStructReturn;
2120 return StackStructReturn;
2123 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2124 /// by "Src" to address "Dst" with size and alignment information specified by
2125 /// the specific parameter attribute. The copy will be passed as a byval
2126 /// function parameter.
2128 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2129 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2131 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2133 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2134 /*isVolatile*/false, /*AlwaysInline=*/true,
2135 MachinePointerInfo(), MachinePointerInfo());
2138 /// IsTailCallConvention - Return true if the calling convention is one that
2139 /// supports tail call optimization.
2140 static bool IsTailCallConvention(CallingConv::ID CC) {
2141 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2142 CC == CallingConv::HiPE);
2145 /// \brief Return true if the calling convention is a C calling convention.
2146 static bool IsCCallConvention(CallingConv::ID CC) {
2147 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2148 CC == CallingConv::X86_64_SysV);
2151 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2152 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2156 CallingConv::ID CalleeCC = CS.getCallingConv();
2157 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2163 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2164 /// a tailcall target by changing its ABI.
2165 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2166 bool GuaranteedTailCallOpt) {
2167 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2171 X86TargetLowering::LowerMemArgument(SDValue Chain,
2172 CallingConv::ID CallConv,
2173 const SmallVectorImpl<ISD::InputArg> &Ins,
2174 SDLoc dl, SelectionDAG &DAG,
2175 const CCValAssign &VA,
2176 MachineFrameInfo *MFI,
2178 // Create the nodes corresponding to a load from this parameter slot.
2179 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2180 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2181 CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2182 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2185 // If value is passed by pointer we have address passed instead of the value
2187 if (VA.getLocInfo() == CCValAssign::Indirect)
2188 ValVT = VA.getLocVT();
2190 ValVT = VA.getValVT();
2192 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2193 // changed with more analysis.
2194 // In case of tail call optimization mark all arguments mutable. Since they
2195 // could be overwritten by lowering of arguments in case of a tail call.
2196 if (Flags.isByVal()) {
2197 unsigned Bytes = Flags.getByValSize();
2198 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2199 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2200 return DAG.getFrameIndex(FI, getPointerTy());
2202 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2203 VA.getLocMemOffset(), isImmutable);
2204 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2205 return DAG.getLoad(ValVT, dl, Chain, FIN,
2206 MachinePointerInfo::getFixedStack(FI),
2207 false, false, false, 0);
2212 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2213 CallingConv::ID CallConv,
2215 const SmallVectorImpl<ISD::InputArg> &Ins,
2218 SmallVectorImpl<SDValue> &InVals)
2220 MachineFunction &MF = DAG.getMachineFunction();
2221 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2223 const Function* Fn = MF.getFunction();
2224 if (Fn->hasExternalLinkage() &&
2225 Subtarget->isTargetCygMing() &&
2226 Fn->getName() == "main")
2227 FuncInfo->setForceFramePointer(true);
2229 MachineFrameInfo *MFI = MF.getFrameInfo();
2230 bool Is64Bit = Subtarget->is64Bit();
2231 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2233 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2234 "Var args not supported with calling convention fastcc, ghc or hipe");
2236 // Assign locations to all of the incoming arguments.
2237 SmallVector<CCValAssign, 16> ArgLocs;
2238 CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
2239 ArgLocs, *DAG.getContext());
2241 // Allocate shadow area for Win64
2243 CCInfo.AllocateStack(32, 8);
2245 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2247 unsigned LastVal = ~0U;
2249 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2250 CCValAssign &VA = ArgLocs[i];
2251 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2253 assert(VA.getValNo() != LastVal &&
2254 "Don't support value assigned to multiple locs yet");
2256 LastVal = VA.getValNo();
2258 if (VA.isRegLoc()) {
2259 EVT RegVT = VA.getLocVT();
2260 const TargetRegisterClass *RC;
2261 if (RegVT == MVT::i32)
2262 RC = &X86::GR32RegClass;
2263 else if (Is64Bit && RegVT == MVT::i64)
2264 RC = &X86::GR64RegClass;
2265 else if (RegVT == MVT::f32)
2266 RC = &X86::FR32RegClass;
2267 else if (RegVT == MVT::f64)
2268 RC = &X86::FR64RegClass;
2269 else if (RegVT.is512BitVector())
2270 RC = &X86::VR512RegClass;
2271 else if (RegVT.is256BitVector())
2272 RC = &X86::VR256RegClass;
2273 else if (RegVT.is128BitVector())
2274 RC = &X86::VR128RegClass;
2275 else if (RegVT == MVT::x86mmx)
2276 RC = &X86::VR64RegClass;
2277 else if (RegVT == MVT::i1)
2278 RC = &X86::VK1RegClass;
2279 else if (RegVT == MVT::v8i1)
2280 RC = &X86::VK8RegClass;
2281 else if (RegVT == MVT::v16i1)
2282 RC = &X86::VK16RegClass;
2284 llvm_unreachable("Unknown argument type!");
2286 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2287 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2289 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2290 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2292 if (VA.getLocInfo() == CCValAssign::SExt)
2293 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2294 DAG.getValueType(VA.getValVT()));
2295 else if (VA.getLocInfo() == CCValAssign::ZExt)
2296 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2297 DAG.getValueType(VA.getValVT()));
2298 else if (VA.getLocInfo() == CCValAssign::BCvt)
2299 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2301 if (VA.isExtInLoc()) {
2302 // Handle MMX values passed in XMM regs.
2303 if (RegVT.isVector())
2304 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2306 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2309 assert(VA.isMemLoc());
2310 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2313 // If value is passed via pointer - do a load.
2314 if (VA.getLocInfo() == CCValAssign::Indirect)
2315 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2316 MachinePointerInfo(), false, false, false, 0);
2318 InVals.push_back(ArgValue);
2321 if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2322 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2323 // The x86-64 ABIs require that for returning structs by value we copy
2324 // the sret argument into %rax/%eax (depending on ABI) for the return.
2325 // Win32 requires us to put the sret argument to %eax as well.
2326 // Save the argument into a virtual register so that we can access it
2327 // from the return points.
2328 if (Ins[i].Flags.isSRet()) {
2329 unsigned Reg = FuncInfo->getSRetReturnReg();
2331 MVT PtrTy = getPointerTy();
2332 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2333 FuncInfo->setSRetReturnReg(Reg);
2335 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2336 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2342 unsigned StackSize = CCInfo.getNextStackOffset();
2343 // Align stack specially for tail calls.
2344 if (FuncIsMadeTailCallSafe(CallConv,
2345 MF.getTarget().Options.GuaranteedTailCallOpt))
2346 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2348 // If the function takes variable number of arguments, make a frame index for
2349 // the start of the first vararg value... for expansion of llvm.va_start.
2351 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2352 CallConv != CallingConv::X86_ThisCall)) {
2353 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2356 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2358 // FIXME: We should really autogenerate these arrays
2359 static const MCPhysReg GPR64ArgRegsWin64[] = {
2360 X86::RCX, X86::RDX, X86::R8, X86::R9
2362 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2363 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2365 static const MCPhysReg XMMArgRegs64Bit[] = {
2366 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2367 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2369 const MCPhysReg *GPR64ArgRegs;
2370 unsigned NumXMMRegs = 0;
2373 // The XMM registers which might contain var arg parameters are shadowed
2374 // in their paired GPR. So we only need to save the GPR to their home
2376 TotalNumIntRegs = 4;
2377 GPR64ArgRegs = GPR64ArgRegsWin64;
2379 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2380 GPR64ArgRegs = GPR64ArgRegs64Bit;
2382 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2385 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2388 bool NoImplicitFloatOps = Fn->getAttributes().
2389 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2390 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2391 "SSE register cannot be used when SSE is disabled!");
2392 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2393 NoImplicitFloatOps) &&
2394 "SSE register cannot be used when SSE is disabled!");
2395 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2396 !Subtarget->hasSSE1())
2397 // Kernel mode asks for SSE to be disabled, so don't push them
2399 TotalNumXMMRegs = 0;
2402 const TargetFrameLowering &TFI = *MF.getTarget().getFrameLowering();
2403 // Get to the caller-allocated home save location. Add 8 to account
2404 // for the return address.
2405 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2406 FuncInfo->setRegSaveFrameIndex(
2407 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2408 // Fixup to set vararg frame on shadow area (4 x i64).
2410 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2412 // For X86-64, if there are vararg parameters that are passed via
2413 // registers, then we must store them to their spots on the stack so
2414 // they may be loaded by deferencing the result of va_next.
2415 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2416 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2417 FuncInfo->setRegSaveFrameIndex(
2418 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2422 // Store the integer parameter registers.
2423 SmallVector<SDValue, 8> MemOps;
2424 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2426 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2427 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2428 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2429 DAG.getIntPtrConstant(Offset));
2430 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2431 &X86::GR64RegClass);
2432 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2434 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2435 MachinePointerInfo::getFixedStack(
2436 FuncInfo->getRegSaveFrameIndex(), Offset),
2438 MemOps.push_back(Store);
2442 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2443 // Now store the XMM (fp + vector) parameter registers.
2444 SmallVector<SDValue, 11> SaveXMMOps;
2445 SaveXMMOps.push_back(Chain);
2447 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2448 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2449 SaveXMMOps.push_back(ALVal);
2451 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2452 FuncInfo->getRegSaveFrameIndex()));
2453 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2454 FuncInfo->getVarArgsFPOffset()));
2456 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2457 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2458 &X86::VR128RegClass);
2459 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2460 SaveXMMOps.push_back(Val);
2462 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2463 MVT::Other, SaveXMMOps));
2466 if (!MemOps.empty())
2467 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2471 // Some CCs need callee pop.
2472 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2473 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2474 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2476 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2477 // If this is an sret function, the return should pop the hidden pointer.
2478 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2479 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2480 argsAreStructReturn(Ins) == StackStructReturn)
2481 FuncInfo->setBytesToPopOnReturn(4);
2485 // RegSaveFrameIndex is X86-64 only.
2486 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2487 if (CallConv == CallingConv::X86_FastCall ||
2488 CallConv == CallingConv::X86_ThisCall)
2489 // fastcc functions can't have varargs.
2490 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2493 FuncInfo->setArgumentStackSize(StackSize);
2499 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2500 SDValue StackPtr, SDValue Arg,
2501 SDLoc dl, SelectionDAG &DAG,
2502 const CCValAssign &VA,
2503 ISD::ArgFlagsTy Flags) const {
2504 unsigned LocMemOffset = VA.getLocMemOffset();
2505 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2506 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2507 if (Flags.isByVal())
2508 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2510 return DAG.getStore(Chain, dl, Arg, PtrOff,
2511 MachinePointerInfo::getStack(LocMemOffset),
2515 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2516 /// optimization is performed and it is required.
2518 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2519 SDValue &OutRetAddr, SDValue Chain,
2520 bool IsTailCall, bool Is64Bit,
2521 int FPDiff, SDLoc dl) const {
2522 // Adjust the Return address stack slot.
2523 EVT VT = getPointerTy();
2524 OutRetAddr = getReturnAddressFrameIndex(DAG);
2526 // Load the "old" Return address.
2527 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2528 false, false, false, 0);
2529 return SDValue(OutRetAddr.getNode(), 1);
2532 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2533 /// optimization is performed and it is required (FPDiff!=0).
2534 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2535 SDValue Chain, SDValue RetAddrFrIdx,
2536 EVT PtrVT, unsigned SlotSize,
2537 int FPDiff, SDLoc dl) {
2538 // Store the return address to the appropriate stack slot.
2539 if (!FPDiff) return Chain;
2540 // Calculate the new stack slot for the return address.
2541 int NewReturnAddrFI =
2542 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2544 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2545 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2546 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2552 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2553 SmallVectorImpl<SDValue> &InVals) const {
2554 SelectionDAG &DAG = CLI.DAG;
2556 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2557 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2558 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2559 SDValue Chain = CLI.Chain;
2560 SDValue Callee = CLI.Callee;
2561 CallingConv::ID CallConv = CLI.CallConv;
2562 bool &isTailCall = CLI.IsTailCall;
2563 bool isVarArg = CLI.IsVarArg;
2565 MachineFunction &MF = DAG.getMachineFunction();
2566 bool Is64Bit = Subtarget->is64Bit();
2567 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2568 StructReturnType SR = callIsStructReturn(Outs);
2569 bool IsSibcall = false;
2571 if (MF.getTarget().Options.DisableTailCalls)
2574 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2576 // Force this to be a tail call. The verifier rules are enough to ensure
2577 // that we can lower this successfully without moving the return address
2580 } else if (isTailCall) {
2581 // Check if it's really possible to do a tail call.
2582 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2583 isVarArg, SR != NotStructReturn,
2584 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2585 Outs, OutVals, Ins, DAG);
2587 // Sibcalls are automatically detected tailcalls which do not require
2589 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2596 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2597 "Var args not supported with calling convention fastcc, ghc or hipe");
2599 // Analyze operands of the call, assigning locations to each operand.
2600 SmallVector<CCValAssign, 16> ArgLocs;
2601 CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
2602 ArgLocs, *DAG.getContext());
2604 // Allocate shadow area for Win64
2606 CCInfo.AllocateStack(32, 8);
2608 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2610 // Get a count of how many bytes are to be pushed on the stack.
2611 unsigned NumBytes = CCInfo.getNextStackOffset();
2613 // This is a sibcall. The memory operands are available in caller's
2614 // own caller's stack.
2616 else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2617 IsTailCallConvention(CallConv))
2618 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2621 if (isTailCall && !IsSibcall && !IsMustTail) {
2622 // Lower arguments at fp - stackoffset + fpdiff.
2623 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2624 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2626 FPDiff = NumBytesCallerPushed - NumBytes;
2628 // Set the delta of movement of the returnaddr stackslot.
2629 // But only set if delta is greater than previous delta.
2630 if (FPDiff < X86Info->getTCReturnAddrDelta())
2631 X86Info->setTCReturnAddrDelta(FPDiff);
2634 unsigned NumBytesToPush = NumBytes;
2635 unsigned NumBytesToPop = NumBytes;
2637 // If we have an inalloca argument, all stack space has already been allocated
2638 // for us and be right at the top of the stack. We don't support multiple
2639 // arguments passed in memory when using inalloca.
2640 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2642 assert(ArgLocs.back().getLocMemOffset() == 0 &&
2643 "an inalloca argument must be the only memory argument");
2647 Chain = DAG.getCALLSEQ_START(
2648 Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2650 SDValue RetAddrFrIdx;
2651 // Load return address for tail calls.
2652 if (isTailCall && FPDiff)
2653 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2654 Is64Bit, FPDiff, dl);
2656 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2657 SmallVector<SDValue, 8> MemOpChains;
2660 // Walk the register/memloc assignments, inserting copies/loads. In the case
2661 // of tail call optimization arguments are handle later.
2662 const X86RegisterInfo *RegInfo =
2663 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
2664 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2665 // Skip inalloca arguments, they have already been written.
2666 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2667 if (Flags.isInAlloca())
2670 CCValAssign &VA = ArgLocs[i];
2671 EVT RegVT = VA.getLocVT();
2672 SDValue Arg = OutVals[i];
2673 bool isByVal = Flags.isByVal();
2675 // Promote the value if needed.
2676 switch (VA.getLocInfo()) {
2677 default: llvm_unreachable("Unknown loc info!");
2678 case CCValAssign::Full: break;
2679 case CCValAssign::SExt:
2680 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2682 case CCValAssign::ZExt:
2683 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2685 case CCValAssign::AExt:
2686 if (RegVT.is128BitVector()) {
2687 // Special case: passing MMX values in XMM registers.
2688 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2689 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2690 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2692 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2694 case CCValAssign::BCvt:
2695 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2697 case CCValAssign::Indirect: {
2698 // Store the argument.
2699 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2700 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2701 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2702 MachinePointerInfo::getFixedStack(FI),
2709 if (VA.isRegLoc()) {
2710 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2711 if (isVarArg && IsWin64) {
2712 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2713 // shadow reg if callee is a varargs function.
2714 unsigned ShadowReg = 0;
2715 switch (VA.getLocReg()) {
2716 case X86::XMM0: ShadowReg = X86::RCX; break;
2717 case X86::XMM1: ShadowReg = X86::RDX; break;
2718 case X86::XMM2: ShadowReg = X86::R8; break;
2719 case X86::XMM3: ShadowReg = X86::R9; break;
2722 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2724 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2725 assert(VA.isMemLoc());
2726 if (!StackPtr.getNode())
2727 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2729 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2730 dl, DAG, VA, Flags));
2734 if (!MemOpChains.empty())
2735 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2737 if (Subtarget->isPICStyleGOT()) {
2738 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2741 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2742 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2744 // If we are tail calling and generating PIC/GOT style code load the
2745 // address of the callee into ECX. The value in ecx is used as target of
2746 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2747 // for tail calls on PIC/GOT architectures. Normally we would just put the
2748 // address of GOT into ebx and then call target@PLT. But for tail calls
2749 // ebx would be restored (since ebx is callee saved) before jumping to the
2752 // Note: The actual moving to ECX is done further down.
2753 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2754 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2755 !G->getGlobal()->hasProtectedVisibility())
2756 Callee = LowerGlobalAddress(Callee, DAG);
2757 else if (isa<ExternalSymbolSDNode>(Callee))
2758 Callee = LowerExternalSymbol(Callee, DAG);
2762 if (Is64Bit && isVarArg && !IsWin64) {
2763 // From AMD64 ABI document:
2764 // For calls that may call functions that use varargs or stdargs
2765 // (prototype-less calls or calls to functions containing ellipsis (...) in
2766 // the declaration) %al is used as hidden argument to specify the number
2767 // of SSE registers used. The contents of %al do not need to match exactly
2768 // the number of registers, but must be an ubound on the number of SSE
2769 // registers used and is in the range 0 - 8 inclusive.
2771 // Count the number of XMM registers allocated.
2772 static const MCPhysReg XMMArgRegs[] = {
2773 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2774 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2776 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2777 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2778 && "SSE registers cannot be used when SSE is disabled");
2780 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2781 DAG.getConstant(NumXMMRegs, MVT::i8)));
2784 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
2785 // don't need this because the eligibility check rejects calls that require
2786 // shuffling arguments passed in memory.
2787 if (!IsSibcall && isTailCall) {
2788 // Force all the incoming stack arguments to be loaded from the stack
2789 // before any new outgoing arguments are stored to the stack, because the
2790 // outgoing stack slots may alias the incoming argument stack slots, and
2791 // the alias isn't otherwise explicit. This is slightly more conservative
2792 // than necessary, because it means that each store effectively depends
2793 // on every argument instead of just those arguments it would clobber.
2794 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2796 SmallVector<SDValue, 8> MemOpChains2;
2799 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2800 CCValAssign &VA = ArgLocs[i];
2803 assert(VA.isMemLoc());
2804 SDValue Arg = OutVals[i];
2805 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2806 // Skip inalloca arguments. They don't require any work.
2807 if (Flags.isInAlloca())
2809 // Create frame index.
2810 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2811 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2812 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2813 FIN = DAG.getFrameIndex(FI, getPointerTy());
2815 if (Flags.isByVal()) {
2816 // Copy relative to framepointer.
2817 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2818 if (!StackPtr.getNode())
2819 StackPtr = DAG.getCopyFromReg(Chain, dl,
2820 RegInfo->getStackRegister(),
2822 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2824 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2828 // Store relative to framepointer.
2829 MemOpChains2.push_back(
2830 DAG.getStore(ArgChain, dl, Arg, FIN,
2831 MachinePointerInfo::getFixedStack(FI),
2836 if (!MemOpChains2.empty())
2837 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2839 // Store the return address to the appropriate stack slot.
2840 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2841 getPointerTy(), RegInfo->getSlotSize(),
2845 // Build a sequence of copy-to-reg nodes chained together with token chain
2846 // and flag operands which copy the outgoing args into registers.
2848 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2849 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2850 RegsToPass[i].second, InFlag);
2851 InFlag = Chain.getValue(1);
2854 if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
2855 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2856 // In the 64-bit large code model, we have to make all calls
2857 // through a register, since the call instruction's 32-bit
2858 // pc-relative offset may not be large enough to hold the whole
2860 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2861 // If the callee is a GlobalAddress node (quite common, every direct call
2862 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2865 // We should use extra load for direct calls to dllimported functions in
2867 const GlobalValue *GV = G->getGlobal();
2868 if (!GV->hasDLLImportStorageClass()) {
2869 unsigned char OpFlags = 0;
2870 bool ExtraLoad = false;
2871 unsigned WrapperKind = ISD::DELETED_NODE;
2873 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2874 // external symbols most go through the PLT in PIC mode. If the symbol
2875 // has hidden or protected visibility, or if it is static or local, then
2876 // we don't need to use the PLT - we can directly call it.
2877 if (Subtarget->isTargetELF() &&
2878 DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
2879 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2880 OpFlags = X86II::MO_PLT;
2881 } else if (Subtarget->isPICStyleStubAny() &&
2882 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2883 (!Subtarget->getTargetTriple().isMacOSX() ||
2884 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2885 // PC-relative references to external symbols should go through $stub,
2886 // unless we're building with the leopard linker or later, which
2887 // automatically synthesizes these stubs.
2888 OpFlags = X86II::MO_DARWIN_STUB;
2889 } else if (Subtarget->isPICStyleRIPRel() &&
2890 isa<Function>(GV) &&
2891 cast<Function>(GV)->getAttributes().
2892 hasAttribute(AttributeSet::FunctionIndex,
2893 Attribute::NonLazyBind)) {
2894 // If the function is marked as non-lazy, generate an indirect call
2895 // which loads from the GOT directly. This avoids runtime overhead
2896 // at the cost of eager binding (and one extra byte of encoding).
2897 OpFlags = X86II::MO_GOTPCREL;
2898 WrapperKind = X86ISD::WrapperRIP;
2902 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2903 G->getOffset(), OpFlags);
2905 // Add a wrapper if needed.
2906 if (WrapperKind != ISD::DELETED_NODE)
2907 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2908 // Add extra indirection if needed.
2910 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2911 MachinePointerInfo::getGOT(),
2912 false, false, false, 0);
2914 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2915 unsigned char OpFlags = 0;
2917 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2918 // external symbols should go through the PLT.
2919 if (Subtarget->isTargetELF() &&
2920 DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
2921 OpFlags = X86II::MO_PLT;
2922 } else if (Subtarget->isPICStyleStubAny() &&
2923 (!Subtarget->getTargetTriple().isMacOSX() ||
2924 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2925 // PC-relative references to external symbols should go through $stub,
2926 // unless we're building with the leopard linker or later, which
2927 // automatically synthesizes these stubs.
2928 OpFlags = X86II::MO_DARWIN_STUB;
2931 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2935 // Returns a chain & a flag for retval copy to use.
2936 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2937 SmallVector<SDValue, 8> Ops;
2939 if (!IsSibcall && isTailCall) {
2940 Chain = DAG.getCALLSEQ_END(Chain,
2941 DAG.getIntPtrConstant(NumBytesToPop, true),
2942 DAG.getIntPtrConstant(0, true), InFlag, dl);
2943 InFlag = Chain.getValue(1);
2946 Ops.push_back(Chain);
2947 Ops.push_back(Callee);
2950 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2952 // Add argument registers to the end of the list so that they are known live
2954 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2955 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2956 RegsToPass[i].second.getValueType()));
2958 // Add a register mask operand representing the call-preserved registers.
2959 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
2960 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2961 assert(Mask && "Missing call preserved mask for calling convention");
2962 Ops.push_back(DAG.getRegisterMask(Mask));
2964 if (InFlag.getNode())
2965 Ops.push_back(InFlag);
2969 //// If this is the first return lowered for this function, add the regs
2970 //// to the liveout set for the function.
2971 // This isn't right, although it's probably harmless on x86; liveouts
2972 // should be computed from returns not tail calls. Consider a void
2973 // function making a tail call to a function returning int.
2974 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
2977 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
2978 InFlag = Chain.getValue(1);
2980 // Create the CALLSEQ_END node.
2981 unsigned NumBytesForCalleeToPop;
2982 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2983 DAG.getTarget().Options.GuaranteedTailCallOpt))
2984 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
2985 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2986 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2987 SR == StackStructReturn)
2988 // If this is a call to a struct-return function, the callee
2989 // pops the hidden struct pointer, so we have to push it back.
2990 // This is common for Darwin/X86, Linux & Mingw32 targets.
2991 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2992 NumBytesForCalleeToPop = 4;
2994 NumBytesForCalleeToPop = 0; // Callee pops nothing.
2996 // Returns a flag for retval copy to use.
2998 Chain = DAG.getCALLSEQ_END(Chain,
2999 DAG.getIntPtrConstant(NumBytesToPop, true),
3000 DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3003 InFlag = Chain.getValue(1);
3006 // Handle result values, copying them out of physregs into vregs that we
3008 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3009 Ins, dl, DAG, InVals);
3012 //===----------------------------------------------------------------------===//
3013 // Fast Calling Convention (tail call) implementation
3014 //===----------------------------------------------------------------------===//
3016 // Like std call, callee cleans arguments, convention except that ECX is
3017 // reserved for storing the tail called function address. Only 2 registers are
3018 // free for argument passing (inreg). Tail call optimization is performed
3020 // * tailcallopt is enabled
3021 // * caller/callee are fastcc
3022 // On X86_64 architecture with GOT-style position independent code only local
3023 // (within module) calls are supported at the moment.
3024 // To keep the stack aligned according to platform abi the function
3025 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3026 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3027 // If a tail called function callee has more arguments than the caller the
3028 // caller needs to make sure that there is room to move the RETADDR to. This is
3029 // achieved by reserving an area the size of the argument delta right after the
3030 // original REtADDR, but before the saved framepointer or the spilled registers
3031 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3043 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3044 /// for a 16 byte align requirement.
3046 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3047 SelectionDAG& DAG) const {
3048 MachineFunction &MF = DAG.getMachineFunction();
3049 const TargetMachine &TM = MF.getTarget();
3050 const X86RegisterInfo *RegInfo =
3051 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3052 const TargetFrameLowering &TFI = *TM.getFrameLowering();
3053 unsigned StackAlignment = TFI.getStackAlignment();
3054 uint64_t AlignMask = StackAlignment - 1;
3055 int64_t Offset = StackSize;
3056 unsigned SlotSize = RegInfo->getSlotSize();
3057 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3058 // Number smaller than 12 so just add the difference.
3059 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3061 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3062 Offset = ((~AlignMask) & Offset) + StackAlignment +
3063 (StackAlignment-SlotSize);
3068 /// MatchingStackOffset - Return true if the given stack call argument is
3069 /// already available in the same position (relatively) of the caller's
3070 /// incoming argument stack.
3072 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3073 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3074 const X86InstrInfo *TII) {
3075 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3077 if (Arg.getOpcode() == ISD::CopyFromReg) {
3078 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3079 if (!TargetRegisterInfo::isVirtualRegister(VR))
3081 MachineInstr *Def = MRI->getVRegDef(VR);
3084 if (!Flags.isByVal()) {
3085 if (!TII->isLoadFromStackSlot(Def, FI))
3088 unsigned Opcode = Def->getOpcode();
3089 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3090 Def->getOperand(1).isFI()) {
3091 FI = Def->getOperand(1).getIndex();
3092 Bytes = Flags.getByValSize();
3096 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3097 if (Flags.isByVal())
3098 // ByVal argument is passed in as a pointer but it's now being
3099 // dereferenced. e.g.
3100 // define @foo(%struct.X* %A) {
3101 // tail call @bar(%struct.X* byval %A)
3104 SDValue Ptr = Ld->getBasePtr();
3105 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3108 FI = FINode->getIndex();
3109 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3110 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3111 FI = FINode->getIndex();
3112 Bytes = Flags.getByValSize();
3116 assert(FI != INT_MAX);
3117 if (!MFI->isFixedObjectIndex(FI))
3119 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3122 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3123 /// for tail call optimization. Targets which want to do tail call
3124 /// optimization should implement this function.
3126 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3127 CallingConv::ID CalleeCC,
3129 bool isCalleeStructRet,
3130 bool isCallerStructRet,
3132 const SmallVectorImpl<ISD::OutputArg> &Outs,
3133 const SmallVectorImpl<SDValue> &OutVals,
3134 const SmallVectorImpl<ISD::InputArg> &Ins,
3135 SelectionDAG &DAG) const {
3136 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3139 // If -tailcallopt is specified, make fastcc functions tail-callable.
3140 const MachineFunction &MF = DAG.getMachineFunction();
3141 const Function *CallerF = MF.getFunction();
3143 // If the function return type is x86_fp80 and the callee return type is not,
3144 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3145 // perform a tailcall optimization here.
3146 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3149 CallingConv::ID CallerCC = CallerF->getCallingConv();
3150 bool CCMatch = CallerCC == CalleeCC;
3151 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3152 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3154 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3155 if (IsTailCallConvention(CalleeCC) && CCMatch)
3160 // Look for obvious safe cases to perform tail call optimization that do not
3161 // require ABI changes. This is what gcc calls sibcall.
3163 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3164 // emit a special epilogue.
3165 const X86RegisterInfo *RegInfo =
3166 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
3167 if (RegInfo->needsStackRealignment(MF))
3170 // Also avoid sibcall optimization if either caller or callee uses struct
3171 // return semantics.
3172 if (isCalleeStructRet || isCallerStructRet)
3175 // An stdcall/thiscall caller is expected to clean up its arguments; the
3176 // callee isn't going to do that.
3177 // FIXME: this is more restrictive than needed. We could produce a tailcall
3178 // when the stack adjustment matches. For example, with a thiscall that takes
3179 // only one argument.
3180 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3181 CallerCC == CallingConv::X86_ThisCall))
3184 // Do not sibcall optimize vararg calls unless all arguments are passed via
3186 if (isVarArg && !Outs.empty()) {
3188 // Optimizing for varargs on Win64 is unlikely to be safe without
3189 // additional testing.
3190 if (IsCalleeWin64 || IsCallerWin64)
3193 SmallVector<CCValAssign, 16> ArgLocs;
3194 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3195 DAG.getTarget(), ArgLocs, *DAG.getContext());
3197 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3198 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3199 if (!ArgLocs[i].isRegLoc())
3203 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3204 // stack. Therefore, if it's not used by the call it is not safe to optimize
3205 // this into a sibcall.
3206 bool Unused = false;
3207 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3214 SmallVector<CCValAssign, 16> RVLocs;
3215 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3216 DAG.getTarget(), RVLocs, *DAG.getContext());
3217 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3218 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3219 CCValAssign &VA = RVLocs[i];
3220 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3225 // If the calling conventions do not match, then we'd better make sure the
3226 // results are returned in the same way as what the caller expects.
3228 SmallVector<CCValAssign, 16> RVLocs1;
3229 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3230 DAG.getTarget(), RVLocs1, *DAG.getContext());
3231 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3233 SmallVector<CCValAssign, 16> RVLocs2;
3234 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3235 DAG.getTarget(), RVLocs2, *DAG.getContext());
3236 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3238 if (RVLocs1.size() != RVLocs2.size())
3240 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3241 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3243 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3245 if (RVLocs1[i].isRegLoc()) {
3246 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3249 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3255 // If the callee takes no arguments then go on to check the results of the
3257 if (!Outs.empty()) {
3258 // Check if stack adjustment is needed. For now, do not do this if any
3259 // argument is passed on the stack.
3260 SmallVector<CCValAssign, 16> ArgLocs;
3261 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3262 DAG.getTarget(), ArgLocs, *DAG.getContext());
3264 // Allocate shadow area for Win64
3266 CCInfo.AllocateStack(32, 8);
3268 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3269 if (CCInfo.getNextStackOffset()) {
3270 MachineFunction &MF = DAG.getMachineFunction();
3271 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3274 // Check if the arguments are already laid out in the right way as
3275 // the caller's fixed stack objects.
3276 MachineFrameInfo *MFI = MF.getFrameInfo();
3277 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3278 const X86InstrInfo *TII =
3279 static_cast<const X86InstrInfo *>(DAG.getTarget().getInstrInfo());
3280 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3281 CCValAssign &VA = ArgLocs[i];
3282 SDValue Arg = OutVals[i];
3283 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3284 if (VA.getLocInfo() == CCValAssign::Indirect)
3286 if (!VA.isRegLoc()) {
3287 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3294 // If the tailcall address may be in a register, then make sure it's
3295 // possible to register allocate for it. In 32-bit, the call address can
3296 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3297 // callee-saved registers are restored. These happen to be the same
3298 // registers used to pass 'inreg' arguments so watch out for those.
3299 if (!Subtarget->is64Bit() &&
3300 ((!isa<GlobalAddressSDNode>(Callee) &&
3301 !isa<ExternalSymbolSDNode>(Callee)) ||
3302 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3303 unsigned NumInRegs = 0;
3304 // In PIC we need an extra register to formulate the address computation
3306 unsigned MaxInRegs =
3307 (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3309 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3310 CCValAssign &VA = ArgLocs[i];
3313 unsigned Reg = VA.getLocReg();
3316 case X86::EAX: case X86::EDX: case X86::ECX:
3317 if (++NumInRegs == MaxInRegs)
3329 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3330 const TargetLibraryInfo *libInfo) const {
3331 return X86::createFastISel(funcInfo, libInfo);
3334 //===----------------------------------------------------------------------===//
3335 // Other Lowering Hooks
3336 //===----------------------------------------------------------------------===//
3338 static bool MayFoldLoad(SDValue Op) {
3339 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3342 static bool MayFoldIntoStore(SDValue Op) {
3343 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3346 static bool isTargetShuffle(unsigned Opcode) {
3348 default: return false;
3349 case X86ISD::PSHUFD:
3350 case X86ISD::PSHUFHW:
3351 case X86ISD::PSHUFLW:
3353 case X86ISD::PALIGNR:
3354 case X86ISD::MOVLHPS:
3355 case X86ISD::MOVLHPD:
3356 case X86ISD::MOVHLPS:
3357 case X86ISD::MOVLPS:
3358 case X86ISD::MOVLPD:
3359 case X86ISD::MOVSHDUP:
3360 case X86ISD::MOVSLDUP:
3361 case X86ISD::MOVDDUP:
3364 case X86ISD::UNPCKL:
3365 case X86ISD::UNPCKH:
3366 case X86ISD::VPERMILP:
3367 case X86ISD::VPERM2X128:
3368 case X86ISD::VPERMI:
3373 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3374 SDValue V1, SelectionDAG &DAG) {
3376 default: llvm_unreachable("Unknown x86 shuffle node");
3377 case X86ISD::MOVSHDUP:
3378 case X86ISD::MOVSLDUP:
3379 case X86ISD::MOVDDUP:
3380 return DAG.getNode(Opc, dl, VT, V1);
3384 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3385 SDValue V1, unsigned TargetMask,
3386 SelectionDAG &DAG) {
3388 default: llvm_unreachable("Unknown x86 shuffle node");
3389 case X86ISD::PSHUFD:
3390 case X86ISD::PSHUFHW:
3391 case X86ISD::PSHUFLW:
3392 case X86ISD::VPERMILP:
3393 case X86ISD::VPERMI:
3394 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3398 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3399 SDValue V1, SDValue V2, unsigned TargetMask,
3400 SelectionDAG &DAG) {
3402 default: llvm_unreachable("Unknown x86 shuffle node");
3403 case X86ISD::PALIGNR:
3405 case X86ISD::VPERM2X128:
3406 return DAG.getNode(Opc, dl, VT, V1, V2,
3407 DAG.getConstant(TargetMask, MVT::i8));
3411 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3412 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3414 default: llvm_unreachable("Unknown x86 shuffle node");
3415 case X86ISD::MOVLHPS:
3416 case X86ISD::MOVLHPD:
3417 case X86ISD::MOVHLPS:
3418 case X86ISD::MOVLPS:
3419 case X86ISD::MOVLPD:
3422 case X86ISD::UNPCKL:
3423 case X86ISD::UNPCKH:
3424 return DAG.getNode(Opc, dl, VT, V1, V2);
3428 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3429 MachineFunction &MF = DAG.getMachineFunction();
3430 const X86RegisterInfo *RegInfo =
3431 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
3432 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3433 int ReturnAddrIndex = FuncInfo->getRAIndex();
3435 if (ReturnAddrIndex == 0) {
3436 // Set up a frame object for the return address.
3437 unsigned SlotSize = RegInfo->getSlotSize();
3438 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3441 FuncInfo->setRAIndex(ReturnAddrIndex);
3444 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3447 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3448 bool hasSymbolicDisplacement) {
3449 // Offset should fit into 32 bit immediate field.
3450 if (!isInt<32>(Offset))
3453 // If we don't have a symbolic displacement - we don't have any extra
3455 if (!hasSymbolicDisplacement)
3458 // FIXME: Some tweaks might be needed for medium code model.
3459 if (M != CodeModel::Small && M != CodeModel::Kernel)
3462 // For small code model we assume that latest object is 16MB before end of 31
3463 // bits boundary. We may also accept pretty large negative constants knowing
3464 // that all objects are in the positive half of address space.
3465 if (M == CodeModel::Small && Offset < 16*1024*1024)
3468 // For kernel code model we know that all object resist in the negative half
3469 // of 32bits address space. We may not accept negative offsets, since they may
3470 // be just off and we may accept pretty large positive ones.
3471 if (M == CodeModel::Kernel && Offset > 0)
3477 /// isCalleePop - Determines whether the callee is required to pop its
3478 /// own arguments. Callee pop is necessary to support tail calls.
3479 bool X86::isCalleePop(CallingConv::ID CallingConv,
3480 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3484 switch (CallingConv) {
3487 case CallingConv::X86_StdCall:
3489 case CallingConv::X86_FastCall:
3491 case CallingConv::X86_ThisCall:
3493 case CallingConv::Fast:
3495 case CallingConv::GHC:
3497 case CallingConv::HiPE:
3502 /// \brief Return true if the condition is an unsigned comparison operation.
3503 static bool isX86CCUnsigned(unsigned X86CC) {
3505 default: llvm_unreachable("Invalid integer condition!");
3506 case X86::COND_E: return true;
3507 case X86::COND_G: return false;
3508 case X86::COND_GE: return false;
3509 case X86::COND_L: return false;
3510 case X86::COND_LE: return false;
3511 case X86::COND_NE: return true;
3512 case X86::COND_B: return true;
3513 case X86::COND_A: return true;
3514 case X86::COND_BE: return true;
3515 case X86::COND_AE: return true;
3517 llvm_unreachable("covered switch fell through?!");
3520 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3521 /// specific condition code, returning the condition code and the LHS/RHS of the
3522 /// comparison to make.
3523 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3524 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3526 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3527 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3528 // X > -1 -> X == 0, jump !sign.
3529 RHS = DAG.getConstant(0, RHS.getValueType());
3530 return X86::COND_NS;
3532 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3533 // X < 0 -> X == 0, jump on sign.
3536 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3538 RHS = DAG.getConstant(0, RHS.getValueType());
3539 return X86::COND_LE;
3543 switch (SetCCOpcode) {
3544 default: llvm_unreachable("Invalid integer condition!");
3545 case ISD::SETEQ: return X86::COND_E;
3546 case ISD::SETGT: return X86::COND_G;
3547 case ISD::SETGE: return X86::COND_GE;
3548 case ISD::SETLT: return X86::COND_L;
3549 case ISD::SETLE: return X86::COND_LE;
3550 case ISD::SETNE: return X86::COND_NE;
3551 case ISD::SETULT: return X86::COND_B;
3552 case ISD::SETUGT: return X86::COND_A;
3553 case ISD::SETULE: return X86::COND_BE;
3554 case ISD::SETUGE: return X86::COND_AE;
3558 // First determine if it is required or is profitable to flip the operands.
3560 // If LHS is a foldable load, but RHS is not, flip the condition.
3561 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3562 !ISD::isNON_EXTLoad(RHS.getNode())) {
3563 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3564 std::swap(LHS, RHS);
3567 switch (SetCCOpcode) {
3573 std::swap(LHS, RHS);
3577 // On a floating point condition, the flags are set as follows:
3579 // 0 | 0 | 0 | X > Y
3580 // 0 | 0 | 1 | X < Y
3581 // 1 | 0 | 0 | X == Y
3582 // 1 | 1 | 1 | unordered
3583 switch (SetCCOpcode) {
3584 default: llvm_unreachable("Condcode should be pre-legalized away");
3586 case ISD::SETEQ: return X86::COND_E;
3587 case ISD::SETOLT: // flipped
3589 case ISD::SETGT: return X86::COND_A;
3590 case ISD::SETOLE: // flipped
3592 case ISD::SETGE: return X86::COND_AE;
3593 case ISD::SETUGT: // flipped
3595 case ISD::SETLT: return X86::COND_B;
3596 case ISD::SETUGE: // flipped
3598 case ISD::SETLE: return X86::COND_BE;
3600 case ISD::SETNE: return X86::COND_NE;
3601 case ISD::SETUO: return X86::COND_P;
3602 case ISD::SETO: return X86::COND_NP;
3604 case ISD::SETUNE: return X86::COND_INVALID;
3608 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3609 /// code. Current x86 isa includes the following FP cmov instructions:
3610 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3611 static bool hasFPCMov(unsigned X86CC) {
3627 /// isFPImmLegal - Returns true if the target can instruction select the
3628 /// specified FP immediate natively. If false, the legalizer will
3629 /// materialize the FP immediate as a load from a constant pool.
3630 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3631 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3632 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3638 /// \brief Returns true if it is beneficial to convert a load of a constant
3639 /// to just the constant itself.
3640 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3642 assert(Ty->isIntegerTy());
3644 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3645 if (BitSize == 0 || BitSize > 64)
3650 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3651 /// the specified range (L, H].
3652 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3653 return (Val < 0) || (Val >= Low && Val < Hi);
3656 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3657 /// specified value.
3658 static bool isUndefOrEqual(int Val, int CmpVal) {
3659 return (Val < 0 || Val == CmpVal);
3662 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3663 /// from position Pos and ending in Pos+Size, falls within the specified
3664 /// sequential range (L, L+Pos]. or is undef.
3665 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3666 unsigned Pos, unsigned Size, int Low) {
3667 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3668 if (!isUndefOrEqual(Mask[i], Low))
3673 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3674 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3675 /// the second operand.
3676 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3677 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3678 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3679 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3680 return (Mask[0] < 2 && Mask[1] < 2);
3684 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3685 /// is suitable for input to PSHUFHW.
3686 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3687 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3690 // Lower quadword copied in order or undef.
3691 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3694 // Upper quadword shuffled.
3695 for (unsigned i = 4; i != 8; ++i)
3696 if (!isUndefOrInRange(Mask[i], 4, 8))
3699 if (VT == MVT::v16i16) {
3700 // Lower quadword copied in order or undef.
3701 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3704 // Upper quadword shuffled.
3705 for (unsigned i = 12; i != 16; ++i)
3706 if (!isUndefOrInRange(Mask[i], 12, 16))
3713 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3714 /// is suitable for input to PSHUFLW.
3715 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3716 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3719 // Upper quadword copied in order.
3720 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3723 // Lower quadword shuffled.
3724 for (unsigned i = 0; i != 4; ++i)
3725 if (!isUndefOrInRange(Mask[i], 0, 4))
3728 if (VT == MVT::v16i16) {
3729 // Upper quadword copied in order.
3730 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3733 // Lower quadword shuffled.
3734 for (unsigned i = 8; i != 12; ++i)
3735 if (!isUndefOrInRange(Mask[i], 8, 12))
3742 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3743 /// is suitable for input to PALIGNR.
3744 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3745 const X86Subtarget *Subtarget) {
3746 if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3747 (VT.is256BitVector() && !Subtarget->hasInt256()))
3750 unsigned NumElts = VT.getVectorNumElements();
3751 unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3752 unsigned NumLaneElts = NumElts/NumLanes;
3754 // Do not handle 64-bit element shuffles with palignr.
3755 if (NumLaneElts == 2)
3758 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3760 for (i = 0; i != NumLaneElts; ++i) {
3765 // Lane is all undef, go to next lane
3766 if (i == NumLaneElts)
3769 int Start = Mask[i+l];
3771 // Make sure its in this lane in one of the sources
3772 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3773 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3776 // If not lane 0, then we must match lane 0
3777 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3780 // Correct second source to be contiguous with first source
3781 if (Start >= (int)NumElts)
3782 Start -= NumElts - NumLaneElts;
3784 // Make sure we're shifting in the right direction.
3785 if (Start <= (int)(i+l))
3790 // Check the rest of the elements to see if they are consecutive.
3791 for (++i; i != NumLaneElts; ++i) {
3792 int Idx = Mask[i+l];
3794 // Make sure its in this lane
3795 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3796 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3799 // If not lane 0, then we must match lane 0
3800 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3803 if (Idx >= (int)NumElts)
3804 Idx -= NumElts - NumLaneElts;
3806 if (!isUndefOrEqual(Idx, Start+i))
3815 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3816 /// the two vector operands have swapped position.
3817 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3818 unsigned NumElems) {
3819 for (unsigned i = 0; i != NumElems; ++i) {
3823 else if (idx < (int)NumElems)
3824 Mask[i] = idx + NumElems;
3826 Mask[i] = idx - NumElems;
3830 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3831 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3832 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3833 /// reverse of what x86 shuffles want.
3834 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3836 unsigned NumElems = VT.getVectorNumElements();
3837 unsigned NumLanes = VT.getSizeInBits()/128;
3838 unsigned NumLaneElems = NumElems/NumLanes;
3840 if (NumLaneElems != 2 && NumLaneElems != 4)
3843 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3844 bool symetricMaskRequired =
3845 (VT.getSizeInBits() >= 256) && (EltSize == 32);
3847 // VSHUFPSY divides the resulting vector into 4 chunks.
3848 // The sources are also splitted into 4 chunks, and each destination
3849 // chunk must come from a different source chunk.
3851 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3852 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3854 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3855 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3857 // VSHUFPDY divides the resulting vector into 4 chunks.
3858 // The sources are also splitted into 4 chunks, and each destination
3859 // chunk must come from a different source chunk.
3861 // SRC1 => X3 X2 X1 X0
3862 // SRC2 => Y3 Y2 Y1 Y0
3864 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3866 SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3867 unsigned HalfLaneElems = NumLaneElems/2;
3868 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3869 for (unsigned i = 0; i != NumLaneElems; ++i) {
3870 int Idx = Mask[i+l];
3871 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3872 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3874 // For VSHUFPSY, the mask of the second half must be the same as the
3875 // first but with the appropriate offsets. This works in the same way as
3876 // VPERMILPS works with masks.
3877 if (!symetricMaskRequired || Idx < 0)
3879 if (MaskVal[i] < 0) {
3880 MaskVal[i] = Idx - l;
3883 if ((signed)(Idx - l) != MaskVal[i])
3891 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3892 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3893 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3894 if (!VT.is128BitVector())
3897 unsigned NumElems = VT.getVectorNumElements();
3902 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3903 return isUndefOrEqual(Mask[0], 6) &&
3904 isUndefOrEqual(Mask[1], 7) &&
3905 isUndefOrEqual(Mask[2], 2) &&
3906 isUndefOrEqual(Mask[3], 3);
3909 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3910 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3912 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3913 if (!VT.is128BitVector())
3916 unsigned NumElems = VT.getVectorNumElements();
3921 return isUndefOrEqual(Mask[0], 2) &&
3922 isUndefOrEqual(Mask[1], 3) &&
3923 isUndefOrEqual(Mask[2], 2) &&
3924 isUndefOrEqual(Mask[3], 3);
3927 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3928 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3929 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3930 if (!VT.is128BitVector())
3933 unsigned NumElems = VT.getVectorNumElements();
3935 if (NumElems != 2 && NumElems != 4)
3938 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3939 if (!isUndefOrEqual(Mask[i], i + NumElems))
3942 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3943 if (!isUndefOrEqual(Mask[i], i))
3949 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3950 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3951 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3952 if (!VT.is128BitVector())
3955 unsigned NumElems = VT.getVectorNumElements();
3957 if (NumElems != 2 && NumElems != 4)
3960 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3961 if (!isUndefOrEqual(Mask[i], i))
3964 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3965 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3971 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
3972 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
3973 /// i. e: If all but one element come from the same vector.
3974 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
3975 // TODO: Deal with AVX's VINSERTPS
3976 if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
3979 unsigned CorrectPosV1 = 0;
3980 unsigned CorrectPosV2 = 0;
3981 for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
3982 if (Mask[i] == -1) {
3990 else if (Mask[i] == i + 4)
3994 if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
3995 // We have 3 elements (undefs count as elements from any vector) from one
3996 // vector, and one from another.
4003 // Some special combinations that can be optimized.
4006 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4007 SelectionDAG &DAG) {
4008 MVT VT = SVOp->getSimpleValueType(0);
4011 if (VT != MVT::v8i32 && VT != MVT::v8f32)
4014 ArrayRef<int> Mask = SVOp->getMask();
4016 // These are the special masks that may be optimized.
4017 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4018 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
4019 bool MatchEvenMask = true;
4020 bool MatchOddMask = true;
4021 for (int i=0; i<8; ++i) {
4022 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4023 MatchEvenMask = false;
4024 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4025 MatchOddMask = false;
4028 if (!MatchEvenMask && !MatchOddMask)
4031 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4033 SDValue Op0 = SVOp->getOperand(0);
4034 SDValue Op1 = SVOp->getOperand(1);
4036 if (MatchEvenMask) {
4037 // Shift the second operand right to 32 bits.
4038 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4039 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4041 // Shift the first operand left to 32 bits.
4042 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4043 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4045 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4046 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4049 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4050 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4051 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4052 bool HasInt256, bool V2IsSplat = false) {
4054 assert(VT.getSizeInBits() >= 128 &&
4055 "Unsupported vector type for unpckl");
4057 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4059 unsigned NumOf256BitLanes;
4060 unsigned NumElts = VT.getVectorNumElements();
4061 if (VT.is256BitVector()) {
4062 if (NumElts != 4 && NumElts != 8 &&
4063 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4066 NumOf256BitLanes = 1;
4067 } else if (VT.is512BitVector()) {
4068 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4069 "Unsupported vector type for unpckh");
4071 NumOf256BitLanes = 2;
4074 NumOf256BitLanes = 1;
4077 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4078 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4080 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4081 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4082 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4083 int BitI = Mask[l256*NumEltsInStride+l+i];
4084 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4085 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4087 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4089 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4097 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4098 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4099 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4100 bool HasInt256, bool V2IsSplat = false) {
4101 assert(VT.getSizeInBits() >= 128 &&
4102 "Unsupported vector type for unpckh");
4104 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4106 unsigned NumOf256BitLanes;
4107 unsigned NumElts = VT.getVectorNumElements();
4108 if (VT.is256BitVector()) {
4109 if (NumElts != 4 && NumElts != 8 &&
4110 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4113 NumOf256BitLanes = 1;
4114 } else if (VT.is512BitVector()) {
4115 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4116 "Unsupported vector type for unpckh");
4118 NumOf256BitLanes = 2;
4121 NumOf256BitLanes = 1;
4124 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4125 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4127 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4128 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4129 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4130 int BitI = Mask[l256*NumEltsInStride+l+i];
4131 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4132 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4134 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4136 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4144 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4145 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4147 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4148 unsigned NumElts = VT.getVectorNumElements();
4149 bool Is256BitVec = VT.is256BitVector();
4151 if (VT.is512BitVector())
4153 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4154 "Unsupported vector type for unpckh");
4156 if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4157 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4160 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4161 // FIXME: Need a better way to get rid of this, there's no latency difference
4162 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4163 // the former later. We should also remove the "_undef" special mask.
4164 if (NumElts == 4 && Is256BitVec)
4167 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4168 // independently on 128-bit lanes.
4169 unsigned NumLanes = VT.getSizeInBits()/128;
4170 unsigned NumLaneElts = NumElts/NumLanes;
4172 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4173 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4174 int BitI = Mask[l+i];
4175 int BitI1 = Mask[l+i+1];
4177 if (!isUndefOrEqual(BitI, j))
4179 if (!isUndefOrEqual(BitI1, j))
4187 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4188 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4190 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4191 unsigned NumElts = VT.getVectorNumElements();
4193 if (VT.is512BitVector())
4196 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4197 "Unsupported vector type for unpckh");
4199 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4200 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4203 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4204 // independently on 128-bit lanes.
4205 unsigned NumLanes = VT.getSizeInBits()/128;
4206 unsigned NumLaneElts = NumElts/NumLanes;
4208 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4209 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4210 int BitI = Mask[l+i];
4211 int BitI1 = Mask[l+i+1];
4212 if (!isUndefOrEqual(BitI, j))
4214 if (!isUndefOrEqual(BitI1, j))
4221 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4222 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4223 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4224 if (!VT.is512BitVector())
4227 unsigned NumElts = VT.getVectorNumElements();
4228 unsigned HalfSize = NumElts/2;
4229 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4230 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4235 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4236 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4244 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4245 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4246 /// MOVSD, and MOVD, i.e. setting the lowest element.
4247 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4248 if (VT.getVectorElementType().getSizeInBits() < 32)
4250 if (!VT.is128BitVector())
4253 unsigned NumElts = VT.getVectorNumElements();
4255 if (!isUndefOrEqual(Mask[0], NumElts))
4258 for (unsigned i = 1; i != NumElts; ++i)
4259 if (!isUndefOrEqual(Mask[i], i))
4265 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4266 /// as permutations between 128-bit chunks or halves. As an example: this
4268 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4269 /// The first half comes from the second half of V1 and the second half from the
4270 /// the second half of V2.
4271 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4272 if (!HasFp256 || !VT.is256BitVector())
4275 // The shuffle result is divided into half A and half B. In total the two
4276 // sources have 4 halves, namely: C, D, E, F. The final values of A and
4277 // B must come from C, D, E or F.
4278 unsigned HalfSize = VT.getVectorNumElements()/2;
4279 bool MatchA = false, MatchB = false;
4281 // Check if A comes from one of C, D, E, F.
4282 for (unsigned Half = 0; Half != 4; ++Half) {
4283 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4289 // Check if B comes from one of C, D, E, F.
4290 for (unsigned Half = 0; Half != 4; ++Half) {
4291 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4297 return MatchA && MatchB;
4300 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4301 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4302 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4303 MVT VT = SVOp->getSimpleValueType(0);
4305 unsigned HalfSize = VT.getVectorNumElements()/2;
4307 unsigned FstHalf = 0, SndHalf = 0;
4308 for (unsigned i = 0; i < HalfSize; ++i) {
4309 if (SVOp->getMaskElt(i) > 0) {
4310 FstHalf = SVOp->getMaskElt(i)/HalfSize;
4314 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4315 if (SVOp->getMaskElt(i) > 0) {
4316 SndHalf = SVOp->getMaskElt(i)/HalfSize;
4321 return (FstHalf | (SndHalf << 4));
4324 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4325 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4326 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4330 unsigned NumElts = VT.getVectorNumElements();
4332 if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4333 for (unsigned i = 0; i != NumElts; ++i) {
4336 Imm8 |= Mask[i] << (i*2);
4341 unsigned LaneSize = 4;
4342 SmallVector<int, 4> MaskVal(LaneSize, -1);
4344 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4345 for (unsigned i = 0; i != LaneSize; ++i) {
4346 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4350 if (MaskVal[i] < 0) {
4351 MaskVal[i] = Mask[i+l] - l;
4352 Imm8 |= MaskVal[i] << (i*2);
4355 if (Mask[i+l] != (signed)(MaskVal[i]+l))
4362 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4363 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4364 /// Note that VPERMIL mask matching is different depending whether theunderlying
4365 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4366 /// to the same elements of the low, but to the higher half of the source.
4367 /// In VPERMILPD the two lanes could be shuffled independently of each other
4368 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4369 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4370 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4371 if (VT.getSizeInBits() < 256 || EltSize < 32)
4373 bool symetricMaskRequired = (EltSize == 32);
4374 unsigned NumElts = VT.getVectorNumElements();
4376 unsigned NumLanes = VT.getSizeInBits()/128;
4377 unsigned LaneSize = NumElts/NumLanes;
4378 // 2 or 4 elements in one lane
4380 SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4381 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4382 for (unsigned i = 0; i != LaneSize; ++i) {
4383 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4385 if (symetricMaskRequired) {
4386 if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4387 ExpectedMaskVal[i] = Mask[i+l] - l;
4390 if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4398 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4399 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
4400 /// element of vector 2 and the other elements to come from vector 1 in order.
4401 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4402 bool V2IsSplat = false, bool V2IsUndef = false) {
4403 if (!VT.is128BitVector())
4406 unsigned NumOps = VT.getVectorNumElements();
4407 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4410 if (!isUndefOrEqual(Mask[0], 0))
4413 for (unsigned i = 1; i != NumOps; ++i)
4414 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4415 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4416 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4422 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4423 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4424 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4425 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4426 const X86Subtarget *Subtarget) {
4427 if (!Subtarget->hasSSE3())
4430 unsigned NumElems = VT.getVectorNumElements();
4432 if ((VT.is128BitVector() && NumElems != 4) ||
4433 (VT.is256BitVector() && NumElems != 8) ||
4434 (VT.is512BitVector() && NumElems != 16))
4437 // "i+1" is the value the indexed mask element must have
4438 for (unsigned i = 0; i != NumElems; i += 2)
4439 if (!isUndefOrEqual(Mask[i], i+1) ||
4440 !isUndefOrEqual(Mask[i+1], i+1))
4446 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4447 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4448 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4449 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4450 const X86Subtarget *Subtarget) {
4451 if (!Subtarget->hasSSE3())
4454 unsigned NumElems = VT.getVectorNumElements();
4456 if ((VT.is128BitVector() && NumElems != 4) ||
4457 (VT.is256BitVector() && NumElems != 8) ||
4458 (VT.is512BitVector() && NumElems != 16))
4461 // "i" is the value the indexed mask element must have
4462 for (unsigned i = 0; i != NumElems; i += 2)
4463 if (!isUndefOrEqual(Mask[i], i) ||
4464 !isUndefOrEqual(Mask[i+1], i))
4470 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4471 /// specifies a shuffle of elements that is suitable for input to 256-bit
4472 /// version of MOVDDUP.
4473 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4474 if (!HasFp256 || !VT.is256BitVector())
4477 unsigned NumElts = VT.getVectorNumElements();
4481 for (unsigned i = 0; i != NumElts/2; ++i)
4482 if (!isUndefOrEqual(Mask[i], 0))
4484 for (unsigned i = NumElts/2; i != NumElts; ++i)
4485 if (!isUndefOrEqual(Mask[i], NumElts/2))
4490 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4491 /// specifies a shuffle of elements that is suitable for input to 128-bit
4492 /// version of MOVDDUP.
4493 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4494 if (!VT.is128BitVector())
4497 unsigned e = VT.getVectorNumElements() / 2;
4498 for (unsigned i = 0; i != e; ++i)
4499 if (!isUndefOrEqual(Mask[i], i))
4501 for (unsigned i = 0; i != e; ++i)
4502 if (!isUndefOrEqual(Mask[e+i], i))
4507 /// isVEXTRACTIndex - Return true if the specified
4508 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4509 /// suitable for instruction that extract 128 or 256 bit vectors
4510 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4511 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4512 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4515 // The index should be aligned on a vecWidth-bit boundary.
4517 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4519 MVT VT = N->getSimpleValueType(0);
4520 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4521 bool Result = (Index * ElSize) % vecWidth == 0;
4526 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4527 /// operand specifies a subvector insert that is suitable for input to
4528 /// insertion of 128 or 256-bit subvectors
4529 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4530 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4531 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4533 // The index should be aligned on a vecWidth-bit boundary.
4535 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4537 MVT VT = N->getSimpleValueType(0);
4538 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4539 bool Result = (Index * ElSize) % vecWidth == 0;
4544 bool X86::isVINSERT128Index(SDNode *N) {
4545 return isVINSERTIndex(N, 128);
4548 bool X86::isVINSERT256Index(SDNode *N) {
4549 return isVINSERTIndex(N, 256);
4552 bool X86::isVEXTRACT128Index(SDNode *N) {
4553 return isVEXTRACTIndex(N, 128);
4556 bool X86::isVEXTRACT256Index(SDNode *N) {
4557 return isVEXTRACTIndex(N, 256);
4560 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4561 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4562 /// Handles 128-bit and 256-bit.
4563 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4564 MVT VT = N->getSimpleValueType(0);
4566 assert((VT.getSizeInBits() >= 128) &&
4567 "Unsupported vector type for PSHUF/SHUFP");
4569 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4570 // independently on 128-bit lanes.
4571 unsigned NumElts = VT.getVectorNumElements();
4572 unsigned NumLanes = VT.getSizeInBits()/128;
4573 unsigned NumLaneElts = NumElts/NumLanes;
4575 assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4576 "Only supports 2, 4 or 8 elements per lane");
4578 unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4580 for (unsigned i = 0; i != NumElts; ++i) {
4581 int Elt = N->getMaskElt(i);
4582 if (Elt < 0) continue;
4583 Elt &= NumLaneElts - 1;
4584 unsigned ShAmt = (i << Shift) % 8;
4585 Mask |= Elt << ShAmt;
4591 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4592 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4593 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4594 MVT VT = N->getSimpleValueType(0);
4596 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4597 "Unsupported vector type for PSHUFHW");
4599 unsigned NumElts = VT.getVectorNumElements();
4602 for (unsigned l = 0; l != NumElts; l += 8) {
4603 // 8 nodes per lane, but we only care about the last 4.
4604 for (unsigned i = 0; i < 4; ++i) {
4605 int Elt = N->getMaskElt(l+i+4);
4606 if (Elt < 0) continue;
4607 Elt &= 0x3; // only 2-bits.
4608 Mask |= Elt << (i * 2);
4615 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4616 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4617 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4618 MVT VT = N->getSimpleValueType(0);
4620 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4621 "Unsupported vector type for PSHUFHW");
4623 unsigned NumElts = VT.getVectorNumElements();
4626 for (unsigned l = 0; l != NumElts; l += 8) {
4627 // 8 nodes per lane, but we only care about the first 4.
4628 for (unsigned i = 0; i < 4; ++i) {
4629 int Elt = N->getMaskElt(l+i);
4630 if (Elt < 0) continue;
4631 Elt &= 0x3; // only 2-bits
4632 Mask |= Elt << (i * 2);
4639 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4640 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4641 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4642 MVT VT = SVOp->getSimpleValueType(0);
4643 unsigned EltSize = VT.is512BitVector() ? 1 :
4644 VT.getVectorElementType().getSizeInBits() >> 3;
4646 unsigned NumElts = VT.getVectorNumElements();
4647 unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4648 unsigned NumLaneElts = NumElts/NumLanes;
4652 for (i = 0; i != NumElts; ++i) {
4653 Val = SVOp->getMaskElt(i);
4657 if (Val >= (int)NumElts)
4658 Val -= NumElts - NumLaneElts;
4660 assert(Val - i > 0 && "PALIGNR imm should be positive");
4661 return (Val - i) * EltSize;
4664 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4665 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4666 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4667 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4670 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4672 MVT VecVT = N->getOperand(0).getSimpleValueType();
4673 MVT ElVT = VecVT.getVectorElementType();
4675 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4676 return Index / NumElemsPerChunk;
4679 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4680 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4681 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4682 llvm_unreachable("Illegal insert subvector for VINSERT");
4685 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4687 MVT VecVT = N->getSimpleValueType(0);
4688 MVT ElVT = VecVT.getVectorElementType();
4690 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4691 return Index / NumElemsPerChunk;
4694 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4695 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4696 /// and VINSERTI128 instructions.
4697 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4698 return getExtractVEXTRACTImmediate(N, 128);
4701 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4702 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4703 /// and VINSERTI64x4 instructions.
4704 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4705 return getExtractVEXTRACTImmediate(N, 256);
4708 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4709 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4710 /// and VINSERTI128 instructions.
4711 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4712 return getInsertVINSERTImmediate(N, 128);
4715 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4716 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4717 /// and VINSERTI64x4 instructions.
4718 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4719 return getInsertVINSERTImmediate(N, 256);
4722 /// isZero - Returns true if Elt is a constant integer zero
4723 static bool isZero(SDValue V) {
4724 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4725 return C && C->isNullValue();
4728 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4730 bool X86::isZeroNode(SDValue Elt) {
4733 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4734 return CFP->getValueAPF().isPosZero();
4738 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4739 /// their permute mask.
4740 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4741 SelectionDAG &DAG) {
4742 MVT VT = SVOp->getSimpleValueType(0);
4743 unsigned NumElems = VT.getVectorNumElements();
4744 SmallVector<int, 8> MaskVec;
4746 for (unsigned i = 0; i != NumElems; ++i) {
4747 int Idx = SVOp->getMaskElt(i);
4749 if (Idx < (int)NumElems)
4754 MaskVec.push_back(Idx);
4756 return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4757 SVOp->getOperand(0), &MaskVec[0]);
4760 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4761 /// match movhlps. The lower half elements should come from upper half of
4762 /// V1 (and in order), and the upper half elements should come from the upper
4763 /// half of V2 (and in order).
4764 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4765 if (!VT.is128BitVector())
4767 if (VT.getVectorNumElements() != 4)
4769 for (unsigned i = 0, e = 2; i != e; ++i)
4770 if (!isUndefOrEqual(Mask[i], i+2))
4772 for (unsigned i = 2; i != 4; ++i)
4773 if (!isUndefOrEqual(Mask[i], i+4))
4778 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4779 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4781 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4782 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4784 N = N->getOperand(0).getNode();
4785 if (!ISD::isNON_EXTLoad(N))
4788 *LD = cast<LoadSDNode>(N);
4792 // Test whether the given value is a vector value which will be legalized
4794 static bool WillBeConstantPoolLoad(SDNode *N) {
4795 if (N->getOpcode() != ISD::BUILD_VECTOR)
4798 // Check for any non-constant elements.
4799 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4800 switch (N->getOperand(i).getNode()->getOpcode()) {
4802 case ISD::ConstantFP:
4809 // Vectors of all-zeros and all-ones are materialized with special
4810 // instructions rather than being loaded.
4811 return !ISD::isBuildVectorAllZeros(N) &&
4812 !ISD::isBuildVectorAllOnes(N);
4815 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4816 /// match movlp{s|d}. The lower half elements should come from lower half of
4817 /// V1 (and in order), and the upper half elements should come from the upper
4818 /// half of V2 (and in order). And since V1 will become the source of the
4819 /// MOVLP, it must be either a vector load or a scalar load to vector.
4820 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4821 ArrayRef<int> Mask, MVT VT) {
4822 if (!VT.is128BitVector())
4825 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4827 // Is V2 is a vector load, don't do this transformation. We will try to use
4828 // load folding shufps op.
4829 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4832 unsigned NumElems = VT.getVectorNumElements();
4834 if (NumElems != 2 && NumElems != 4)
4836 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4837 if (!isUndefOrEqual(Mask[i], i))
4839 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4840 if (!isUndefOrEqual(Mask[i], i+NumElems))
4845 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4847 static bool isSplatVector(SDNode *N) {
4848 if (N->getOpcode() != ISD::BUILD_VECTOR)
4851 SDValue SplatValue = N->getOperand(0);
4852 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4853 if (N->getOperand(i) != SplatValue)
4858 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4859 /// to an zero vector.
4860 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4861 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4862 SDValue V1 = N->getOperand(0);
4863 SDValue V2 = N->getOperand(1);
4864 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4865 for (unsigned i = 0; i != NumElems; ++i) {
4866 int Idx = N->getMaskElt(i);
4867 if (Idx >= (int)NumElems) {
4868 unsigned Opc = V2.getOpcode();
4869 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4871 if (Opc != ISD::BUILD_VECTOR ||
4872 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4874 } else if (Idx >= 0) {
4875 unsigned Opc = V1.getOpcode();
4876 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4878 if (Opc != ISD::BUILD_VECTOR ||
4879 !X86::isZeroNode(V1.getOperand(Idx)))
4886 /// getZeroVector - Returns a vector of specified type with all zero elements.
4888 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4889 SelectionDAG &DAG, SDLoc dl) {
4890 assert(VT.isVector() && "Expected a vector type");
4892 // Always build SSE zero vectors as <4 x i32> bitcasted
4893 // to their dest type. This ensures they get CSE'd.
4895 if (VT.is128BitVector()) { // SSE
4896 if (Subtarget->hasSSE2()) { // SSE2
4897 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4898 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4900 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4901 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4903 } else if (VT.is256BitVector()) { // AVX
4904 if (Subtarget->hasInt256()) { // AVX2
4905 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4906 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4907 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4909 // 256-bit logic and arithmetic instructions in AVX are all
4910 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4911 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4912 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4913 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4915 } else if (VT.is512BitVector()) { // AVX-512
4916 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4917 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4918 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4919 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4920 } else if (VT.getScalarType() == MVT::i1) {
4921 assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4922 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4923 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4924 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4926 llvm_unreachable("Unexpected vector type");
4928 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4931 /// getOnesVector - Returns a vector of specified type with all bits set.
4932 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4933 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4934 /// Then bitcast to their original type, ensuring they get CSE'd.
4935 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4937 assert(VT.isVector() && "Expected a vector type");
4939 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4941 if (VT.is256BitVector()) {
4942 if (HasInt256) { // AVX2
4943 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4944 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4946 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4947 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4949 } else if (VT.is128BitVector()) {
4950 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4952 llvm_unreachable("Unexpected vector type");
4954 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4957 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4958 /// that point to V2 points to its first element.
4959 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4960 for (unsigned i = 0; i != NumElems; ++i) {
4961 if (Mask[i] > (int)NumElems) {
4967 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4968 /// operation of specified width.
4969 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4971 unsigned NumElems = VT.getVectorNumElements();
4972 SmallVector<int, 8> Mask;
4973 Mask.push_back(NumElems);
4974 for (unsigned i = 1; i != NumElems; ++i)
4976 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4979 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4980 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4982 unsigned NumElems = VT.getVectorNumElements();
4983 SmallVector<int, 8> Mask;
4984 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4986 Mask.push_back(i + NumElems);
4988 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4991 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4992 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4994 unsigned NumElems = VT.getVectorNumElements();
4995 SmallVector<int, 8> Mask;
4996 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4997 Mask.push_back(i + Half);
4998 Mask.push_back(i + NumElems + Half);
5000 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5003 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
5004 // a generic shuffle instruction because the target has no such instructions.
5005 // Generate shuffles which repeat i16 and i8 several times until they can be
5006 // represented by v4f32 and then be manipulated by target suported shuffles.
5007 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5008 MVT VT = V.getSimpleValueType();
5009 int NumElems = VT.getVectorNumElements();
5012 while (NumElems > 4) {
5013 if (EltNo < NumElems/2) {
5014 V = getUnpackl(DAG, dl, VT, V, V);
5016 V = getUnpackh(DAG, dl, VT, V, V);
5017 EltNo -= NumElems/2;
5024 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5025 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5026 MVT VT = V.getSimpleValueType();
5029 if (VT.is128BitVector()) {
5030 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5031 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5032 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5034 } else if (VT.is256BitVector()) {
5035 // To use VPERMILPS to splat scalars, the second half of indicies must
5036 // refer to the higher part, which is a duplication of the lower one,
5037 // because VPERMILPS can only handle in-lane permutations.
5038 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5039 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5041 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5042 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5045 llvm_unreachable("Vector size not supported");
5047 return DAG.getNode(ISD::BITCAST, dl, VT, V);
5050 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5051 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5052 MVT SrcVT = SV->getSimpleValueType(0);
5053 SDValue V1 = SV->getOperand(0);
5056 int EltNo = SV->getSplatIndex();
5057 int NumElems = SrcVT.getVectorNumElements();
5058 bool Is256BitVec = SrcVT.is256BitVector();
5060 assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5061 "Unknown how to promote splat for type");
5063 // Extract the 128-bit part containing the splat element and update
5064 // the splat element index when it refers to the higher register.
5066 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5067 if (EltNo >= NumElems/2)
5068 EltNo -= NumElems/2;
5071 // All i16 and i8 vector types can't be used directly by a generic shuffle
5072 // instruction because the target has no such instruction. Generate shuffles
5073 // which repeat i16 and i8 several times until they fit in i32, and then can
5074 // be manipulated by target suported shuffles.
5075 MVT EltVT = SrcVT.getVectorElementType();
5076 if (EltVT == MVT::i8 || EltVT == MVT::i16)
5077 V1 = PromoteSplati8i16(V1, DAG, EltNo);
5079 // Recreate the 256-bit vector and place the same 128-bit vector
5080 // into the low and high part. This is necessary because we want
5081 // to use VPERM* to shuffle the vectors
5083 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5086 return getLegalSplat(DAG, V1, EltNo);
5089 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5090 /// vector of zero or undef vector. This produces a shuffle where the low
5091 /// element of V2 is swizzled into the zero/undef vector, landing at element
5092 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
5093 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5095 const X86Subtarget *Subtarget,
5096 SelectionDAG &DAG) {
5097 MVT VT = V2.getSimpleValueType();
5099 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5100 unsigned NumElems = VT.getVectorNumElements();
5101 SmallVector<int, 16> MaskVec;
5102 for (unsigned i = 0; i != NumElems; ++i)
5103 // If this is the insertion idx, put the low elt of V2 here.
5104 MaskVec.push_back(i == Idx ? NumElems : i);
5105 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5108 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5109 /// target specific opcode. Returns true if the Mask could be calculated.
5110 /// Sets IsUnary to true if only uses one source.
5111 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5112 SmallVectorImpl<int> &Mask, bool &IsUnary) {
5113 unsigned NumElems = VT.getVectorNumElements();
5117 switch(N->getOpcode()) {
5119 ImmN = N->getOperand(N->getNumOperands()-1);
5120 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5122 case X86ISD::UNPCKH:
5123 DecodeUNPCKHMask(VT, Mask);
5125 case X86ISD::UNPCKL:
5126 DecodeUNPCKLMask(VT, Mask);
5128 case X86ISD::MOVHLPS:
5129 DecodeMOVHLPSMask(NumElems, Mask);
5131 case X86ISD::MOVLHPS:
5132 DecodeMOVLHPSMask(NumElems, Mask);
5134 case X86ISD::PALIGNR:
5135 ImmN = N->getOperand(N->getNumOperands()-1);
5136 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5138 case X86ISD::PSHUFD:
5139 case X86ISD::VPERMILP:
5140 ImmN = N->getOperand(N->getNumOperands()-1);
5141 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5144 case X86ISD::PSHUFHW:
5145 ImmN = N->getOperand(N->getNumOperands()-1);
5146 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5149 case X86ISD::PSHUFLW:
5150 ImmN = N->getOperand(N->getNumOperands()-1);
5151 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5154 case X86ISD::VPERMI:
5155 ImmN = N->getOperand(N->getNumOperands()-1);
5156 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5160 case X86ISD::MOVSD: {
5161 // The index 0 always comes from the first element of the second source,
5162 // this is why MOVSS and MOVSD are used in the first place. The other
5163 // elements come from the other positions of the first source vector
5164 Mask.push_back(NumElems);
5165 for (unsigned i = 1; i != NumElems; ++i) {
5170 case X86ISD::VPERM2X128:
5171 ImmN = N->getOperand(N->getNumOperands()-1);
5172 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5173 if (Mask.empty()) return false;
5175 case X86ISD::MOVDDUP:
5176 case X86ISD::MOVLHPD:
5177 case X86ISD::MOVLPD:
5178 case X86ISD::MOVLPS:
5179 case X86ISD::MOVSHDUP:
5180 case X86ISD::MOVSLDUP:
5181 // Not yet implemented
5183 default: llvm_unreachable("unknown target shuffle node");
5189 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5190 /// element of the result of the vector shuffle.
5191 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5194 return SDValue(); // Limit search depth.
5196 SDValue V = SDValue(N, 0);
5197 EVT VT = V.getValueType();
5198 unsigned Opcode = V.getOpcode();
5200 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5201 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5202 int Elt = SV->getMaskElt(Index);
5205 return DAG.getUNDEF(VT.getVectorElementType());
5207 unsigned NumElems = VT.getVectorNumElements();
5208 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5209 : SV->getOperand(1);
5210 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5213 // Recurse into target specific vector shuffles to find scalars.
5214 if (isTargetShuffle(Opcode)) {
5215 MVT ShufVT = V.getSimpleValueType();
5216 unsigned NumElems = ShufVT.getVectorNumElements();
5217 SmallVector<int, 16> ShuffleMask;
5220 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5223 int Elt = ShuffleMask[Index];
5225 return DAG.getUNDEF(ShufVT.getVectorElementType());
5227 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5229 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5233 // Actual nodes that may contain scalar elements
5234 if (Opcode == ISD::BITCAST) {
5235 V = V.getOperand(0);
5236 EVT SrcVT = V.getValueType();
5237 unsigned NumElems = VT.getVectorNumElements();
5239 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5243 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5244 return (Index == 0) ? V.getOperand(0)
5245 : DAG.getUNDEF(VT.getVectorElementType());
5247 if (V.getOpcode() == ISD::BUILD_VECTOR)
5248 return V.getOperand(Index);
5253 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5254 /// shuffle operation which come from a consecutively from a zero. The
5255 /// search can start in two different directions, from left or right.
5256 /// We count undefs as zeros until PreferredNum is reached.
5257 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5258 unsigned NumElems, bool ZerosFromLeft,
5260 unsigned PreferredNum = -1U) {
5261 unsigned NumZeros = 0;
5262 for (unsigned i = 0; i != NumElems; ++i) {
5263 unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5264 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5268 if (X86::isZeroNode(Elt))
5270 else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5271 NumZeros = std::min(NumZeros + 1, PreferredNum);
5279 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5280 /// correspond consecutively to elements from one of the vector operands,
5281 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5283 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5284 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5285 unsigned NumElems, unsigned &OpNum) {
5286 bool SeenV1 = false;
5287 bool SeenV2 = false;
5289 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5290 int Idx = SVOp->getMaskElt(i);
5291 // Ignore undef indicies
5295 if (Idx < (int)NumElems)
5300 // Only accept consecutive elements from the same vector
5301 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5305 OpNum = SeenV1 ? 0 : 1;
5309 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5310 /// logical left shift of a vector.
5311 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5312 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5314 SVOp->getSimpleValueType(0).getVectorNumElements();
5315 unsigned NumZeros = getNumOfConsecutiveZeros(
5316 SVOp, NumElems, false /* check zeros from right */, DAG,
5317 SVOp->getMaskElt(0));
5323 // Considering the elements in the mask that are not consecutive zeros,
5324 // check if they consecutively come from only one of the source vectors.
5326 // V1 = {X, A, B, C} 0
5328 // vector_shuffle V1, V2 <1, 2, 3, X>
5330 if (!isShuffleMaskConsecutive(SVOp,
5331 0, // Mask Start Index
5332 NumElems-NumZeros, // Mask End Index(exclusive)
5333 NumZeros, // Where to start looking in the src vector
5334 NumElems, // Number of elements in vector
5335 OpSrc)) // Which source operand ?
5340 ShVal = SVOp->getOperand(OpSrc);
5344 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5345 /// logical left shift of a vector.
5346 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5347 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5349 SVOp->getSimpleValueType(0).getVectorNumElements();
5350 unsigned NumZeros = getNumOfConsecutiveZeros(
5351 SVOp, NumElems, true /* check zeros from left */, DAG,
5352 NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5358 // Considering the elements in the mask that are not consecutive zeros,
5359 // check if they consecutively come from only one of the source vectors.
5361 // 0 { A, B, X, X } = V2
5363 // vector_shuffle V1, V2 <X, X, 4, 5>
5365 if (!isShuffleMaskConsecutive(SVOp,
5366 NumZeros, // Mask Start Index
5367 NumElems, // Mask End Index(exclusive)
5368 0, // Where to start looking in the src vector
5369 NumElems, // Number of elements in vector
5370 OpSrc)) // Which source operand ?
5375 ShVal = SVOp->getOperand(OpSrc);
5379 /// isVectorShift - Returns true if the shuffle can be implemented as a
5380 /// logical left or right shift of a vector.
5381 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5382 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5383 // Although the logic below support any bitwidth size, there are no
5384 // shift instructions which handle more than 128-bit vectors.
5385 if (!SVOp->getSimpleValueType(0).is128BitVector())
5388 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5389 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5395 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5397 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5398 unsigned NumNonZero, unsigned NumZero,
5400 const X86Subtarget* Subtarget,
5401 const TargetLowering &TLI) {
5408 for (unsigned i = 0; i < 16; ++i) {
5409 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5410 if (ThisIsNonZero && First) {
5412 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5414 V = DAG.getUNDEF(MVT::v8i16);
5419 SDValue ThisElt, LastElt;
5420 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5421 if (LastIsNonZero) {
5422 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5423 MVT::i16, Op.getOperand(i-1));
5425 if (ThisIsNonZero) {
5426 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5427 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5428 ThisElt, DAG.getConstant(8, MVT::i8));
5430 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5434 if (ThisElt.getNode())
5435 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5436 DAG.getIntPtrConstant(i/2));
5440 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5443 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5445 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5446 unsigned NumNonZero, unsigned NumZero,
5448 const X86Subtarget* Subtarget,
5449 const TargetLowering &TLI) {
5456 for (unsigned i = 0; i < 8; ++i) {
5457 bool isNonZero = (NonZeros & (1 << i)) != 0;
5461 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5463 V = DAG.getUNDEF(MVT::v8i16);
5466 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5467 MVT::v8i16, V, Op.getOperand(i),
5468 DAG.getIntPtrConstant(i));
5475 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5476 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5477 unsigned NonZeros, unsigned NumNonZero,
5478 unsigned NumZero, SelectionDAG &DAG,
5479 const X86Subtarget *Subtarget,
5480 const TargetLowering &TLI) {
5481 // We know there's at least one non-zero element
5482 unsigned FirstNonZeroIdx = 0;
5483 SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5484 while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5485 X86::isZeroNode(FirstNonZero)) {
5487 FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5490 if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5491 !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5494 SDValue V = FirstNonZero.getOperand(0);
5495 MVT VVT = V.getSimpleValueType();
5496 if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5499 unsigned FirstNonZeroDst =
5500 cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5501 unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5502 unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5503 unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5505 for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5506 SDValue Elem = Op.getOperand(Idx);
5507 if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5510 // TODO: What else can be here? Deal with it.
5511 if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5514 // TODO: Some optimizations are still possible here
5515 // ex: Getting one element from a vector, and the rest from another.
5516 if (Elem.getOperand(0) != V)
5519 unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5522 else if (IncorrectIdx == -1U) {
5526 // There was already one element with an incorrect index.
5527 // We can't optimize this case to an insertps.
5531 if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5533 EVT VT = Op.getSimpleValueType();
5534 unsigned ElementMoveMask = 0;
5535 if (IncorrectIdx == -1U)
5536 ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5538 ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5540 SDValue InsertpsMask =
5541 DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5542 return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5548 /// getVShift - Return a vector logical shift node.
5550 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5551 unsigned NumBits, SelectionDAG &DAG,
5552 const TargetLowering &TLI, SDLoc dl) {
5553 assert(VT.is128BitVector() && "Unknown type for VShift");
5554 EVT ShVT = MVT::v2i64;
5555 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5556 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5557 return DAG.getNode(ISD::BITCAST, dl, VT,
5558 DAG.getNode(Opc, dl, ShVT, SrcOp,
5559 DAG.getConstant(NumBits,
5560 TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5564 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5566 // Check if the scalar load can be widened into a vector load. And if
5567 // the address is "base + cst" see if the cst can be "absorbed" into
5568 // the shuffle mask.
5569 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5570 SDValue Ptr = LD->getBasePtr();
5571 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5573 EVT PVT = LD->getValueType(0);
5574 if (PVT != MVT::i32 && PVT != MVT::f32)
5579 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5580 FI = FINode->getIndex();
5582 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5583 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5584 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5585 Offset = Ptr.getConstantOperandVal(1);
5586 Ptr = Ptr.getOperand(0);
5591 // FIXME: 256-bit vector instructions don't require a strict alignment,
5592 // improve this code to support it better.
5593 unsigned RequiredAlign = VT.getSizeInBits()/8;
5594 SDValue Chain = LD->getChain();
5595 // Make sure the stack object alignment is at least 16 or 32.
5596 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5597 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5598 if (MFI->isFixedObjectIndex(FI)) {
5599 // Can't change the alignment. FIXME: It's possible to compute
5600 // the exact stack offset and reference FI + adjust offset instead.
5601 // If someone *really* cares about this. That's the way to implement it.
5604 MFI->setObjectAlignment(FI, RequiredAlign);
5608 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5609 // Ptr + (Offset & ~15).
5612 if ((Offset % RequiredAlign) & 3)
5614 int64_t StartOffset = Offset & ~(RequiredAlign-1);
5616 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5617 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5619 int EltNo = (Offset - StartOffset) >> 2;
5620 unsigned NumElems = VT.getVectorNumElements();
5622 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5623 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5624 LD->getPointerInfo().getWithOffset(StartOffset),
5625 false, false, false, 0);
5627 SmallVector<int, 8> Mask;
5628 for (unsigned i = 0; i != NumElems; ++i)
5629 Mask.push_back(EltNo);
5631 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5637 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5638 /// vector of type 'VT', see if the elements can be replaced by a single large
5639 /// load which has the same value as a build_vector whose operands are 'elts'.
5641 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5643 /// FIXME: we'd also like to handle the case where the last elements are zero
5644 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5645 /// There's even a handy isZeroNode for that purpose.
5646 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5647 SDLoc &DL, SelectionDAG &DAG,
5648 bool isAfterLegalize) {
5649 EVT EltVT = VT.getVectorElementType();
5650 unsigned NumElems = Elts.size();
5652 LoadSDNode *LDBase = nullptr;
5653 unsigned LastLoadedElt = -1U;
5655 // For each element in the initializer, see if we've found a load or an undef.
5656 // If we don't find an initial load element, or later load elements are
5657 // non-consecutive, bail out.
5658 for (unsigned i = 0; i < NumElems; ++i) {
5659 SDValue Elt = Elts[i];
5661 if (!Elt.getNode() ||
5662 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5665 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5667 LDBase = cast<LoadSDNode>(Elt.getNode());
5671 if (Elt.getOpcode() == ISD::UNDEF)
5674 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5675 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5680 // If we have found an entire vector of loads and undefs, then return a large
5681 // load of the entire vector width starting at the base pointer. If we found
5682 // consecutive loads for the low half, generate a vzext_load node.
5683 if (LastLoadedElt == NumElems - 1) {
5685 if (isAfterLegalize &&
5686 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5689 SDValue NewLd = SDValue();
5691 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5692 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5693 LDBase->getPointerInfo(),
5694 LDBase->isVolatile(), LDBase->isNonTemporal(),
5695 LDBase->isInvariant(), 0);
5696 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5697 LDBase->getPointerInfo(),
5698 LDBase->isVolatile(), LDBase->isNonTemporal(),
5699 LDBase->isInvariant(), LDBase->getAlignment());
5701 if (LDBase->hasAnyUseOfValue(1)) {
5702 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5704 SDValue(NewLd.getNode(), 1));
5705 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5706 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5707 SDValue(NewLd.getNode(), 1));
5712 if (NumElems == 4 && LastLoadedElt == 1 &&
5713 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5714 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5715 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5717 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5718 LDBase->getPointerInfo(),
5719 LDBase->getAlignment(),
5720 false/*isVolatile*/, true/*ReadMem*/,
5723 // Make sure the newly-created LOAD is in the same position as LDBase in
5724 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5725 // update uses of LDBase's output chain to use the TokenFactor.
5726 if (LDBase->hasAnyUseOfValue(1)) {
5727 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5728 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5729 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5730 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5731 SDValue(ResNode.getNode(), 1));
5734 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5739 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5740 /// to generate a splat value for the following cases:
5741 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5742 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5743 /// a scalar load, or a constant.
5744 /// The VBROADCAST node is returned when a pattern is found,
5745 /// or SDValue() otherwise.
5746 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5747 SelectionDAG &DAG) {
5748 if (!Subtarget->hasFp256())
5751 MVT VT = Op.getSimpleValueType();
5754 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5755 "Unsupported vector type for broadcast.");
5760 switch (Op.getOpcode()) {
5762 // Unknown pattern found.
5765 case ISD::BUILD_VECTOR: {
5766 // The BUILD_VECTOR node must be a splat.
5767 if (!isSplatVector(Op.getNode()))
5770 Ld = Op.getOperand(0);
5771 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5772 Ld.getOpcode() == ISD::ConstantFP);
5774 // The suspected load node has several users. Make sure that all
5775 // of its users are from the BUILD_VECTOR node.
5776 // Constants may have multiple users.
5777 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5782 case ISD::VECTOR_SHUFFLE: {
5783 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5785 // Shuffles must have a splat mask where the first element is
5787 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5790 SDValue Sc = Op.getOperand(0);
5791 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5792 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5794 if (!Subtarget->hasInt256())
5797 // Use the register form of the broadcast instruction available on AVX2.
5798 if (VT.getSizeInBits() >= 256)
5799 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5800 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5803 Ld = Sc.getOperand(0);
5804 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5805 Ld.getOpcode() == ISD::ConstantFP);
5807 // The scalar_to_vector node and the suspected
5808 // load node must have exactly one user.
5809 // Constants may have multiple users.
5811 // AVX-512 has register version of the broadcast
5812 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5813 Ld.getValueType().getSizeInBits() >= 32;
5814 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5821 bool IsGE256 = (VT.getSizeInBits() >= 256);
5823 // Handle the broadcasting a single constant scalar from the constant pool
5824 // into a vector. On Sandybridge it is still better to load a constant vector
5825 // from the constant pool and not to broadcast it from a scalar.
5826 if (ConstSplatVal && Subtarget->hasInt256()) {
5827 EVT CVT = Ld.getValueType();
5828 assert(!CVT.isVector() && "Must not broadcast a vector type");
5829 unsigned ScalarSize = CVT.getSizeInBits();
5831 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5832 const Constant *C = nullptr;
5833 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5834 C = CI->getConstantIntValue();
5835 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5836 C = CF->getConstantFPValue();
5838 assert(C && "Invalid constant type");
5840 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5841 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5842 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5843 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5844 MachinePointerInfo::getConstantPool(),
5845 false, false, false, Alignment);
5847 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5851 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5852 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5854 // Handle AVX2 in-register broadcasts.
5855 if (!IsLoad && Subtarget->hasInt256() &&
5856 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5857 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5859 // The scalar source must be a normal load.
5863 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5864 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5866 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5867 // double since there is no vbroadcastsd xmm
5868 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5869 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5870 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5873 // Unsupported broadcast.
5877 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5878 /// underlying vector and index.
5880 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5882 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5884 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5885 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5888 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5890 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5892 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5893 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5896 // In this case the vector is the extract_subvector expression and the index
5897 // is 2, as specified by the shuffle.
5898 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5899 SDValue ShuffleVec = SVOp->getOperand(0);
5900 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5901 assert(ShuffleVecVT.getVectorElementType() ==
5902 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5904 int ShuffleIdx = SVOp->getMaskElt(Idx);
5905 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5906 ExtractedFromVec = ShuffleVec;
5912 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5913 MVT VT = Op.getSimpleValueType();
5915 // Skip if insert_vec_elt is not supported.
5916 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5917 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5921 unsigned NumElems = Op.getNumOperands();
5925 SmallVector<unsigned, 4> InsertIndices;
5926 SmallVector<int, 8> Mask(NumElems, -1);
5928 for (unsigned i = 0; i != NumElems; ++i) {
5929 unsigned Opc = Op.getOperand(i).getOpcode();
5931 if (Opc == ISD::UNDEF)
5934 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5935 // Quit if more than 1 elements need inserting.
5936 if (InsertIndices.size() > 1)
5939 InsertIndices.push_back(i);
5943 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5944 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5945 // Quit if non-constant index.
5946 if (!isa<ConstantSDNode>(ExtIdx))
5948 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5950 // Quit if extracted from vector of different type.
5951 if (ExtractedFromVec.getValueType() != VT)
5954 if (!VecIn1.getNode())
5955 VecIn1 = ExtractedFromVec;
5956 else if (VecIn1 != ExtractedFromVec) {
5957 if (!VecIn2.getNode())
5958 VecIn2 = ExtractedFromVec;
5959 else if (VecIn2 != ExtractedFromVec)
5960 // Quit if more than 2 vectors to shuffle
5964 if (ExtractedFromVec == VecIn1)
5966 else if (ExtractedFromVec == VecIn2)
5967 Mask[i] = Idx + NumElems;
5970 if (!VecIn1.getNode())
5973 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5974 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5975 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5976 unsigned Idx = InsertIndices[i];
5977 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5978 DAG.getIntPtrConstant(Idx));
5984 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5986 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5988 MVT VT = Op.getSimpleValueType();
5989 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5990 "Unexpected type in LowerBUILD_VECTORvXi1!");
5993 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5994 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5995 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5996 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5999 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
6000 SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
6001 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6002 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6005 bool AllContants = true;
6006 uint64_t Immediate = 0;
6007 int NonConstIdx = -1;
6008 bool IsSplat = true;
6009 unsigned NumNonConsts = 0;
6010 unsigned NumConsts = 0;
6011 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6012 SDValue In = Op.getOperand(idx);
6013 if (In.getOpcode() == ISD::UNDEF)
6015 if (!isa<ConstantSDNode>(In)) {
6016 AllContants = false;
6022 if (cast<ConstantSDNode>(In)->getZExtValue())
6023 Immediate |= (1ULL << idx);
6025 if (In != Op.getOperand(0))
6030 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6031 DAG.getConstant(Immediate, MVT::i16));
6032 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6033 DAG.getIntPtrConstant(0));
6036 if (NumNonConsts == 1 && NonConstIdx != 0) {
6039 SDValue VecAsImm = DAG.getConstant(Immediate,
6040 MVT::getIntegerVT(VT.getSizeInBits()));
6041 DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6044 DstVec = DAG.getUNDEF(VT);
6045 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6046 Op.getOperand(NonConstIdx),
6047 DAG.getIntPtrConstant(NonConstIdx));
6049 if (!IsSplat && (NonConstIdx != 0))
6050 llvm_unreachable("Unsupported BUILD_VECTOR operation");
6051 MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6054 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6055 DAG.getConstant(-1, SelectVT),
6056 DAG.getConstant(0, SelectVT));
6058 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6059 DAG.getConstant((Immediate | 1), SelectVT),
6060 DAG.getConstant(Immediate, SelectVT));
6061 return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6064 /// \brief Return true if \p N implements a horizontal binop and return the
6065 /// operands for the horizontal binop into V0 and V1.
6067 /// This is a helper function of PerformBUILD_VECTORCombine.
6068 /// This function checks that the build_vector \p N in input implements a
6069 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
6070 /// operation to match.
6071 /// For example, if \p Opcode is equal to ISD::ADD, then this function
6072 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
6073 /// is equal to ISD::SUB, then this function checks if this is a horizontal
6076 /// This function only analyzes elements of \p N whose indices are
6077 /// in range [BaseIdx, LastIdx).
6078 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
6080 unsigned BaseIdx, unsigned LastIdx,
6081 SDValue &V0, SDValue &V1) {
6082 EVT VT = N->getValueType(0);
6084 assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
6085 assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
6086 "Invalid Vector in input!");
6088 bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
6089 bool CanFold = true;
6090 unsigned ExpectedVExtractIdx = BaseIdx;
6091 unsigned NumElts = LastIdx - BaseIdx;
6092 V0 = DAG.getUNDEF(VT);
6093 V1 = DAG.getUNDEF(VT);
6095 // Check if N implements a horizontal binop.
6096 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
6097 SDValue Op = N->getOperand(i + BaseIdx);
6100 if (Op->getOpcode() == ISD::UNDEF) {
6101 // Update the expected vector extract index.
6102 if (i * 2 == NumElts)
6103 ExpectedVExtractIdx = BaseIdx;
6104 ExpectedVExtractIdx += 2;
6108 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6113 SDValue Op0 = Op.getOperand(0);
6114 SDValue Op1 = Op.getOperand(1);
6116 // Try to match the following pattern:
6117 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6118 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6119 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6120 Op0.getOperand(0) == Op1.getOperand(0) &&
6121 isa<ConstantSDNode>(Op0.getOperand(1)) &&
6122 isa<ConstantSDNode>(Op1.getOperand(1)));
6126 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6127 unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6129 if (i * 2 < NumElts) {
6130 if (V0.getOpcode() == ISD::UNDEF)
6131 V0 = Op0.getOperand(0);
6133 if (V1.getOpcode() == ISD::UNDEF)
6134 V1 = Op0.getOperand(0);
6135 if (i * 2 == NumElts)
6136 ExpectedVExtractIdx = BaseIdx;
6139 SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
6140 if (I0 == ExpectedVExtractIdx)
6141 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6142 else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6143 // Try to match the following dag sequence:
6144 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6145 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6149 ExpectedVExtractIdx += 2;
6155 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6156 /// a concat_vector.
6158 /// This is a helper function of PerformBUILD_VECTORCombine.
6159 /// This function expects two 256-bit vectors called V0 and V1.
6160 /// At first, each vector is split into two separate 128-bit vectors.
6161 /// Then, the resulting 128-bit vectors are used to implement two
6162 /// horizontal binary operations.
6164 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6166 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6167 /// the two new horizontal binop.
6168 /// When Mode is set, the first horizontal binop dag node would take as input
6169 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6170 /// horizontal binop dag node would take as input the lower 128-bit of V1
6171 /// and the upper 128-bit of V1.
6173 /// HADD V0_LO, V0_HI
6174 /// HADD V1_LO, V1_HI
6176 /// Otherwise, the first horizontal binop dag node takes as input the lower
6177 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6178 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
6180 /// HADD V0_LO, V1_LO
6181 /// HADD V0_HI, V1_HI
6183 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6184 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6185 /// the upper 128-bits of the result.
6186 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6187 SDLoc DL, SelectionDAG &DAG,
6188 unsigned X86Opcode, bool Mode,
6189 bool isUndefLO, bool isUndefHI) {
6190 EVT VT = V0.getValueType();
6191 assert(VT.is256BitVector() && VT == V1.getValueType() &&
6192 "Invalid nodes in input!");
6194 unsigned NumElts = VT.getVectorNumElements();
6195 SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6196 SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6197 SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6198 SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6199 EVT NewVT = V0_LO.getValueType();
6201 SDValue LO = DAG.getUNDEF(NewVT);
6202 SDValue HI = DAG.getUNDEF(NewVT);
6205 // Don't emit a horizontal binop if the result is expected to be UNDEF.
6206 if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6207 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6208 if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6209 HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6211 // Don't emit a horizontal binop if the result is expected to be UNDEF.
6212 if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6213 V1_LO->getOpcode() != ISD::UNDEF))
6214 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6216 if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6217 V1_HI->getOpcode() != ISD::UNDEF))
6218 HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6221 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6224 /// \brief Try to fold a build_vector that performs an 'addsub' into the
6225 /// sequence of 'vadd + vsub + blendi'.
6226 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
6227 const X86Subtarget *Subtarget) {
6229 EVT VT = BV->getValueType(0);
6230 unsigned NumElts = VT.getVectorNumElements();
6231 SDValue InVec0 = DAG.getUNDEF(VT);
6232 SDValue InVec1 = DAG.getUNDEF(VT);
6234 assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6235 VT == MVT::v2f64) && "build_vector with an invalid type found!");
6237 // Don't try to emit a VSELECT that cannot be lowered into a blend.
6238 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6239 if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
6242 // Odd-numbered elements in the input build vector are obtained from
6243 // adding two integer/float elements.
6244 // Even-numbered elements in the input build vector are obtained from
6245 // subtracting two integer/float elements.
6246 unsigned ExpectedOpcode = ISD::FSUB;
6247 unsigned NextExpectedOpcode = ISD::FADD;
6248 bool AddFound = false;
6249 bool SubFound = false;
6251 for (unsigned i = 0, e = NumElts; i != e; i++) {
6252 SDValue Op = BV->getOperand(i);
6254 // Skip 'undef' values.
6255 unsigned Opcode = Op.getOpcode();
6256 if (Opcode == ISD::UNDEF) {
6257 std::swap(ExpectedOpcode, NextExpectedOpcode);
6261 // Early exit if we found an unexpected opcode.
6262 if (Opcode != ExpectedOpcode)
6265 SDValue Op0 = Op.getOperand(0);
6266 SDValue Op1 = Op.getOperand(1);
6268 // Try to match the following pattern:
6269 // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6270 // Early exit if we cannot match that sequence.
6271 if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6272 Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6273 !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6274 !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6275 Op0.getOperand(1) != Op1.getOperand(1))
6278 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6282 // We found a valid add/sub node. Update the information accordingly.
6288 // Update InVec0 and InVec1.
6289 if (InVec0.getOpcode() == ISD::UNDEF)
6290 InVec0 = Op0.getOperand(0);
6291 if (InVec1.getOpcode() == ISD::UNDEF)
6292 InVec1 = Op1.getOperand(0);
6294 // Make sure that operands in input to each add/sub node always
6295 // come from a same pair of vectors.
6296 if (InVec0 != Op0.getOperand(0)) {
6297 if (ExpectedOpcode == ISD::FSUB)
6300 // FADD is commutable. Try to commute the operands
6301 // and then test again.
6302 std::swap(Op0, Op1);
6303 if (InVec0 != Op0.getOperand(0))
6307 if (InVec1 != Op1.getOperand(0))
6310 // Update the pair of expected opcodes.
6311 std::swap(ExpectedOpcode, NextExpectedOpcode);
6314 // Don't try to fold this build_vector into a VSELECT if it has
6315 // too many UNDEF operands.
6316 if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6317 InVec1.getOpcode() != ISD::UNDEF) {
6318 // Emit a sequence of vector add and sub followed by a VSELECT.
6319 // The new VSELECT will be lowered into a BLENDI.
6320 // At ISel stage, we pattern-match the sequence 'add + sub + BLENDI'
6321 // and emit a single ADDSUB instruction.
6322 SDValue Sub = DAG.getNode(ExpectedOpcode, DL, VT, InVec0, InVec1);
6323 SDValue Add = DAG.getNode(NextExpectedOpcode, DL, VT, InVec0, InVec1);
6325 // Construct the VSELECT mask.
6326 EVT MaskVT = VT.changeVectorElementTypeToInteger();
6327 EVT SVT = MaskVT.getVectorElementType();
6328 unsigned SVTBits = SVT.getSizeInBits();
6329 SmallVector<SDValue, 8> Ops;
6331 for (unsigned i = 0, e = NumElts; i != e; ++i) {
6332 APInt Value = i & 1 ? APInt::getNullValue(SVTBits) :
6333 APInt::getAllOnesValue(SVTBits);
6334 SDValue Constant = DAG.getConstant(Value, SVT);
6335 Ops.push_back(Constant);
6338 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskVT, Ops);
6339 return DAG.getSelect(DL, VT, Mask, Sub, Add);
6345 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6346 const X86Subtarget *Subtarget) {
6348 EVT VT = N->getValueType(0);
6349 unsigned NumElts = VT.getVectorNumElements();
6350 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
6351 SDValue InVec0, InVec1;
6353 // Try to match an ADDSUB.
6354 if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
6355 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
6356 SDValue Value = matchAddSub(BV, DAG, Subtarget);
6357 if (Value.getNode())
6361 // Try to match horizontal ADD/SUB.
6362 unsigned NumUndefsLO = 0;
6363 unsigned NumUndefsHI = 0;
6364 unsigned Half = NumElts/2;
6366 // Count the number of UNDEF operands in the build_vector in input.
6367 for (unsigned i = 0, e = Half; i != e; ++i)
6368 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6371 for (unsigned i = Half, e = NumElts; i != e; ++i)
6372 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6375 // Early exit if this is either a build_vector of all UNDEFs or all the
6376 // operands but one are UNDEF.
6377 if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6380 if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6381 // Try to match an SSE3 float HADD/HSUB.
6382 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6383 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6385 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6386 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6387 } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6388 // Try to match an SSSE3 integer HADD/HSUB.
6389 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6390 return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6392 if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6393 return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6396 if (!Subtarget->hasAVX())
6399 if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6400 // Try to match an AVX horizontal add/sub of packed single/double
6401 // precision floating point values from 256-bit vectors.
6402 SDValue InVec2, InVec3;
6403 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6404 isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6405 ((InVec0.getOpcode() == ISD::UNDEF ||
6406 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6407 ((InVec1.getOpcode() == ISD::UNDEF ||
6408 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6409 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6411 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6412 isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6413 ((InVec0.getOpcode() == ISD::UNDEF ||
6414 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6415 ((InVec1.getOpcode() == ISD::UNDEF ||
6416 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6417 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6418 } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6419 // Try to match an AVX2 horizontal add/sub of signed integers.
6420 SDValue InVec2, InVec3;
6422 bool CanFold = true;
6424 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6425 isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6426 ((InVec0.getOpcode() == ISD::UNDEF ||
6427 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6428 ((InVec1.getOpcode() == ISD::UNDEF ||
6429 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6430 X86Opcode = X86ISD::HADD;
6431 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6432 isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6433 ((InVec0.getOpcode() == ISD::UNDEF ||
6434 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6435 ((InVec1.getOpcode() == ISD::UNDEF ||
6436 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6437 X86Opcode = X86ISD::HSUB;
6442 // Fold this build_vector into a single horizontal add/sub.
6443 // Do this only if the target has AVX2.
6444 if (Subtarget->hasAVX2())
6445 return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6447 // Do not try to expand this build_vector into a pair of horizontal
6448 // add/sub if we can emit a pair of scalar add/sub.
6449 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6452 // Convert this build_vector into a pair of horizontal binop followed by
6454 bool isUndefLO = NumUndefsLO == Half;
6455 bool isUndefHI = NumUndefsHI == Half;
6456 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6457 isUndefLO, isUndefHI);
6461 if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6462 VT == MVT::v16i16) && Subtarget->hasAVX()) {
6464 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6465 X86Opcode = X86ISD::HADD;
6466 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6467 X86Opcode = X86ISD::HSUB;
6468 else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6469 X86Opcode = X86ISD::FHADD;
6470 else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6471 X86Opcode = X86ISD::FHSUB;
6475 // Don't try to expand this build_vector into a pair of horizontal add/sub
6476 // if we can simply emit a pair of scalar add/sub.
6477 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6480 // Convert this build_vector into two horizontal add/sub followed by
6482 bool isUndefLO = NumUndefsLO == Half;
6483 bool isUndefHI = NumUndefsHI == Half;
6484 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6485 isUndefLO, isUndefHI);
6492 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6495 MVT VT = Op.getSimpleValueType();
6496 MVT ExtVT = VT.getVectorElementType();
6497 unsigned NumElems = Op.getNumOperands();
6499 // Generate vectors for predicate vectors.
6500 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6501 return LowerBUILD_VECTORvXi1(Op, DAG);
6503 // Vectors containing all zeros can be matched by pxor and xorps later
6504 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6505 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6506 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6507 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6510 return getZeroVector(VT, Subtarget, DAG, dl);
6513 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6514 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6515 // vpcmpeqd on 256-bit vectors.
6516 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6517 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6520 if (!VT.is512BitVector())
6521 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6524 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6525 if (Broadcast.getNode())
6528 unsigned EVTBits = ExtVT.getSizeInBits();
6530 unsigned NumZero = 0;
6531 unsigned NumNonZero = 0;
6532 unsigned NonZeros = 0;
6533 bool IsAllConstants = true;
6534 SmallSet<SDValue, 8> Values;
6535 for (unsigned i = 0; i < NumElems; ++i) {
6536 SDValue Elt = Op.getOperand(i);
6537 if (Elt.getOpcode() == ISD::UNDEF)
6540 if (Elt.getOpcode() != ISD::Constant &&
6541 Elt.getOpcode() != ISD::ConstantFP)
6542 IsAllConstants = false;
6543 if (X86::isZeroNode(Elt))
6546 NonZeros |= (1 << i);
6551 // All undef vector. Return an UNDEF. All zero vectors were handled above.
6552 if (NumNonZero == 0)
6553 return DAG.getUNDEF(VT);
6555 // Special case for single non-zero, non-undef, element.
6556 if (NumNonZero == 1) {
6557 unsigned Idx = countTrailingZeros(NonZeros);
6558 SDValue Item = Op.getOperand(Idx);
6560 // If this is an insertion of an i64 value on x86-32, and if the top bits of
6561 // the value are obviously zero, truncate the value to i32 and do the
6562 // insertion that way. Only do this if the value is non-constant or if the
6563 // value is a constant being inserted into element 0. It is cheaper to do
6564 // a constant pool load than it is to do a movd + shuffle.
6565 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6566 (!IsAllConstants || Idx == 0)) {
6567 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6569 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6570 EVT VecVT = MVT::v4i32;
6571 unsigned VecElts = 4;
6573 // Truncate the value (which may itself be a constant) to i32, and
6574 // convert it to a vector with movd (S2V+shuffle to zero extend).
6575 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6576 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6577 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6579 // Now we have our 32-bit value zero extended in the low element of
6580 // a vector. If Idx != 0, swizzle it into place.
6582 SmallVector<int, 4> Mask;
6583 Mask.push_back(Idx);
6584 for (unsigned i = 1; i != VecElts; ++i)
6586 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6589 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6593 // If we have a constant or non-constant insertion into the low element of
6594 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6595 // the rest of the elements. This will be matched as movd/movq/movss/movsd
6596 // depending on what the source datatype is.
6599 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6601 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6602 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6603 if (VT.is256BitVector() || VT.is512BitVector()) {
6604 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6605 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6606 Item, DAG.getIntPtrConstant(0));
6608 assert(VT.is128BitVector() && "Expected an SSE value type!");
6609 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6610 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6611 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6614 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6615 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6616 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6617 if (VT.is256BitVector()) {
6618 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6619 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6621 assert(VT.is128BitVector() && "Expected an SSE value type!");
6622 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6624 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6628 // Is it a vector logical left shift?
6629 if (NumElems == 2 && Idx == 1 &&
6630 X86::isZeroNode(Op.getOperand(0)) &&
6631 !X86::isZeroNode(Op.getOperand(1))) {
6632 unsigned NumBits = VT.getSizeInBits();
6633 return getVShift(true, VT,
6634 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6635 VT, Op.getOperand(1)),
6636 NumBits/2, DAG, *this, dl);
6639 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6642 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6643 // is a non-constant being inserted into an element other than the low one,
6644 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6645 // movd/movss) to move this into the low element, then shuffle it into
6647 if (EVTBits == 32) {
6648 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6650 // Turn it into a shuffle of zero and zero-extended scalar to vector.
6651 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6652 SmallVector<int, 8> MaskVec;
6653 for (unsigned i = 0; i != NumElems; ++i)
6654 MaskVec.push_back(i == Idx ? 0 : 1);
6655 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6659 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6660 if (Values.size() == 1) {
6661 if (EVTBits == 32) {
6662 // Instead of a shuffle like this:
6663 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6664 // Check if it's possible to issue this instead.
6665 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6666 unsigned Idx = countTrailingZeros(NonZeros);
6667 SDValue Item = Op.getOperand(Idx);
6668 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6669 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6674 // A vector full of immediates; various special cases are already
6675 // handled, so this is best done with a single constant-pool load.
6679 // For AVX-length vectors, build the individual 128-bit pieces and use
6680 // shuffles to put them in place.
6681 if (VT.is256BitVector() || VT.is512BitVector()) {
6682 SmallVector<SDValue, 64> V;
6683 for (unsigned i = 0; i != NumElems; ++i)
6684 V.push_back(Op.getOperand(i));
6686 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6688 // Build both the lower and upper subvector.
6689 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6690 makeArrayRef(&V[0], NumElems/2));
6691 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6692 makeArrayRef(&V[NumElems / 2], NumElems/2));
6694 // Recreate the wider vector with the lower and upper part.
6695 if (VT.is256BitVector())
6696 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6697 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6700 // Let legalizer expand 2-wide build_vectors.
6701 if (EVTBits == 64) {
6702 if (NumNonZero == 1) {
6703 // One half is zero or undef.
6704 unsigned Idx = countTrailingZeros(NonZeros);
6705 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6706 Op.getOperand(Idx));
6707 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6712 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6713 if (EVTBits == 8 && NumElems == 16) {
6714 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6716 if (V.getNode()) return V;
6719 if (EVTBits == 16 && NumElems == 8) {
6720 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6722 if (V.getNode()) return V;
6725 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6726 if (EVTBits == 32 && NumElems == 4) {
6727 SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6728 NumZero, DAG, Subtarget, *this);
6733 // If element VT is == 32 bits, turn it into a number of shuffles.
6734 SmallVector<SDValue, 8> V(NumElems);
6735 if (NumElems == 4 && NumZero > 0) {
6736 for (unsigned i = 0; i < 4; ++i) {
6737 bool isZero = !(NonZeros & (1 << i));
6739 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6741 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6744 for (unsigned i = 0; i < 2; ++i) {
6745 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6748 V[i] = V[i*2]; // Must be a zero vector.
6751 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6754 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6757 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6762 bool Reverse1 = (NonZeros & 0x3) == 2;
6763 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6767 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6768 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6770 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6773 if (Values.size() > 1 && VT.is128BitVector()) {
6774 // Check for a build vector of consecutive loads.
6775 for (unsigned i = 0; i < NumElems; ++i)
6776 V[i] = Op.getOperand(i);
6778 // Check for elements which are consecutive loads.
6779 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6783 // Check for a build vector from mostly shuffle plus few inserting.
6784 SDValue Sh = buildFromShuffleMostly(Op, DAG);
6788 // For SSE 4.1, use insertps to put the high elements into the low element.
6789 if (getSubtarget()->hasSSE41()) {
6791 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6792 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6794 Result = DAG.getUNDEF(VT);
6796 for (unsigned i = 1; i < NumElems; ++i) {
6797 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6798 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6799 Op.getOperand(i), DAG.getIntPtrConstant(i));
6804 // Otherwise, expand into a number of unpckl*, start by extending each of
6805 // our (non-undef) elements to the full vector width with the element in the
6806 // bottom slot of the vector (which generates no code for SSE).
6807 for (unsigned i = 0; i < NumElems; ++i) {
6808 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6809 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6811 V[i] = DAG.getUNDEF(VT);
6814 // Next, we iteratively mix elements, e.g. for v4f32:
6815 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6816 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6817 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6818 unsigned EltStride = NumElems >> 1;
6819 while (EltStride != 0) {
6820 for (unsigned i = 0; i < EltStride; ++i) {
6821 // If V[i+EltStride] is undef and this is the first round of mixing,
6822 // then it is safe to just drop this shuffle: V[i] is already in the
6823 // right place, the one element (since it's the first round) being
6824 // inserted as undef can be dropped. This isn't safe for successive
6825 // rounds because they will permute elements within both vectors.
6826 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6827 EltStride == NumElems/2)
6830 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6839 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6840 // to create 256-bit vectors from two other 128-bit ones.
6841 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6843 MVT ResVT = Op.getSimpleValueType();
6845 assert((ResVT.is256BitVector() ||
6846 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6848 SDValue V1 = Op.getOperand(0);
6849 SDValue V2 = Op.getOperand(1);
6850 unsigned NumElems = ResVT.getVectorNumElements();
6851 if(ResVT.is256BitVector())
6852 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6854 if (Op.getNumOperands() == 4) {
6855 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6856 ResVT.getVectorNumElements()/2);
6857 SDValue V3 = Op.getOperand(2);
6858 SDValue V4 = Op.getOperand(3);
6859 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6860 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6862 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6865 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6866 MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6867 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6868 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6869 Op.getNumOperands() == 4)));
6871 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6872 // from two other 128-bit ones.
6874 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6875 return LowerAVXCONCAT_VECTORS(Op, DAG);
6878 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
6879 bool hasInt256, unsigned *MaskOut = nullptr) {
6880 MVT EltVT = VT.getVectorElementType();
6882 // There is no blend with immediate in AVX-512.
6883 if (VT.is512BitVector())
6886 if (!hasSSE41 || EltVT == MVT::i8)
6888 if (!hasInt256 && VT == MVT::v16i16)
6891 unsigned MaskValue = 0;
6892 unsigned NumElems = VT.getVectorNumElements();
6893 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6894 unsigned NumLanes = (NumElems - 1) / 8 + 1;
6895 unsigned NumElemsInLane = NumElems / NumLanes;
6897 // Blend for v16i16 should be symetric for the both lanes.
6898 for (unsigned i = 0; i < NumElemsInLane; ++i) {
6900 int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
6901 int EltIdx = MaskVals[i];
6903 if ((EltIdx < 0 || EltIdx == (int)i) &&
6904 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6907 if (((unsigned)EltIdx == (i + NumElems)) &&
6908 (SndLaneEltIdx < 0 ||
6909 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6910 MaskValue |= (1 << i);
6916 *MaskOut = MaskValue;
6920 // Try to lower a shuffle node into a simple blend instruction.
6921 // This function assumes isBlendMask returns true for this
6922 // SuffleVectorSDNode
6923 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6925 const X86Subtarget *Subtarget,
6926 SelectionDAG &DAG) {
6927 MVT VT = SVOp->getSimpleValueType(0);
6928 MVT EltVT = VT.getVectorElementType();
6929 assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
6930 Subtarget->hasInt256() && "Trying to lower a "
6931 "VECTOR_SHUFFLE to a Blend but "
6932 "with the wrong mask"));
6933 SDValue V1 = SVOp->getOperand(0);
6934 SDValue V2 = SVOp->getOperand(1);
6936 unsigned NumElems = VT.getVectorNumElements();
6938 // Convert i32 vectors to floating point if it is not AVX2.
6939 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6941 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6942 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6944 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6945 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6948 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6949 DAG.getConstant(MaskValue, MVT::i32));
6950 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6953 /// In vector type \p VT, return true if the element at index \p InputIdx
6954 /// falls on a different 128-bit lane than \p OutputIdx.
6955 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
6956 unsigned OutputIdx) {
6957 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6958 return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
6961 /// Generate a PSHUFB if possible. Selects elements from \p V1 according to
6962 /// \p MaskVals. MaskVals[OutputIdx] = InputIdx specifies that we want to
6963 /// shuffle the element at InputIdx in V1 to OutputIdx in the result. If \p
6964 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
6966 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
6967 SelectionDAG &DAG) {
6968 MVT VT = V1.getSimpleValueType();
6969 assert(VT.is128BitVector() || VT.is256BitVector());
6971 MVT EltVT = VT.getVectorElementType();
6972 unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
6973 unsigned NumElts = VT.getVectorNumElements();
6975 SmallVector<SDValue, 32> PshufbMask;
6976 for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
6977 int InputIdx = MaskVals[OutputIdx];
6978 unsigned InputByteIdx;
6980 if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
6981 InputByteIdx = 0x80;
6983 // Cross lane is not allowed.
6984 if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
6986 InputByteIdx = InputIdx * EltSizeInBytes;
6987 // Index is an byte offset within the 128-bit lane.
6988 InputByteIdx &= 0xf;
6991 for (unsigned j = 0; j < EltSizeInBytes; ++j) {
6992 PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
6993 if (InputByteIdx != 0x80)
6998 MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
7000 V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
7001 return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
7002 DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
7005 // v8i16 shuffles - Prefer shuffles in the following order:
7006 // 1. [all] pshuflw, pshufhw, optional move
7007 // 2. [ssse3] 1 x pshufb
7008 // 3. [ssse3] 2 x pshufb + 1 x por
7009 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
7011 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
7012 SelectionDAG &DAG) {
7013 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7014 SDValue V1 = SVOp->getOperand(0);
7015 SDValue V2 = SVOp->getOperand(1);
7017 SmallVector<int, 8> MaskVals;
7019 // Determine if more than 1 of the words in each of the low and high quadwords
7020 // of the result come from the same quadword of one of the two inputs. Undef
7021 // mask values count as coming from any quadword, for better codegen.
7023 // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
7024 // feeds this quad. For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
7025 unsigned LoQuad[] = { 0, 0, 0, 0 };
7026 unsigned HiQuad[] = { 0, 0, 0, 0 };
7027 // Indices of quads used.
7028 std::bitset<4> InputQuads;
7029 for (unsigned i = 0; i < 8; ++i) {
7030 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
7031 int EltIdx = SVOp->getMaskElt(i);
7032 MaskVals.push_back(EltIdx);
7041 InputQuads.set(EltIdx / 4);
7044 int BestLoQuad = -1;
7045 unsigned MaxQuad = 1;
7046 for (unsigned i = 0; i < 4; ++i) {
7047 if (LoQuad[i] > MaxQuad) {
7049 MaxQuad = LoQuad[i];
7053 int BestHiQuad = -1;
7055 for (unsigned i = 0; i < 4; ++i) {
7056 if (HiQuad[i] > MaxQuad) {
7058 MaxQuad = HiQuad[i];
7062 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
7063 // of the two input vectors, shuffle them into one input vector so only a
7064 // single pshufb instruction is necessary. If there are more than 2 input
7065 // quads, disable the next transformation since it does not help SSSE3.
7066 bool V1Used = InputQuads[0] || InputQuads[1];
7067 bool V2Used = InputQuads[2] || InputQuads[3];
7068 if (Subtarget->hasSSSE3()) {
7069 if (InputQuads.count() == 2 && V1Used && V2Used) {
7070 BestLoQuad = InputQuads[0] ? 0 : 1;
7071 BestHiQuad = InputQuads[2] ? 2 : 3;
7073 if (InputQuads.count() > 2) {
7079 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
7080 // the shuffle mask. If a quad is scored as -1, that means that it contains
7081 // words from all 4 input quadwords.
7083 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
7085 BestLoQuad < 0 ? 0 : BestLoQuad,
7086 BestHiQuad < 0 ? 1 : BestHiQuad
7088 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
7089 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
7090 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
7091 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
7093 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
7094 // source words for the shuffle, to aid later transformations.
7095 bool AllWordsInNewV = true;
7096 bool InOrder[2] = { true, true };
7097 for (unsigned i = 0; i != 8; ++i) {
7098 int idx = MaskVals[i];
7100 InOrder[i/4] = false;
7101 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
7103 AllWordsInNewV = false;
7107 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
7108 if (AllWordsInNewV) {
7109 for (int i = 0; i != 8; ++i) {
7110 int idx = MaskVals[i];
7113 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
7114 if ((idx != i) && idx < 4)
7116 if ((idx != i) && idx > 3)
7125 // If we've eliminated the use of V2, and the new mask is a pshuflw or
7126 // pshufhw, that's as cheap as it gets. Return the new shuffle.
7127 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
7128 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
7129 unsigned TargetMask = 0;
7130 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
7131 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
7132 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
7133 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
7134 getShufflePSHUFLWImmediate(SVOp);
7135 V1 = NewV.getOperand(0);
7136 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
7140 // Promote splats to a larger type which usually leads to more efficient code.
7141 // FIXME: Is this true if pshufb is available?
7142 if (SVOp->isSplat())
7143 return PromoteSplat(SVOp, DAG);
7145 // If we have SSSE3, and all words of the result are from 1 input vector,
7146 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
7147 // is present, fall back to case 4.
7148 if (Subtarget->hasSSSE3()) {
7149 SmallVector<SDValue,16> pshufbMask;
7151 // If we have elements from both input vectors, set the high bit of the
7152 // shuffle mask element to zero out elements that come from V2 in the V1
7153 // mask, and elements that come from V1 in the V2 mask, so that the two
7154 // results can be OR'd together.
7155 bool TwoInputs = V1Used && V2Used;
7156 V1 = getPSHUFB(MaskVals, V1, dl, DAG);
7158 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
7160 // Calculate the shuffle mask for the second input, shuffle it, and
7161 // OR it with the first shuffled input.
7162 CommuteVectorShuffleMask(MaskVals, 8);
7163 V2 = getPSHUFB(MaskVals, V2, dl, DAG);
7164 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
7165 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
7168 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
7169 // and update MaskVals with new element order.
7170 std::bitset<8> InOrder;
7171 if (BestLoQuad >= 0) {
7172 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
7173 for (int i = 0; i != 4; ++i) {
7174 int idx = MaskVals[i];
7177 } else if ((idx / 4) == BestLoQuad) {
7182 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
7185 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
7186 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
7187 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
7189 getShufflePSHUFLWImmediate(SVOp), DAG);
7193 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
7194 // and update MaskVals with the new element order.
7195 if (BestHiQuad >= 0) {
7196 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
7197 for (unsigned i = 4; i != 8; ++i) {
7198 int idx = MaskVals[i];
7201 } else if ((idx / 4) == BestHiQuad) {
7202 MaskV[i] = (idx & 3) + 4;
7206 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
7209 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
7210 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
7211 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
7213 getShufflePSHUFHWImmediate(SVOp), DAG);
7217 // In case BestHi & BestLo were both -1, which means each quadword has a word
7218 // from each of the four input quadwords, calculate the InOrder bitvector now
7219 // before falling through to the insert/extract cleanup.
7220 if (BestLoQuad == -1 && BestHiQuad == -1) {
7222 for (int i = 0; i != 8; ++i)
7223 if (MaskVals[i] < 0 || MaskVals[i] == i)
7227 // The other elements are put in the right place using pextrw and pinsrw.
7228 for (unsigned i = 0; i != 8; ++i) {
7231 int EltIdx = MaskVals[i];
7234 SDValue ExtOp = (EltIdx < 8) ?
7235 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
7236 DAG.getIntPtrConstant(EltIdx)) :
7237 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
7238 DAG.getIntPtrConstant(EltIdx - 8));
7239 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
7240 DAG.getIntPtrConstant(i));
7245 /// \brief v16i16 shuffles
7247 /// FIXME: We only support generation of a single pshufb currently. We can
7248 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
7249 /// well (e.g 2 x pshufb + 1 x por).
7251 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
7252 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7253 SDValue V1 = SVOp->getOperand(0);
7254 SDValue V2 = SVOp->getOperand(1);
7257 if (V2.getOpcode() != ISD::UNDEF)
7260 SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
7261 return getPSHUFB(MaskVals, V1, dl, DAG);
7264 // v16i8 shuffles - Prefer shuffles in the following order:
7265 // 1. [ssse3] 1 x pshufb
7266 // 2. [ssse3] 2 x pshufb + 1 x por
7267 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
7268 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
7269 const X86Subtarget* Subtarget,
7270 SelectionDAG &DAG) {
7271 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7272 SDValue V1 = SVOp->getOperand(0);
7273 SDValue V2 = SVOp->getOperand(1);
7275 ArrayRef<int> MaskVals = SVOp->getMask();
7277 // Promote splats to a larger type which usually leads to more efficient code.
7278 // FIXME: Is this true if pshufb is available?
7279 if (SVOp->isSplat())
7280 return PromoteSplat(SVOp, DAG);
7282 // If we have SSSE3, case 1 is generated when all result bytes come from
7283 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
7284 // present, fall back to case 3.
7286 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
7287 if (Subtarget->hasSSSE3()) {
7288 SmallVector<SDValue,16> pshufbMask;
7290 // If all result elements are from one input vector, then only translate
7291 // undef mask values to 0x80 (zero out result) in the pshufb mask.
7293 // Otherwise, we have elements from both input vectors, and must zero out
7294 // elements that come from V2 in the first mask, and V1 in the second mask
7295 // so that we can OR them together.
7296 for (unsigned i = 0; i != 16; ++i) {
7297 int EltIdx = MaskVals[i];
7298 if (EltIdx < 0 || EltIdx >= 16)
7300 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
7302 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
7303 DAG.getNode(ISD::BUILD_VECTOR, dl,
7304 MVT::v16i8, pshufbMask));
7306 // As PSHUFB will zero elements with negative indices, it's safe to ignore
7307 // the 2nd operand if it's undefined or zero.
7308 if (V2.getOpcode() == ISD::UNDEF ||
7309 ISD::isBuildVectorAllZeros(V2.getNode()))
7312 // Calculate the shuffle mask for the second input, shuffle it, and
7313 // OR it with the first shuffled input.
7315 for (unsigned i = 0; i != 16; ++i) {
7316 int EltIdx = MaskVals[i];
7317 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
7318 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
7320 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
7321 DAG.getNode(ISD::BUILD_VECTOR, dl,
7322 MVT::v16i8, pshufbMask));
7323 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
7326 // No SSSE3 - Calculate in place words and then fix all out of place words
7327 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
7328 // the 16 different words that comprise the two doublequadword input vectors.
7329 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
7330 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
7332 for (int i = 0; i != 8; ++i) {
7333 int Elt0 = MaskVals[i*2];
7334 int Elt1 = MaskVals[i*2+1];
7336 // This word of the result is all undef, skip it.
7337 if (Elt0 < 0 && Elt1 < 0)
7340 // This word of the result is already in the correct place, skip it.
7341 if ((Elt0 == i*2) && (Elt1 == i*2+1))
7344 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
7345 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
7348 // If Elt0 and Elt1 are defined, are consecutive, and can be load
7349 // using a single extract together, load it and store it.
7350 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
7351 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
7352 DAG.getIntPtrConstant(Elt1 / 2));
7353 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
7354 DAG.getIntPtrConstant(i));
7358 // If Elt1 is defined, extract it from the appropriate source. If the
7359 // source byte is not also odd, shift the extracted word left 8 bits
7360 // otherwise clear the bottom 8 bits if we need to do an or.
7362 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
7363 DAG.getIntPtrConstant(Elt1 / 2));
7364 if ((Elt1 & 1) == 0)
7365 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
7367 TLI.getShiftAmountTy(InsElt.getValueType())));
7369 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
7370 DAG.getConstant(0xFF00, MVT::i16));
7372 // If Elt0 is defined, extract it from the appropriate source. If the
7373 // source byte is not also even, shift the extracted word right 8 bits. If
7374 // Elt1 was also defined, OR the extracted values together before
7375 // inserting them in the result.
7377 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
7378 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
7379 if ((Elt0 & 1) != 0)
7380 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
7382 TLI.getShiftAmountTy(InsElt0.getValueType())));
7384 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
7385 DAG.getConstant(0x00FF, MVT::i16));
7386 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
7389 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
7390 DAG.getIntPtrConstant(i));
7392 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
7395 // v32i8 shuffles - Translate to VPSHUFB if possible.
7397 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
7398 const X86Subtarget *Subtarget,
7399 SelectionDAG &DAG) {
7400 MVT VT = SVOp->getSimpleValueType(0);
7401 SDValue V1 = SVOp->getOperand(0);
7402 SDValue V2 = SVOp->getOperand(1);
7404 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
7406 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7407 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
7408 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
7410 // VPSHUFB may be generated if
7411 // (1) one of input vector is undefined or zeroinitializer.
7412 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
7413 // And (2) the mask indexes don't cross the 128-bit lane.
7414 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
7415 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
7418 if (V1IsAllZero && !V2IsAllZero) {
7419 CommuteVectorShuffleMask(MaskVals, 32);
7422 return getPSHUFB(MaskVals, V1, dl, DAG);
7425 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
7426 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
7427 /// done when every pair / quad of shuffle mask elements point to elements in
7428 /// the right sequence. e.g.
7429 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
7431 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
7432 SelectionDAG &DAG) {
7433 MVT VT = SVOp->getSimpleValueType(0);
7435 unsigned NumElems = VT.getVectorNumElements();
7438 switch (VT.SimpleTy) {
7439 default: llvm_unreachable("Unexpected!");
7442 return SDValue(SVOp, 0);
7443 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
7444 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
7445 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
7446 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
7447 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
7448 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
7451 SmallVector<int, 8> MaskVec;
7452 for (unsigned i = 0; i != NumElems; i += Scale) {
7454 for (unsigned j = 0; j != Scale; ++j) {
7455 int EltIdx = SVOp->getMaskElt(i+j);
7459 StartIdx = (EltIdx / Scale);
7460 if (EltIdx != (int)(StartIdx*Scale + j))
7463 MaskVec.push_back(StartIdx);
7466 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
7467 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
7468 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
7471 /// getVZextMovL - Return a zero-extending vector move low node.
7473 static SDValue getVZextMovL(MVT VT, MVT OpVT,
7474 SDValue SrcOp, SelectionDAG &DAG,
7475 const X86Subtarget *Subtarget, SDLoc dl) {
7476 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
7477 LoadSDNode *LD = nullptr;
7478 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
7479 LD = dyn_cast<LoadSDNode>(SrcOp);
7481 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
7483 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
7484 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
7485 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
7486 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
7487 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
7489 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
7490 return DAG.getNode(ISD::BITCAST, dl, VT,
7491 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
7492 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7500 return DAG.getNode(ISD::BITCAST, dl, VT,
7501 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
7502 DAG.getNode(ISD::BITCAST, dl,
7506 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
7507 /// which could not be matched by any known target speficic shuffle
7509 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7511 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
7512 if (NewOp.getNode())
7515 MVT VT = SVOp->getSimpleValueType(0);
7517 unsigned NumElems = VT.getVectorNumElements();
7518 unsigned NumLaneElems = NumElems / 2;
7521 MVT EltVT = VT.getVectorElementType();
7522 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
7525 SmallVector<int, 16> Mask;
7526 for (unsigned l = 0; l < 2; ++l) {
7527 // Build a shuffle mask for the output, discovering on the fly which
7528 // input vectors to use as shuffle operands (recorded in InputUsed).
7529 // If building a suitable shuffle vector proves too hard, then bail
7530 // out with UseBuildVector set.
7531 bool UseBuildVector = false;
7532 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
7533 unsigned LaneStart = l * NumLaneElems;
7534 for (unsigned i = 0; i != NumLaneElems; ++i) {
7535 // The mask element. This indexes into the input.
7536 int Idx = SVOp->getMaskElt(i+LaneStart);
7538 // the mask element does not index into any input vector.
7543 // The input vector this mask element indexes into.
7544 int Input = Idx / NumLaneElems;
7546 // Turn the index into an offset from the start of the input vector.
7547 Idx -= Input * NumLaneElems;
7549 // Find or create a shuffle vector operand to hold this input.
7551 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
7552 if (InputUsed[OpNo] == Input)
7553 // This input vector is already an operand.
7555 if (InputUsed[OpNo] < 0) {
7556 // Create a new operand for this input vector.
7557 InputUsed[OpNo] = Input;
7562 if (OpNo >= array_lengthof(InputUsed)) {
7563 // More than two input vectors used! Give up on trying to create a
7564 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
7565 UseBuildVector = true;
7569 // Add the mask index for the new shuffle vector.
7570 Mask.push_back(Idx + OpNo * NumLaneElems);
7573 if (UseBuildVector) {
7574 SmallVector<SDValue, 16> SVOps;
7575 for (unsigned i = 0; i != NumLaneElems; ++i) {
7576 // The mask element. This indexes into the input.
7577 int Idx = SVOp->getMaskElt(i+LaneStart);
7579 SVOps.push_back(DAG.getUNDEF(EltVT));
7583 // The input vector this mask element indexes into.
7584 int Input = Idx / NumElems;
7586 // Turn the index into an offset from the start of the input vector.
7587 Idx -= Input * NumElems;
7589 // Extract the vector element by hand.
7590 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
7591 SVOp->getOperand(Input),
7592 DAG.getIntPtrConstant(Idx)));
7595 // Construct the output using a BUILD_VECTOR.
7596 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
7597 } else if (InputUsed[0] < 0) {
7598 // No input vectors were used! The result is undefined.
7599 Output[l] = DAG.getUNDEF(NVT);
7601 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
7602 (InputUsed[0] % 2) * NumLaneElems,
7604 // If only one input was used, use an undefined vector for the other.
7605 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
7606 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
7607 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
7608 // At least one input vector was used. Create a new shuffle vector.
7609 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
7615 // Concatenate the result back
7616 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
7619 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
7620 /// 4 elements, and match them with several different shuffle types.
7622 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7623 SDValue V1 = SVOp->getOperand(0);
7624 SDValue V2 = SVOp->getOperand(1);
7626 MVT VT = SVOp->getSimpleValueType(0);
7628 assert(VT.is128BitVector() && "Unsupported vector size");
7630 std::pair<int, int> Locs[4];
7631 int Mask1[] = { -1, -1, -1, -1 };
7632 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
7636 for (unsigned i = 0; i != 4; ++i) {
7637 int Idx = PermMask[i];
7639 Locs[i] = std::make_pair(-1, -1);
7641 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
7643 Locs[i] = std::make_pair(0, NumLo);
7647 Locs[i] = std::make_pair(1, NumHi);
7649 Mask1[2+NumHi] = Idx;
7655 if (NumLo <= 2 && NumHi <= 2) {
7656 // If no more than two elements come from either vector. This can be
7657 // implemented with two shuffles. First shuffle gather the elements.
7658 // The second shuffle, which takes the first shuffle as both of its
7659 // vector operands, put the elements into the right order.
7660 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7662 int Mask2[] = { -1, -1, -1, -1 };
7664 for (unsigned i = 0; i != 4; ++i)
7665 if (Locs[i].first != -1) {
7666 unsigned Idx = (i < 2) ? 0 : 4;
7667 Idx += Locs[i].first * 2 + Locs[i].second;
7671 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
7674 if (NumLo == 3 || NumHi == 3) {
7675 // Otherwise, we must have three elements from one vector, call it X, and
7676 // one element from the other, call it Y. First, use a shufps to build an
7677 // intermediate vector with the one element from Y and the element from X
7678 // that will be in the same half in the final destination (the indexes don't
7679 // matter). Then, use a shufps to build the final vector, taking the half
7680 // containing the element from Y from the intermediate, and the other half
7683 // Normalize it so the 3 elements come from V1.
7684 CommuteVectorShuffleMask(PermMask, 4);
7688 // Find the element from V2.
7690 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
7691 int Val = PermMask[HiIndex];
7698 Mask1[0] = PermMask[HiIndex];
7700 Mask1[2] = PermMask[HiIndex^1];
7702 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7705 Mask1[0] = PermMask[0];
7706 Mask1[1] = PermMask[1];
7707 Mask1[2] = HiIndex & 1 ? 6 : 4;
7708 Mask1[3] = HiIndex & 1 ? 4 : 6;
7709 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7712 Mask1[0] = HiIndex & 1 ? 2 : 0;
7713 Mask1[1] = HiIndex & 1 ? 0 : 2;
7714 Mask1[2] = PermMask[2];
7715 Mask1[3] = PermMask[3];
7720 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7723 // Break it into (shuffle shuffle_hi, shuffle_lo).
7724 int LoMask[] = { -1, -1, -1, -1 };
7725 int HiMask[] = { -1, -1, -1, -1 };
7727 int *MaskPtr = LoMask;
7728 unsigned MaskIdx = 0;
7731 for (unsigned i = 0; i != 4; ++i) {
7738 int Idx = PermMask[i];
7740 Locs[i] = std::make_pair(-1, -1);
7741 } else if (Idx < 4) {
7742 Locs[i] = std::make_pair(MaskIdx, LoIdx);
7743 MaskPtr[LoIdx] = Idx;
7746 Locs[i] = std::make_pair(MaskIdx, HiIdx);
7747 MaskPtr[HiIdx] = Idx;
7752 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7753 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7754 int MaskOps[] = { -1, -1, -1, -1 };
7755 for (unsigned i = 0; i != 4; ++i)
7756 if (Locs[i].first != -1)
7757 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7758 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7761 static bool MayFoldVectorLoad(SDValue V) {
7762 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7763 V = V.getOperand(0);
7765 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7766 V = V.getOperand(0);
7767 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7768 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7769 // BUILD_VECTOR (load), undef
7770 V = V.getOperand(0);
7772 return MayFoldLoad(V);
7776 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7777 MVT VT = Op.getSimpleValueType();
7779 // Canonizalize to v2f64.
7780 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7781 return DAG.getNode(ISD::BITCAST, dl, VT,
7782 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7787 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7789 SDValue V1 = Op.getOperand(0);
7790 SDValue V2 = Op.getOperand(1);
7791 MVT VT = Op.getSimpleValueType();
7793 assert(VT != MVT::v2i64 && "unsupported shuffle type");
7795 if (HasSSE2 && VT == MVT::v2f64)
7796 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7798 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7799 return DAG.getNode(ISD::BITCAST, dl, VT,
7800 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7801 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7802 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7806 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7807 SDValue V1 = Op.getOperand(0);
7808 SDValue V2 = Op.getOperand(1);
7809 MVT VT = Op.getSimpleValueType();
7811 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7812 "unsupported shuffle type");
7814 if (V2.getOpcode() == ISD::UNDEF)
7818 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7822 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7823 SDValue V1 = Op.getOperand(0);
7824 SDValue V2 = Op.getOperand(1);
7825 MVT VT = Op.getSimpleValueType();
7826 unsigned NumElems = VT.getVectorNumElements();
7828 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7829 // operand of these instructions is only memory, so check if there's a
7830 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7832 bool CanFoldLoad = false;
7834 // Trivial case, when V2 comes from a load.
7835 if (MayFoldVectorLoad(V2))
7838 // When V1 is a load, it can be folded later into a store in isel, example:
7839 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7841 // (MOVLPSmr addr:$src1, VR128:$src2)
7842 // So, recognize this potential and also use MOVLPS or MOVLPD
7843 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7846 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7848 if (HasSSE2 && NumElems == 2)
7849 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7852 // If we don't care about the second element, proceed to use movss.
7853 if (SVOp->getMaskElt(1) != -1)
7854 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7857 // movl and movlp will both match v2i64, but v2i64 is never matched by
7858 // movl earlier because we make it strict to avoid messing with the movlp load
7859 // folding logic (see the code above getMOVLP call). Match it here then,
7860 // this is horrible, but will stay like this until we move all shuffle
7861 // matching to x86 specific nodes. Note that for the 1st condition all
7862 // types are matched with movsd.
7864 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7865 // as to remove this logic from here, as much as possible
7866 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7867 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7868 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7871 assert(VT != MVT::v4i32 && "unsupported shuffle type");
7873 // Invert the operand order and use SHUFPS to match it.
7874 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7875 getShuffleSHUFImmediate(SVOp), DAG);
7878 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
7879 SelectionDAG &DAG) {
7881 MVT VT = Load->getSimpleValueType(0);
7882 MVT EVT = VT.getVectorElementType();
7883 SDValue Addr = Load->getOperand(1);
7884 SDValue NewAddr = DAG.getNode(
7885 ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
7886 DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
7889 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
7890 DAG.getMachineFunction().getMachineMemOperand(
7891 Load->getMemOperand(), 0, EVT.getStoreSize()));
7895 // It is only safe to call this function if isINSERTPSMask is true for
7896 // this shufflevector mask.
7897 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
7898 SelectionDAG &DAG) {
7899 // Generate an insertps instruction when inserting an f32 from memory onto a
7900 // v4f32 or when copying a member from one v4f32 to another.
7901 // We also use it for transferring i32 from one register to another,
7902 // since it simply copies the same bits.
7903 // If we're transferring an i32 from memory to a specific element in a
7904 // register, we output a generic DAG that will match the PINSRD
7906 MVT VT = SVOp->getSimpleValueType(0);
7907 MVT EVT = VT.getVectorElementType();
7908 SDValue V1 = SVOp->getOperand(0);
7909 SDValue V2 = SVOp->getOperand(1);
7910 auto Mask = SVOp->getMask();
7911 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
7912 "unsupported vector type for insertps/pinsrd");
7914 auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
7915 auto FromV2Predicate = [](const int &i) { return i >= 4; };
7916 int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
7924 DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
7927 assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
7928 "More than one element from V1 and from V2, or no elements from one "
7929 "of the vectors. This case should not have returned true from "
7934 std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
7937 unsigned SrcIndex = Mask[DestIndex] % 4;
7938 if (MayFoldLoad(From)) {
7939 // Trivial case, when From comes from a load and is only used by the
7940 // shuffle. Make it use insertps from the vector that we need from that
7943 NarrowVectorLoadToElement(cast<LoadSDNode>(From), SrcIndex, DAG);
7944 if (!NewLoad.getNode())
7947 if (EVT == MVT::f32) {
7948 // Create this as a scalar to vector to match the instruction pattern.
7949 SDValue LoadScalarToVector =
7950 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
7951 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
7952 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
7954 } else { // EVT == MVT::i32
7955 // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
7956 // instruction, to match the PINSRD instruction, which loads an i32 to a
7957 // certain vector element.
7958 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
7959 DAG.getConstant(DestIndex, MVT::i32));
7963 // Vector-element-to-vector
7964 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
7965 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
7968 // Reduce a vector shuffle to zext.
7969 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7970 SelectionDAG &DAG) {
7971 // PMOVZX is only available from SSE41.
7972 if (!Subtarget->hasSSE41())
7975 MVT VT = Op.getSimpleValueType();
7977 // Only AVX2 support 256-bit vector integer extending.
7978 if (!Subtarget->hasInt256() && VT.is256BitVector())
7981 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7983 SDValue V1 = Op.getOperand(0);
7984 SDValue V2 = Op.getOperand(1);
7985 unsigned NumElems = VT.getVectorNumElements();
7987 // Extending is an unary operation and the element type of the source vector
7988 // won't be equal to or larger than i64.
7989 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7990 VT.getVectorElementType() == MVT::i64)
7993 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7994 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7995 while ((1U << Shift) < NumElems) {
7996 if (SVOp->getMaskElt(1U << Shift) == 1)
7999 // The maximal ratio is 8, i.e. from i8 to i64.
8004 // Check the shuffle mask.
8005 unsigned Mask = (1U << Shift) - 1;
8006 for (unsigned i = 0; i != NumElems; ++i) {
8007 int EltIdx = SVOp->getMaskElt(i);
8008 if ((i & Mask) != 0 && EltIdx != -1)
8010 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
8014 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
8015 MVT NeVT = MVT::getIntegerVT(NBits);
8016 MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
8018 if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
8021 // Simplify the operand as it's prepared to be fed into shuffle.
8022 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
8023 if (V1.getOpcode() == ISD::BITCAST &&
8024 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
8025 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
8026 V1.getOperand(0).getOperand(0)
8027 .getSimpleValueType().getSizeInBits() == SignificantBits) {
8028 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
8029 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
8030 ConstantSDNode *CIdx =
8031 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
8032 // If it's foldable, i.e. normal load with single use, we will let code
8033 // selection to fold it. Otherwise, we will short the conversion sequence.
8034 if (CIdx && CIdx->getZExtValue() == 0 &&
8035 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
8036 MVT FullVT = V.getSimpleValueType();
8037 MVT V1VT = V1.getSimpleValueType();
8038 if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
8039 // The "ext_vec_elt" node is wider than the result node.
8040 // In this case we should extract subvector from V.
8041 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
8042 unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
8043 MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
8044 FullVT.getVectorNumElements()/Ratio);
8045 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
8046 DAG.getIntPtrConstant(0));
8048 V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
8052 return DAG.getNode(ISD::BITCAST, DL, VT,
8053 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
8056 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
8057 SelectionDAG &DAG) {
8058 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8059 MVT VT = Op.getSimpleValueType();
8061 SDValue V1 = Op.getOperand(0);
8062 SDValue V2 = Op.getOperand(1);
8064 if (isZeroShuffle(SVOp))
8065 return getZeroVector(VT, Subtarget, DAG, dl);
8067 // Handle splat operations
8068 if (SVOp->isSplat()) {
8069 // Use vbroadcast whenever the splat comes from a foldable load
8070 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
8071 if (Broadcast.getNode())
8075 // Check integer expanding shuffles.
8076 SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
8077 if (NewOp.getNode())
8080 // If the shuffle can be profitably rewritten as a narrower shuffle, then
8082 if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
8084 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
8085 if (NewOp.getNode())
8086 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
8087 } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
8088 // FIXME: Figure out a cleaner way to do this.
8089 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
8090 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
8091 if (NewOp.getNode()) {
8092 MVT NewVT = NewOp.getSimpleValueType();
8093 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
8094 NewVT, true, false))
8095 return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
8098 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
8099 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
8100 if (NewOp.getNode()) {
8101 MVT NewVT = NewOp.getSimpleValueType();
8102 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
8103 return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
8112 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
8113 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8114 SDValue V1 = Op.getOperand(0);
8115 SDValue V2 = Op.getOperand(1);
8116 MVT VT = Op.getSimpleValueType();
8118 unsigned NumElems = VT.getVectorNumElements();
8119 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
8120 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
8121 bool V1IsSplat = false;
8122 bool V2IsSplat = false;
8123 bool HasSSE2 = Subtarget->hasSSE2();
8124 bool HasFp256 = Subtarget->hasFp256();
8125 bool HasInt256 = Subtarget->hasInt256();
8126 MachineFunction &MF = DAG.getMachineFunction();
8127 bool OptForSize = MF.getFunction()->getAttributes().
8128 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
8130 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
8132 if (V1IsUndef && V2IsUndef)
8133 return DAG.getUNDEF(VT);
8135 // When we create a shuffle node we put the UNDEF node to second operand,
8136 // but in some cases the first operand may be transformed to UNDEF.
8137 // In this case we should just commute the node.
8139 return CommuteVectorShuffle(SVOp, DAG);
8141 // Vector shuffle lowering takes 3 steps:
8143 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
8144 // narrowing and commutation of operands should be handled.
8145 // 2) Matching of shuffles with known shuffle masks to x86 target specific
8147 // 3) Rewriting of unmatched masks into new generic shuffle operations,
8148 // so the shuffle can be broken into other shuffles and the legalizer can
8149 // try the lowering again.
8151 // The general idea is that no vector_shuffle operation should be left to
8152 // be matched during isel, all of them must be converted to a target specific
8155 // Normalize the input vectors. Here splats, zeroed vectors, profitable
8156 // narrowing and commutation of operands should be handled. The actual code
8157 // doesn't include all of those, work in progress...
8158 SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
8159 if (NewOp.getNode())
8162 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
8164 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
8165 // unpckh_undef). Only use pshufd if speed is more important than size.
8166 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
8167 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
8168 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
8169 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
8171 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
8172 V2IsUndef && MayFoldVectorLoad(V1))
8173 return getMOVDDup(Op, dl, V1, DAG);
8175 if (isMOVHLPS_v_undef_Mask(M, VT))
8176 return getMOVHighToLow(Op, dl, DAG);
8178 // Use to match splats
8179 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
8180 (VT == MVT::v2f64 || VT == MVT::v2i64))
8181 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
8183 if (isPSHUFDMask(M, VT)) {
8184 // The actual implementation will match the mask in the if above and then
8185 // during isel it can match several different instructions, not only pshufd
8186 // as its name says, sad but true, emulate the behavior for now...
8187 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
8188 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
8190 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
8192 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
8193 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
8195 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
8196 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
8199 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
8203 if (isPALIGNRMask(M, VT, Subtarget))
8204 return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
8205 getShufflePALIGNRImmediate(SVOp),
8208 // Check if this can be converted into a logical shift.
8209 bool isLeft = false;
8212 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
8213 if (isShift && ShVal.hasOneUse()) {
8214 // If the shifted value has multiple uses, it may be cheaper to use
8215 // v_set0 + movlhps or movhlps, etc.
8216 MVT EltVT = VT.getVectorElementType();
8217 ShAmt *= EltVT.getSizeInBits();
8218 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
8221 if (isMOVLMask(M, VT)) {
8222 if (ISD::isBuildVectorAllZeros(V1.getNode()))
8223 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
8224 if (!isMOVLPMask(M, VT)) {
8225 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
8226 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
8228 if (VT == MVT::v4i32 || VT == MVT::v4f32)
8229 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
8233 // FIXME: fold these into legal mask.
8234 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
8235 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
8237 if (isMOVHLPSMask(M, VT))
8238 return getMOVHighToLow(Op, dl, DAG);
8240 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
8241 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
8243 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
8244 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
8246 if (isMOVLPMask(M, VT))
8247 return getMOVLP(Op, dl, DAG, HasSSE2);
8249 if (ShouldXformToMOVHLPS(M, VT) ||
8250 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
8251 return CommuteVectorShuffle(SVOp, DAG);
8254 // No better options. Use a vshldq / vsrldq.
8255 MVT EltVT = VT.getVectorElementType();
8256 ShAmt *= EltVT.getSizeInBits();
8257 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
8260 bool Commuted = false;
8261 // FIXME: This should also accept a bitcast of a splat? Be careful, not
8262 // 1,1,1,1 -> v8i16 though.
8263 V1IsSplat = isSplatVector(V1.getNode());
8264 V2IsSplat = isSplatVector(V2.getNode());
8266 // Canonicalize the splat or undef, if present, to be on the RHS.
8267 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
8268 CommuteVectorShuffleMask(M, NumElems);
8270 std::swap(V1IsSplat, V2IsSplat);
8274 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
8275 // Shuffling low element of v1 into undef, just return v1.
8278 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
8279 // the instruction selector will not match, so get a canonical MOVL with
8280 // swapped operands to undo the commute.
8281 return getMOVL(DAG, dl, VT, V2, V1);
8284 if (isUNPCKLMask(M, VT, HasInt256))
8285 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
8287 if (isUNPCKHMask(M, VT, HasInt256))
8288 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
8291 // Normalize mask so all entries that point to V2 points to its first
8292 // element then try to match unpck{h|l} again. If match, return a
8293 // new vector_shuffle with the corrected mask.p
8294 SmallVector<int, 8> NewMask(M.begin(), M.end());
8295 NormalizeMask(NewMask, NumElems);
8296 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
8297 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
8298 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
8299 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
8303 // Commute is back and try unpck* again.
8304 // FIXME: this seems wrong.
8305 CommuteVectorShuffleMask(M, NumElems);
8307 std::swap(V1IsSplat, V2IsSplat);
8309 if (isUNPCKLMask(M, VT, HasInt256))
8310 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
8312 if (isUNPCKHMask(M, VT, HasInt256))
8313 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
8316 // Normalize the node to match x86 shuffle ops if needed
8317 if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
8318 return CommuteVectorShuffle(SVOp, DAG);
8320 // The checks below are all present in isShuffleMaskLegal, but they are
8321 // inlined here right now to enable us to directly emit target specific
8322 // nodes, and remove one by one until they don't return Op anymore.
8324 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
8325 SVOp->getSplatIndex() == 0 && V2IsUndef) {
8326 if (VT == MVT::v2f64 || VT == MVT::v2i64)
8327 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
8330 if (isPSHUFHWMask(M, VT, HasInt256))
8331 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
8332 getShufflePSHUFHWImmediate(SVOp),
8335 if (isPSHUFLWMask(M, VT, HasInt256))
8336 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
8337 getShufflePSHUFLWImmediate(SVOp),
8340 if (isSHUFPMask(M, VT))
8341 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
8342 getShuffleSHUFImmediate(SVOp), DAG);
8344 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
8345 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
8346 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
8347 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
8349 //===--------------------------------------------------------------------===//
8350 // Generate target specific nodes for 128 or 256-bit shuffles only
8351 // supported in the AVX instruction set.
8354 // Handle VMOVDDUPY permutations
8355 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
8356 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
8358 // Handle VPERMILPS/D* permutations
8359 if (isVPERMILPMask(M, VT)) {
8360 if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
8361 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
8362 getShuffleSHUFImmediate(SVOp), DAG);
8363 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
8364 getShuffleSHUFImmediate(SVOp), DAG);
8368 if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
8369 return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
8370 Idx*(NumElems/2), DAG, dl);
8372 // Handle VPERM2F128/VPERM2I128 permutations
8373 if (isVPERM2X128Mask(M, VT, HasFp256))
8374 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
8375 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
8378 if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
8380 return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
8382 if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
8383 return getINSERTPS(SVOp, dl, DAG);
8386 if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
8387 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
8389 if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
8390 VT.is512BitVector()) {
8391 MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
8392 MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
8393 SmallVector<SDValue, 16> permclMask;
8394 for (unsigned i = 0; i != NumElems; ++i) {
8395 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
8398 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
8400 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
8401 return DAG.getNode(X86ISD::VPERMV, dl, VT,
8402 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
8403 return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
8404 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
8407 //===--------------------------------------------------------------------===//
8408 // Since no target specific shuffle was selected for this generic one,
8409 // lower it into other known shuffles. FIXME: this isn't true yet, but
8410 // this is the plan.
8413 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
8414 if (VT == MVT::v8i16) {
8415 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
8416 if (NewOp.getNode())
8420 if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
8421 SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
8422 if (NewOp.getNode())
8426 if (VT == MVT::v16i8) {
8427 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
8428 if (NewOp.getNode())
8432 if (VT == MVT::v32i8) {
8433 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
8434 if (NewOp.getNode())
8438 // Handle all 128-bit wide vectors with 4 elements, and match them with
8439 // several different shuffle types.
8440 if (NumElems == 4 && VT.is128BitVector())
8441 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
8443 // Handle general 256-bit shuffles
8444 if (VT.is256BitVector())
8445 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
8450 // This function assumes its argument is a BUILD_VECTOR of constants or
8451 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
8453 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
8454 unsigned &MaskValue) {
8456 unsigned NumElems = BuildVector->getNumOperands();
8457 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
8458 unsigned NumLanes = (NumElems - 1) / 8 + 1;
8459 unsigned NumElemsInLane = NumElems / NumLanes;
8461 // Blend for v16i16 should be symetric for the both lanes.
8462 for (unsigned i = 0; i < NumElemsInLane; ++i) {
8463 SDValue EltCond = BuildVector->getOperand(i);
8464 SDValue SndLaneEltCond =
8465 (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
8467 int Lane1Cond = -1, Lane2Cond = -1;
8468 if (isa<ConstantSDNode>(EltCond))
8469 Lane1Cond = !isZero(EltCond);
8470 if (isa<ConstantSDNode>(SndLaneEltCond))
8471 Lane2Cond = !isZero(SndLaneEltCond);
8473 if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
8474 // Lane1Cond != 0, means we want the first argument.
8475 // Lane1Cond == 0, means we want the second argument.
8476 // The encoding of this argument is 0 for the first argument, 1
8477 // for the second. Therefore, invert the condition.
8478 MaskValue |= !Lane1Cond << i;
8479 else if (Lane1Cond < 0)
8480 MaskValue |= !Lane2Cond << i;
8487 // Try to lower a vselect node into a simple blend instruction.
8488 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
8489 SelectionDAG &DAG) {
8490 SDValue Cond = Op.getOperand(0);
8491 SDValue LHS = Op.getOperand(1);
8492 SDValue RHS = Op.getOperand(2);
8494 MVT VT = Op.getSimpleValueType();
8495 MVT EltVT = VT.getVectorElementType();
8496 unsigned NumElems = VT.getVectorNumElements();
8498 // There is no blend with immediate in AVX-512.
8499 if (VT.is512BitVector())
8502 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
8504 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
8507 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
8510 // Check the mask for BLEND and build the value.
8511 unsigned MaskValue = 0;
8512 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
8515 // Convert i32 vectors to floating point if it is not AVX2.
8516 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
8518 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
8519 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
8521 LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
8522 RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
8525 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
8526 DAG.getConstant(MaskValue, MVT::i32));
8527 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
8530 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
8531 SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
8532 if (BlendOp.getNode())
8535 // Some types for vselect were previously set to Expand, not Legal or
8536 // Custom. Return an empty SDValue so we fall-through to Expand, after
8537 // the Custom lowering phase.
8538 MVT VT = Op.getSimpleValueType();
8539 switch (VT.SimpleTy) {
8547 // We couldn't create a "Blend with immediate" node.
8548 // This node should still be legal, but we'll have to emit a blendv*
8553 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8554 MVT VT = Op.getSimpleValueType();
8557 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
8560 if (VT.getSizeInBits() == 8) {
8561 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
8562 Op.getOperand(0), Op.getOperand(1));
8563 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
8564 DAG.getValueType(VT));
8565 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8568 if (VT.getSizeInBits() == 16) {
8569 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8570 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
8572 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8573 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8574 DAG.getNode(ISD::BITCAST, dl,
8578 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
8579 Op.getOperand(0), Op.getOperand(1));
8580 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
8581 DAG.getValueType(VT));
8582 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8585 if (VT == MVT::f32) {
8586 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
8587 // the result back to FR32 register. It's only worth matching if the
8588 // result has a single use which is a store or a bitcast to i32. And in
8589 // the case of a store, it's not worth it if the index is a constant 0,
8590 // because a MOVSSmr can be used instead, which is smaller and faster.
8591 if (!Op.hasOneUse())
8593 SDNode *User = *Op.getNode()->use_begin();
8594 if ((User->getOpcode() != ISD::STORE ||
8595 (isa<ConstantSDNode>(Op.getOperand(1)) &&
8596 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
8597 (User->getOpcode() != ISD::BITCAST ||
8598 User->getValueType(0) != MVT::i32))
8600 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8601 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
8604 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
8607 if (VT == MVT::i32 || VT == MVT::i64) {
8608 // ExtractPS/pextrq works with constant index.
8609 if (isa<ConstantSDNode>(Op.getOperand(1)))
8615 /// Extract one bit from mask vector, like v16i1 or v8i1.
8616 /// AVX-512 feature.
8618 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
8619 SDValue Vec = Op.getOperand(0);
8621 MVT VecVT = Vec.getSimpleValueType();
8622 SDValue Idx = Op.getOperand(1);
8623 MVT EltVT = Op.getSimpleValueType();
8625 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
8627 // variable index can't be handled in mask registers,
8628 // extend vector to VR512
8629 if (!isa<ConstantSDNode>(Idx)) {
8630 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
8631 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
8632 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
8633 ExtVT.getVectorElementType(), Ext, Idx);
8634 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
8637 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8638 const TargetRegisterClass* rc = getRegClassFor(VecVT);
8639 unsigned MaxSift = rc->getSize()*8 - 1;
8640 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
8641 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8642 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
8643 DAG.getConstant(MaxSift, MVT::i8));
8644 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
8645 DAG.getIntPtrConstant(0));
8649 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
8650 SelectionDAG &DAG) const {
8652 SDValue Vec = Op.getOperand(0);
8653 MVT VecVT = Vec.getSimpleValueType();
8654 SDValue Idx = Op.getOperand(1);
8656 if (Op.getSimpleValueType() == MVT::i1)
8657 return ExtractBitFromMaskVector(Op, DAG);
8659 if (!isa<ConstantSDNode>(Idx)) {
8660 if (VecVT.is512BitVector() ||
8661 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
8662 VecVT.getVectorElementType().getSizeInBits() == 32)) {
8665 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
8666 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
8667 MaskEltVT.getSizeInBits());
8669 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
8670 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
8671 getZeroVector(MaskVT, Subtarget, DAG, dl),
8672 Idx, DAG.getConstant(0, getPointerTy()));
8673 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
8674 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
8675 Perm, DAG.getConstant(0, getPointerTy()));
8680 // If this is a 256-bit vector result, first extract the 128-bit vector and
8681 // then extract the element from the 128-bit vector.
8682 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
8684 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8685 // Get the 128-bit vector.
8686 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
8687 MVT EltVT = VecVT.getVectorElementType();
8689 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
8691 //if (IdxVal >= NumElems/2)
8692 // IdxVal -= NumElems/2;
8693 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
8694 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
8695 DAG.getConstant(IdxVal, MVT::i32));
8698 assert(VecVT.is128BitVector() && "Unexpected vector length");
8700 if (Subtarget->hasSSE41()) {
8701 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
8706 MVT VT = Op.getSimpleValueType();
8707 // TODO: handle v16i8.
8708 if (VT.getSizeInBits() == 16) {
8709 SDValue Vec = Op.getOperand(0);
8710 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8712 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8713 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8714 DAG.getNode(ISD::BITCAST, dl,
8717 // Transform it so it match pextrw which produces a 32-bit result.
8718 MVT EltVT = MVT::i32;
8719 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
8720 Op.getOperand(0), Op.getOperand(1));
8721 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
8722 DAG.getValueType(VT));
8723 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8726 if (VT.getSizeInBits() == 32) {
8727 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8731 // SHUFPS the element to the lowest double word, then movss.
8732 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
8733 MVT VVT = Op.getOperand(0).getSimpleValueType();
8734 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8735 DAG.getUNDEF(VVT), Mask);
8736 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8737 DAG.getIntPtrConstant(0));
8740 if (VT.getSizeInBits() == 64) {
8741 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
8742 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
8743 // to match extract_elt for f64.
8744 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8748 // UNPCKHPD the element to the lowest double word, then movsd.
8749 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
8750 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
8751 int Mask[2] = { 1, -1 };
8752 MVT VVT = Op.getOperand(0).getSimpleValueType();
8753 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8754 DAG.getUNDEF(VVT), Mask);
8755 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8756 DAG.getIntPtrConstant(0));
8762 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8763 MVT VT = Op.getSimpleValueType();
8764 MVT EltVT = VT.getVectorElementType();
8767 SDValue N0 = Op.getOperand(0);
8768 SDValue N1 = Op.getOperand(1);
8769 SDValue N2 = Op.getOperand(2);
8771 if (!VT.is128BitVector())
8774 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
8775 isa<ConstantSDNode>(N2)) {
8777 if (VT == MVT::v8i16)
8778 Opc = X86ISD::PINSRW;
8779 else if (VT == MVT::v16i8)
8780 Opc = X86ISD::PINSRB;
8782 Opc = X86ISD::PINSRB;
8784 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
8786 if (N1.getValueType() != MVT::i32)
8787 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8788 if (N2.getValueType() != MVT::i32)
8789 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8790 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
8793 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
8794 // Bits [7:6] of the constant are the source select. This will always be
8795 // zero here. The DAG Combiner may combine an extract_elt index into these
8796 // bits. For example (insert (extract, 3), 2) could be matched by putting
8797 // the '3' into bits [7:6] of X86ISD::INSERTPS.
8798 // Bits [5:4] of the constant are the destination select. This is the
8799 // value of the incoming immediate.
8800 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
8801 // combine either bitwise AND or insert of float 0.0 to set these bits.
8802 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
8803 // Create this as a scalar to vector..
8804 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
8805 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
8808 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
8809 // PINSR* works with constant index.
8815 /// Insert one bit to mask vector, like v16i1 or v8i1.
8816 /// AVX-512 feature.
8818 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
8820 SDValue Vec = Op.getOperand(0);
8821 SDValue Elt = Op.getOperand(1);
8822 SDValue Idx = Op.getOperand(2);
8823 MVT VecVT = Vec.getSimpleValueType();
8825 if (!isa<ConstantSDNode>(Idx)) {
8826 // Non constant index. Extend source and destination,
8827 // insert element and then truncate the result.
8828 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
8829 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
8830 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
8831 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
8832 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
8833 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
8836 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8837 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
8838 if (Vec.getOpcode() == ISD::UNDEF)
8839 return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8840 DAG.getConstant(IdxVal, MVT::i8));
8841 const TargetRegisterClass* rc = getRegClassFor(VecVT);
8842 unsigned MaxSift = rc->getSize()*8 - 1;
8843 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8844 DAG.getConstant(MaxSift, MVT::i8));
8845 EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
8846 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8847 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
8850 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
8851 MVT VT = Op.getSimpleValueType();
8852 MVT EltVT = VT.getVectorElementType();
8854 if (EltVT == MVT::i1)
8855 return InsertBitToMaskVector(Op, DAG);
8858 SDValue N0 = Op.getOperand(0);
8859 SDValue N1 = Op.getOperand(1);
8860 SDValue N2 = Op.getOperand(2);
8862 // If this is a 256-bit vector result, first extract the 128-bit vector,
8863 // insert the element into the extracted half and then place it back.
8864 if (VT.is256BitVector() || VT.is512BitVector()) {
8865 if (!isa<ConstantSDNode>(N2))
8868 // Get the desired 128-bit vector half.
8869 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
8870 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
8872 // Insert the element into the desired half.
8873 unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
8874 unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
8876 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
8877 DAG.getConstant(IdxIn128, MVT::i32));
8879 // Insert the changed part back to the 256-bit vector
8880 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
8883 if (Subtarget->hasSSE41())
8884 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
8886 if (EltVT == MVT::i8)
8889 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
8890 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
8891 // as its second argument.
8892 if (N1.getValueType() != MVT::i32)
8893 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8894 if (N2.getValueType() != MVT::i32)
8895 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8896 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
8901 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
8903 MVT OpVT = Op.getSimpleValueType();
8905 // If this is a 256-bit vector result, first insert into a 128-bit
8906 // vector and then insert into the 256-bit vector.
8907 if (!OpVT.is128BitVector()) {
8908 // Insert into a 128-bit vector.
8909 unsigned SizeFactor = OpVT.getSizeInBits()/128;
8910 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
8911 OpVT.getVectorNumElements() / SizeFactor);
8913 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
8915 // Insert the 128-bit vector.
8916 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
8919 if (OpVT == MVT::v1i64 &&
8920 Op.getOperand(0).getValueType() == MVT::i64)
8921 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
8923 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
8924 assert(OpVT.is128BitVector() && "Expected an SSE type!");
8925 return DAG.getNode(ISD::BITCAST, dl, OpVT,
8926 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
8929 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
8930 // a simple subregister reference or explicit instructions to grab
8931 // upper bits of a vector.
8932 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8933 SelectionDAG &DAG) {
8935 SDValue In = Op.getOperand(0);
8936 SDValue Idx = Op.getOperand(1);
8937 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8938 MVT ResVT = Op.getSimpleValueType();
8939 MVT InVT = In.getSimpleValueType();
8941 if (Subtarget->hasFp256()) {
8942 if (ResVT.is128BitVector() &&
8943 (InVT.is256BitVector() || InVT.is512BitVector()) &&
8944 isa<ConstantSDNode>(Idx)) {
8945 return Extract128BitVector(In, IdxVal, DAG, dl);
8947 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
8948 isa<ConstantSDNode>(Idx)) {
8949 return Extract256BitVector(In, IdxVal, DAG, dl);
8955 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
8956 // simple superregister reference or explicit instructions to insert
8957 // the upper bits of a vector.
8958 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8959 SelectionDAG &DAG) {
8960 if (Subtarget->hasFp256()) {
8961 SDLoc dl(Op.getNode());
8962 SDValue Vec = Op.getNode()->getOperand(0);
8963 SDValue SubVec = Op.getNode()->getOperand(1);
8964 SDValue Idx = Op.getNode()->getOperand(2);
8966 if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8967 Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8968 SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8969 isa<ConstantSDNode>(Idx)) {
8970 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8971 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8974 if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8975 SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8976 isa<ConstantSDNode>(Idx)) {
8977 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8978 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8984 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8985 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8986 // one of the above mentioned nodes. It has to be wrapped because otherwise
8987 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8988 // be used to form addressing mode. These wrapped nodes will be selected
8991 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8992 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8994 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8996 unsigned char OpFlag = 0;
8997 unsigned WrapperKind = X86ISD::Wrapper;
8998 CodeModel::Model M = DAG.getTarget().getCodeModel();
9000 if (Subtarget->isPICStyleRIPRel() &&
9001 (M == CodeModel::Small || M == CodeModel::Kernel))
9002 WrapperKind = X86ISD::WrapperRIP;
9003 else if (Subtarget->isPICStyleGOT())
9004 OpFlag = X86II::MO_GOTOFF;
9005 else if (Subtarget->isPICStyleStubPIC())
9006 OpFlag = X86II::MO_PIC_BASE_OFFSET;
9008 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
9010 CP->getOffset(), OpFlag);
9012 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
9013 // With PIC, the address is actually $g + Offset.
9015 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9016 DAG.getNode(X86ISD::GlobalBaseReg,
9017 SDLoc(), getPointerTy()),
9024 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
9025 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
9027 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
9029 unsigned char OpFlag = 0;
9030 unsigned WrapperKind = X86ISD::Wrapper;
9031 CodeModel::Model M = DAG.getTarget().getCodeModel();
9033 if (Subtarget->isPICStyleRIPRel() &&
9034 (M == CodeModel::Small || M == CodeModel::Kernel))
9035 WrapperKind = X86ISD::WrapperRIP;
9036 else if (Subtarget->isPICStyleGOT())
9037 OpFlag = X86II::MO_GOTOFF;
9038 else if (Subtarget->isPICStyleStubPIC())
9039 OpFlag = X86II::MO_PIC_BASE_OFFSET;
9041 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
9044 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
9046 // With PIC, the address is actually $g + Offset.
9048 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9049 DAG.getNode(X86ISD::GlobalBaseReg,
9050 SDLoc(), getPointerTy()),
9057 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
9058 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
9060 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
9062 unsigned char OpFlag = 0;
9063 unsigned WrapperKind = X86ISD::Wrapper;
9064 CodeModel::Model M = DAG.getTarget().getCodeModel();
9066 if (Subtarget->isPICStyleRIPRel() &&
9067 (M == CodeModel::Small || M == CodeModel::Kernel)) {
9068 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
9069 OpFlag = X86II::MO_GOTPCREL;
9070 WrapperKind = X86ISD::WrapperRIP;
9071 } else if (Subtarget->isPICStyleGOT()) {
9072 OpFlag = X86II::MO_GOT;
9073 } else if (Subtarget->isPICStyleStubPIC()) {
9074 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
9075 } else if (Subtarget->isPICStyleStubNoDynamic()) {
9076 OpFlag = X86II::MO_DARWIN_NONLAZY;
9079 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
9082 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
9084 // With PIC, the address is actually $g + Offset.
9085 if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
9086 !Subtarget->is64Bit()) {
9087 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9088 DAG.getNode(X86ISD::GlobalBaseReg,
9089 SDLoc(), getPointerTy()),
9093 // For symbols that require a load from a stub to get the address, emit the
9095 if (isGlobalStubReference(OpFlag))
9096 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
9097 MachinePointerInfo::getGOT(), false, false, false, 0);
9103 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
9104 // Create the TargetBlockAddressAddress node.
9105 unsigned char OpFlags =
9106 Subtarget->ClassifyBlockAddressReference();
9107 CodeModel::Model M = DAG.getTarget().getCodeModel();
9108 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
9109 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
9111 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
9114 if (Subtarget->isPICStyleRIPRel() &&
9115 (M == CodeModel::Small || M == CodeModel::Kernel))
9116 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
9118 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
9120 // With PIC, the address is actually $g + Offset.
9121 if (isGlobalRelativeToPICBase(OpFlags)) {
9122 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
9123 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
9131 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
9132 int64_t Offset, SelectionDAG &DAG) const {
9133 // Create the TargetGlobalAddress node, folding in the constant
9134 // offset if it is legal.
9135 unsigned char OpFlags =
9136 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
9137 CodeModel::Model M = DAG.getTarget().getCodeModel();
9139 if (OpFlags == X86II::MO_NO_FLAG &&
9140 X86::isOffsetSuitableForCodeModel(Offset, M)) {
9141 // A direct static reference to a global.
9142 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
9145 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
9148 if (Subtarget->isPICStyleRIPRel() &&
9149 (M == CodeModel::Small || M == CodeModel::Kernel))
9150 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
9152 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
9154 // With PIC, the address is actually $g + Offset.
9155 if (isGlobalRelativeToPICBase(OpFlags)) {
9156 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
9157 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
9161 // For globals that require a load from a stub to get the address, emit the
9163 if (isGlobalStubReference(OpFlags))
9164 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
9165 MachinePointerInfo::getGOT(), false, false, false, 0);
9167 // If there was a non-zero offset that we didn't fold, create an explicit
9170 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
9171 DAG.getConstant(Offset, getPointerTy()));
9177 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
9178 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
9179 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
9180 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
9184 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
9185 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
9186 unsigned char OperandFlags, bool LocalDynamic = false) {
9187 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9188 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9190 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
9191 GA->getValueType(0),
9195 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
9199 SDValue Ops[] = { Chain, TGA, *InFlag };
9200 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
9202 SDValue Ops[] = { Chain, TGA };
9203 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
9206 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
9207 MFI->setAdjustsStack(true);
9209 SDValue Flag = Chain.getValue(1);
9210 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
9213 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
9215 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
9218 SDLoc dl(GA); // ? function entry point might be better
9219 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
9220 DAG.getNode(X86ISD::GlobalBaseReg,
9221 SDLoc(), PtrVT), InFlag);
9222 InFlag = Chain.getValue(1);
9224 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
9227 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
9229 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
9231 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
9232 X86::RAX, X86II::MO_TLSGD);
9235 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
9241 // Get the start address of the TLS block for this module.
9242 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
9243 .getInfo<X86MachineFunctionInfo>();
9244 MFI->incNumLocalDynamicTLSAccesses();
9248 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
9249 X86II::MO_TLSLD, /*LocalDynamic=*/true);
9252 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
9253 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
9254 InFlag = Chain.getValue(1);
9255 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
9256 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
9259 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
9263 unsigned char OperandFlags = X86II::MO_DTPOFF;
9264 unsigned WrapperKind = X86ISD::Wrapper;
9265 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
9266 GA->getValueType(0),
9267 GA->getOffset(), OperandFlags);
9268 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
9270 // Add x@dtpoff with the base.
9271 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
9274 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
9275 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
9276 const EVT PtrVT, TLSModel::Model model,
9277 bool is64Bit, bool isPIC) {
9280 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
9281 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
9282 is64Bit ? 257 : 256));
9284 SDValue ThreadPointer =
9285 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
9286 MachinePointerInfo(Ptr), false, false, false, 0);
9288 unsigned char OperandFlags = 0;
9289 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
9291 unsigned WrapperKind = X86ISD::Wrapper;
9292 if (model == TLSModel::LocalExec) {
9293 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
9294 } else if (model == TLSModel::InitialExec) {
9296 OperandFlags = X86II::MO_GOTTPOFF;
9297 WrapperKind = X86ISD::WrapperRIP;
9299 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
9302 llvm_unreachable("Unexpected model");
9305 // emit "addl x@ntpoff,%eax" (local exec)
9306 // or "addl x@indntpoff,%eax" (initial exec)
9307 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
9309 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
9310 GA->getOffset(), OperandFlags);
9311 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
9313 if (model == TLSModel::InitialExec) {
9314 if (isPIC && !is64Bit) {
9315 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
9316 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
9320 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
9321 MachinePointerInfo::getGOT(), false, false, false, 0);
9324 // The address of the thread local variable is the add of the thread
9325 // pointer with the offset of the variable.
9326 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
9330 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
9332 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
9333 const GlobalValue *GV = GA->getGlobal();
9335 if (Subtarget->isTargetELF()) {
9336 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
9339 case TLSModel::GeneralDynamic:
9340 if (Subtarget->is64Bit())
9341 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
9342 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
9343 case TLSModel::LocalDynamic:
9344 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
9345 Subtarget->is64Bit());
9346 case TLSModel::InitialExec:
9347 case TLSModel::LocalExec:
9348 return LowerToTLSExecModel(
9349 GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
9350 DAG.getTarget().getRelocationModel() == Reloc::PIC_);
9352 llvm_unreachable("Unknown TLS model.");
9355 if (Subtarget->isTargetDarwin()) {
9356 // Darwin only has one model of TLS. Lower to that.
9357 unsigned char OpFlag = 0;
9358 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
9359 X86ISD::WrapperRIP : X86ISD::Wrapper;
9361 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
9363 bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
9364 !Subtarget->is64Bit();
9366 OpFlag = X86II::MO_TLVP_PIC_BASE;
9368 OpFlag = X86II::MO_TLVP;
9370 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
9371 GA->getValueType(0),
9372 GA->getOffset(), OpFlag);
9373 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
9375 // With PIC32, the address is actually $g + Offset.
9377 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9378 DAG.getNode(X86ISD::GlobalBaseReg,
9379 SDLoc(), getPointerTy()),
9382 // Lowering the machine isd will make sure everything is in the right
9384 SDValue Chain = DAG.getEntryNode();
9385 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9386 SDValue Args[] = { Chain, Offset };
9387 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
9389 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
9390 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9391 MFI->setAdjustsStack(true);
9393 // And our return value (tls address) is in the standard call return value
9395 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
9396 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
9400 if (Subtarget->isTargetKnownWindowsMSVC() ||
9401 Subtarget->isTargetWindowsGNU()) {
9402 // Just use the implicit TLS architecture
9403 // Need to generate someting similar to:
9404 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
9406 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
9407 // mov rcx, qword [rdx+rcx*8]
9408 // mov eax, .tls$:tlsvar
9409 // [rax+rcx] contains the address
9410 // Windows 64bit: gs:0x58
9411 // Windows 32bit: fs:__tls_array
9414 SDValue Chain = DAG.getEntryNode();
9416 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
9417 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
9418 // use its literal value of 0x2C.
9419 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
9420 ? Type::getInt8PtrTy(*DAG.getContext(),
9422 : Type::getInt32PtrTy(*DAG.getContext(),
9426 Subtarget->is64Bit()
9427 ? DAG.getIntPtrConstant(0x58)
9428 : (Subtarget->isTargetWindowsGNU()
9429 ? DAG.getIntPtrConstant(0x2C)
9430 : DAG.getExternalSymbol("_tls_array", getPointerTy()));
9432 SDValue ThreadPointer =
9433 DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
9434 MachinePointerInfo(Ptr), false, false, false, 0);
9436 // Load the _tls_index variable
9437 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
9438 if (Subtarget->is64Bit())
9439 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
9440 IDX, MachinePointerInfo(), MVT::i32,
9443 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
9444 false, false, false, 0);
9446 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
9448 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
9450 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
9451 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
9452 false, false, false, 0);
9454 // Get the offset of start of .tls section
9455 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
9456 GA->getValueType(0),
9457 GA->getOffset(), X86II::MO_SECREL);
9458 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
9460 // The address of the thread local variable is the add of the thread
9461 // pointer with the offset of the variable.
9462 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
9465 llvm_unreachable("TLS not implemented for this target.");
9468 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
9469 /// and take a 2 x i32 value to shift plus a shift amount.
9470 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
9471 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
9472 MVT VT = Op.getSimpleValueType();
9473 unsigned VTBits = VT.getSizeInBits();
9475 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
9476 SDValue ShOpLo = Op.getOperand(0);
9477 SDValue ShOpHi = Op.getOperand(1);
9478 SDValue ShAmt = Op.getOperand(2);
9479 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
9480 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
9482 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
9483 DAG.getConstant(VTBits - 1, MVT::i8));
9484 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
9485 DAG.getConstant(VTBits - 1, MVT::i8))
9486 : DAG.getConstant(0, VT);
9489 if (Op.getOpcode() == ISD::SHL_PARTS) {
9490 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
9491 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
9493 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
9494 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
9497 // If the shift amount is larger or equal than the width of a part we can't
9498 // rely on the results of shld/shrd. Insert a test and select the appropriate
9499 // values for large shift amounts.
9500 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
9501 DAG.getConstant(VTBits, MVT::i8));
9502 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9503 AndNode, DAG.getConstant(0, MVT::i8));
9506 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9507 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
9508 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
9510 if (Op.getOpcode() == ISD::SHL_PARTS) {
9511 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
9512 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
9514 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
9515 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
9518 SDValue Ops[2] = { Lo, Hi };
9519 return DAG.getMergeValues(Ops, dl);
9522 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
9523 SelectionDAG &DAG) const {
9524 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
9526 if (SrcVT.isVector())
9529 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
9530 "Unknown SINT_TO_FP to lower!");
9532 // These are really Legal; return the operand so the caller accepts it as
9534 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
9536 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
9537 Subtarget->is64Bit()) {
9542 unsigned Size = SrcVT.getSizeInBits()/8;
9543 MachineFunction &MF = DAG.getMachineFunction();
9544 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
9545 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9546 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9548 MachinePointerInfo::getFixedStack(SSFI),
9550 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
9553 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
9555 SelectionDAG &DAG) const {
9559 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
9561 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
9563 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
9565 unsigned ByteSize = SrcVT.getSizeInBits()/8;
9567 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
9568 MachineMemOperand *MMO;
9570 int SSFI = FI->getIndex();
9572 DAG.getMachineFunction()
9573 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9574 MachineMemOperand::MOLoad, ByteSize, ByteSize);
9576 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
9577 StackSlot = StackSlot.getOperand(1);
9579 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
9580 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
9582 Tys, Ops, SrcVT, MMO);
9585 Chain = Result.getValue(1);
9586 SDValue InFlag = Result.getValue(2);
9588 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
9589 // shouldn't be necessary except that RFP cannot be live across
9590 // multiple blocks. When stackifier is fixed, they can be uncoupled.
9591 MachineFunction &MF = DAG.getMachineFunction();
9592 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
9593 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
9594 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9595 Tys = DAG.getVTList(MVT::Other);
9597 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
9599 MachineMemOperand *MMO =
9600 DAG.getMachineFunction()
9601 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9602 MachineMemOperand::MOStore, SSFISize, SSFISize);
9604 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
9605 Ops, Op.getValueType(), MMO);
9606 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
9607 MachinePointerInfo::getFixedStack(SSFI),
9608 false, false, false, 0);
9614 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
9615 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
9616 SelectionDAG &DAG) const {
9617 // This algorithm is not obvious. Here it is what we're trying to output:
9620 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
9621 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
9625 pshufd $0x4e, %xmm0, %xmm1
9631 LLVMContext *Context = DAG.getContext();
9633 // Build some magic constants.
9634 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
9635 Constant *C0 = ConstantDataVector::get(*Context, CV0);
9636 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
9638 SmallVector<Constant*,2> CV1;
9640 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9641 APInt(64, 0x4330000000000000ULL))));
9643 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9644 APInt(64, 0x4530000000000000ULL))));
9645 Constant *C1 = ConstantVector::get(CV1);
9646 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
9648 // Load the 64-bit value into an XMM register.
9649 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
9651 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
9652 MachinePointerInfo::getConstantPool(),
9653 false, false, false, 16);
9654 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
9655 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
9658 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
9659 MachinePointerInfo::getConstantPool(),
9660 false, false, false, 16);
9661 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
9662 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
9665 if (Subtarget->hasSSE3()) {
9666 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
9667 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
9669 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
9670 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
9672 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
9673 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
9677 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
9678 DAG.getIntPtrConstant(0));
9681 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
9682 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
9683 SelectionDAG &DAG) const {
9685 // FP constant to bias correct the final result.
9686 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
9689 // Load the 32-bit value into an XMM register.
9690 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
9693 // Zero out the upper parts of the register.
9694 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
9696 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9697 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
9698 DAG.getIntPtrConstant(0));
9700 // Or the load with the bias.
9701 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
9702 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9703 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9705 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9706 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9707 MVT::v2f64, Bias)));
9708 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9709 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
9710 DAG.getIntPtrConstant(0));
9712 // Subtract the bias.
9713 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
9715 // Handle final rounding.
9716 EVT DestVT = Op.getValueType();
9718 if (DestVT.bitsLT(MVT::f64))
9719 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
9720 DAG.getIntPtrConstant(0));
9721 if (DestVT.bitsGT(MVT::f64))
9722 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
9724 // Handle final rounding.
9728 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
9729 SelectionDAG &DAG) const {
9730 SDValue N0 = Op.getOperand(0);
9731 MVT SVT = N0.getSimpleValueType();
9734 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
9735 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
9736 "Custom UINT_TO_FP is not supported!");
9738 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
9739 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
9740 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
9743 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
9744 SelectionDAG &DAG) const {
9745 SDValue N0 = Op.getOperand(0);
9748 if (Op.getValueType().isVector())
9749 return lowerUINT_TO_FP_vec(Op, DAG);
9751 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
9752 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
9753 // the optimization here.
9754 if (DAG.SignBitIsZero(N0))
9755 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
9757 MVT SrcVT = N0.getSimpleValueType();
9758 MVT DstVT = Op.getSimpleValueType();
9759 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
9760 return LowerUINT_TO_FP_i64(Op, DAG);
9761 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
9762 return LowerUINT_TO_FP_i32(Op, DAG);
9763 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
9766 // Make a 64-bit buffer, and use it to build an FILD.
9767 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
9768 if (SrcVT == MVT::i32) {
9769 SDValue WordOff = DAG.getConstant(4, getPointerTy());
9770 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
9771 getPointerTy(), StackSlot, WordOff);
9772 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9773 StackSlot, MachinePointerInfo(),
9775 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
9776 OffsetSlot, MachinePointerInfo(),
9778 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
9782 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
9783 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9784 StackSlot, MachinePointerInfo(),
9786 // For i64 source, we need to add the appropriate power of 2 if the input
9787 // was negative. This is the same as the optimization in
9788 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
9789 // we must be careful to do the computation in x87 extended precision, not
9790 // in SSE. (The generic code can't know it's OK to do this, or how to.)
9791 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
9792 MachineMemOperand *MMO =
9793 DAG.getMachineFunction()
9794 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9795 MachineMemOperand::MOLoad, 8, 8);
9797 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
9798 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
9799 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
9802 APInt FF(32, 0x5F800000ULL);
9804 // Check whether the sign bit is set.
9805 SDValue SignSet = DAG.getSetCC(dl,
9806 getSetCCResultType(*DAG.getContext(), MVT::i64),
9807 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
9810 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
9811 SDValue FudgePtr = DAG.getConstantPool(
9812 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
9815 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
9816 SDValue Zero = DAG.getIntPtrConstant(0);
9817 SDValue Four = DAG.getIntPtrConstant(4);
9818 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
9820 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
9822 // Load the value out, extending it from f32 to f80.
9823 // FIXME: Avoid the extend by constructing the right constant pool?
9824 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
9825 FudgePtr, MachinePointerInfo::getConstantPool(),
9826 MVT::f32, false, false, 4);
9827 // Extend everything to 80 bits to force it to be done on x87.
9828 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
9829 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
9832 std::pair<SDValue,SDValue>
9833 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
9834 bool IsSigned, bool IsReplace) const {
9837 EVT DstTy = Op.getValueType();
9839 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
9840 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
9844 assert(DstTy.getSimpleVT() <= MVT::i64 &&
9845 DstTy.getSimpleVT() >= MVT::i16 &&
9846 "Unknown FP_TO_INT to lower!");
9848 // These are really Legal.
9849 if (DstTy == MVT::i32 &&
9850 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9851 return std::make_pair(SDValue(), SDValue());
9852 if (Subtarget->is64Bit() &&
9853 DstTy == MVT::i64 &&
9854 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9855 return std::make_pair(SDValue(), SDValue());
9857 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
9858 // stack slot, or into the FTOL runtime function.
9859 MachineFunction &MF = DAG.getMachineFunction();
9860 unsigned MemSize = DstTy.getSizeInBits()/8;
9861 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9862 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9865 if (!IsSigned && isIntegerTypeFTOL(DstTy))
9866 Opc = X86ISD::WIN_FTOL;
9868 switch (DstTy.getSimpleVT().SimpleTy) {
9869 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
9870 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
9871 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
9872 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
9875 SDValue Chain = DAG.getEntryNode();
9876 SDValue Value = Op.getOperand(0);
9877 EVT TheVT = Op.getOperand(0).getValueType();
9878 // FIXME This causes a redundant load/store if the SSE-class value is already
9879 // in memory, such as if it is on the callstack.
9880 if (isScalarFPTypeInSSEReg(TheVT)) {
9881 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
9882 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
9883 MachinePointerInfo::getFixedStack(SSFI),
9885 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
9887 Chain, StackSlot, DAG.getValueType(TheVT)
9890 MachineMemOperand *MMO =
9891 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9892 MachineMemOperand::MOLoad, MemSize, MemSize);
9893 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
9894 Chain = Value.getValue(1);
9895 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9896 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9899 MachineMemOperand *MMO =
9900 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9901 MachineMemOperand::MOStore, MemSize, MemSize);
9903 if (Opc != X86ISD::WIN_FTOL) {
9904 // Build the FP_TO_INT*_IN_MEM
9905 SDValue Ops[] = { Chain, Value, StackSlot };
9906 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
9908 return std::make_pair(FIST, StackSlot);
9910 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
9911 DAG.getVTList(MVT::Other, MVT::Glue),
9913 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
9914 MVT::i32, ftol.getValue(1));
9915 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
9916 MVT::i32, eax.getValue(2));
9917 SDValue Ops[] = { eax, edx };
9918 SDValue pair = IsReplace
9919 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
9920 : DAG.getMergeValues(Ops, DL);
9921 return std::make_pair(pair, SDValue());
9925 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
9926 const X86Subtarget *Subtarget) {
9927 MVT VT = Op->getSimpleValueType(0);
9928 SDValue In = Op->getOperand(0);
9929 MVT InVT = In.getSimpleValueType();
9932 // Optimize vectors in AVX mode:
9935 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
9936 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
9937 // Concat upper and lower parts.
9940 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
9941 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
9942 // Concat upper and lower parts.
9945 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
9946 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
9947 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
9950 if (Subtarget->hasInt256())
9951 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
9953 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
9954 SDValue Undef = DAG.getUNDEF(InVT);
9955 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9956 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9957 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9959 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9960 VT.getVectorNumElements()/2);
9962 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9963 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9965 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9968 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9969 SelectionDAG &DAG) {
9970 MVT VT = Op->getSimpleValueType(0);
9971 SDValue In = Op->getOperand(0);
9972 MVT InVT = In.getSimpleValueType();
9974 unsigned int NumElts = VT.getVectorNumElements();
9975 if (NumElts != 8 && NumElts != 16)
9978 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9979 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9981 EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9982 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9983 // Now we have only mask extension
9984 assert(InVT.getVectorElementType() == MVT::i1);
9985 SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9986 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9987 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9988 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9989 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9990 MachinePointerInfo::getConstantPool(),
9991 false, false, false, Alignment);
9993 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9994 if (VT.is512BitVector())
9996 return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9999 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
10000 SelectionDAG &DAG) {
10001 if (Subtarget->hasFp256()) {
10002 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
10010 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
10011 SelectionDAG &DAG) {
10013 MVT VT = Op.getSimpleValueType();
10014 SDValue In = Op.getOperand(0);
10015 MVT SVT = In.getSimpleValueType();
10017 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
10018 return LowerZERO_EXTEND_AVX512(Op, DAG);
10020 if (Subtarget->hasFp256()) {
10021 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
10026 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
10027 VT.getVectorNumElements() != SVT.getVectorNumElements());
10031 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
10033 MVT VT = Op.getSimpleValueType();
10034 SDValue In = Op.getOperand(0);
10035 MVT InVT = In.getSimpleValueType();
10037 if (VT == MVT::i1) {
10038 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
10039 "Invalid scalar TRUNCATE operation");
10040 if (InVT == MVT::i32)
10042 if (InVT.getSizeInBits() == 64)
10043 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
10044 else if (InVT.getSizeInBits() < 32)
10045 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
10046 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
10048 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
10049 "Invalid TRUNCATE operation");
10051 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
10052 if (VT.getVectorElementType().getSizeInBits() >=8)
10053 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
10055 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
10056 unsigned NumElts = InVT.getVectorNumElements();
10057 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
10058 if (InVT.getSizeInBits() < 512) {
10059 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
10060 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
10064 SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
10065 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
10066 SDValue CP = DAG.getConstantPool(C, getPointerTy());
10067 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
10068 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
10069 MachinePointerInfo::getConstantPool(),
10070 false, false, false, Alignment);
10071 SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
10072 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
10073 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
10076 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
10077 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
10078 if (Subtarget->hasInt256()) {
10079 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
10080 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
10081 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
10083 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
10084 DAG.getIntPtrConstant(0));
10087 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
10088 DAG.getIntPtrConstant(0));
10089 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
10090 DAG.getIntPtrConstant(2));
10091 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
10092 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
10093 static const int ShufMask[] = {0, 2, 4, 6};
10094 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
10097 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
10098 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
10099 if (Subtarget->hasInt256()) {
10100 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
10102 SmallVector<SDValue,32> pshufbMask;
10103 for (unsigned i = 0; i < 2; ++i) {
10104 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
10105 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
10106 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
10107 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
10108 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
10109 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
10110 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
10111 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
10112 for (unsigned j = 0; j < 8; ++j)
10113 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
10115 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
10116 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
10117 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
10119 static const int ShufMask[] = {0, 2, -1, -1};
10120 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
10122 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
10123 DAG.getIntPtrConstant(0));
10124 return DAG.getNode(ISD::BITCAST, DL, VT, In);
10127 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
10128 DAG.getIntPtrConstant(0));
10130 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
10131 DAG.getIntPtrConstant(4));
10133 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
10134 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
10136 // The PSHUFB mask:
10137 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
10138 -1, -1, -1, -1, -1, -1, -1, -1};
10140 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
10141 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
10142 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
10144 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
10145 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
10147 // The MOVLHPS Mask:
10148 static const int ShufMask2[] = {0, 1, 4, 5};
10149 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
10150 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
10153 // Handle truncation of V256 to V128 using shuffles.
10154 if (!VT.is128BitVector() || !InVT.is256BitVector())
10157 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
10159 unsigned NumElems = VT.getVectorNumElements();
10160 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
10162 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
10163 // Prepare truncation shuffle mask
10164 for (unsigned i = 0; i != NumElems; ++i)
10165 MaskVec[i] = i * 2;
10166 SDValue V = DAG.getVectorShuffle(NVT, DL,
10167 DAG.getNode(ISD::BITCAST, DL, NVT, In),
10168 DAG.getUNDEF(NVT), &MaskVec[0]);
10169 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
10170 DAG.getIntPtrConstant(0));
10173 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
10174 SelectionDAG &DAG) const {
10175 assert(!Op.getSimpleValueType().isVector());
10177 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
10178 /*IsSigned=*/ true, /*IsReplace=*/ false);
10179 SDValue FIST = Vals.first, StackSlot = Vals.second;
10180 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
10181 if (!FIST.getNode()) return Op;
10183 if (StackSlot.getNode())
10184 // Load the result.
10185 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
10186 FIST, StackSlot, MachinePointerInfo(),
10187 false, false, false, 0);
10189 // The node is the result.
10193 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
10194 SelectionDAG &DAG) const {
10195 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
10196 /*IsSigned=*/ false, /*IsReplace=*/ false);
10197 SDValue FIST = Vals.first, StackSlot = Vals.second;
10198 assert(FIST.getNode() && "Unexpected failure");
10200 if (StackSlot.getNode())
10201 // Load the result.
10202 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
10203 FIST, StackSlot, MachinePointerInfo(),
10204 false, false, false, 0);
10206 // The node is the result.
10210 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
10212 MVT VT = Op.getSimpleValueType();
10213 SDValue In = Op.getOperand(0);
10214 MVT SVT = In.getSimpleValueType();
10216 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
10218 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
10219 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
10220 In, DAG.getUNDEF(SVT)));
10223 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
10224 LLVMContext *Context = DAG.getContext();
10226 MVT VT = Op.getSimpleValueType();
10228 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
10229 if (VT.isVector()) {
10230 EltVT = VT.getVectorElementType();
10231 NumElts = VT.getVectorNumElements();
10234 if (EltVT == MVT::f64)
10235 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
10236 APInt(64, ~(1ULL << 63))));
10238 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
10239 APInt(32, ~(1U << 31))));
10240 C = ConstantVector::getSplat(NumElts, C);
10241 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10242 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
10243 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
10244 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10245 MachinePointerInfo::getConstantPool(),
10246 false, false, false, Alignment);
10247 if (VT.isVector()) {
10248 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
10249 return DAG.getNode(ISD::BITCAST, dl, VT,
10250 DAG.getNode(ISD::AND, dl, ANDVT,
10251 DAG.getNode(ISD::BITCAST, dl, ANDVT,
10253 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
10255 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
10258 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
10259 LLVMContext *Context = DAG.getContext();
10261 MVT VT = Op.getSimpleValueType();
10263 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
10264 if (VT.isVector()) {
10265 EltVT = VT.getVectorElementType();
10266 NumElts = VT.getVectorNumElements();
10269 if (EltVT == MVT::f64)
10270 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
10271 APInt(64, 1ULL << 63)));
10273 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
10274 APInt(32, 1U << 31)));
10275 C = ConstantVector::getSplat(NumElts, C);
10276 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10277 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
10278 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
10279 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10280 MachinePointerInfo::getConstantPool(),
10281 false, false, false, Alignment);
10282 if (VT.isVector()) {
10283 MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
10284 return DAG.getNode(ISD::BITCAST, dl, VT,
10285 DAG.getNode(ISD::XOR, dl, XORVT,
10286 DAG.getNode(ISD::BITCAST, dl, XORVT,
10288 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
10291 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
10294 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
10295 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10296 LLVMContext *Context = DAG.getContext();
10297 SDValue Op0 = Op.getOperand(0);
10298 SDValue Op1 = Op.getOperand(1);
10300 MVT VT = Op.getSimpleValueType();
10301 MVT SrcVT = Op1.getSimpleValueType();
10303 // If second operand is smaller, extend it first.
10304 if (SrcVT.bitsLT(VT)) {
10305 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
10308 // And if it is bigger, shrink it first.
10309 if (SrcVT.bitsGT(VT)) {
10310 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
10314 // At this point the operands and the result should have the same
10315 // type, and that won't be f80 since that is not custom lowered.
10317 // First get the sign bit of second operand.
10318 SmallVector<Constant*,4> CV;
10319 if (SrcVT == MVT::f64) {
10320 const fltSemantics &Sem = APFloat::IEEEdouble;
10321 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
10322 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
10324 const fltSemantics &Sem = APFloat::IEEEsingle;
10325 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
10326 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10327 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10328 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10330 Constant *C = ConstantVector::get(CV);
10331 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
10332 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
10333 MachinePointerInfo::getConstantPool(),
10334 false, false, false, 16);
10335 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
10337 // Shift sign bit right or left if the two operands have different types.
10338 if (SrcVT.bitsGT(VT)) {
10339 // Op0 is MVT::f32, Op1 is MVT::f64.
10340 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
10341 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
10342 DAG.getConstant(32, MVT::i32));
10343 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
10344 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
10345 DAG.getIntPtrConstant(0));
10348 // Clear first operand sign bit.
10350 if (VT == MVT::f64) {
10351 const fltSemantics &Sem = APFloat::IEEEdouble;
10352 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
10353 APInt(64, ~(1ULL << 63)))));
10354 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
10356 const fltSemantics &Sem = APFloat::IEEEsingle;
10357 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
10358 APInt(32, ~(1U << 31)))));
10359 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10360 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10361 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10363 C = ConstantVector::get(CV);
10364 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
10365 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10366 MachinePointerInfo::getConstantPool(),
10367 false, false, false, 16);
10368 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
10370 // Or the value with the sign bit.
10371 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
10374 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
10375 SDValue N0 = Op.getOperand(0);
10377 MVT VT = Op.getSimpleValueType();
10379 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
10380 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
10381 DAG.getConstant(1, VT));
10382 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
10385 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
10387 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
10388 SelectionDAG &DAG) {
10389 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
10391 if (!Subtarget->hasSSE41())
10394 if (!Op->hasOneUse())
10397 SDNode *N = Op.getNode();
10400 SmallVector<SDValue, 8> Opnds;
10401 DenseMap<SDValue, unsigned> VecInMap;
10402 SmallVector<SDValue, 8> VecIns;
10403 EVT VT = MVT::Other;
10405 // Recognize a special case where a vector is casted into wide integer to
10407 Opnds.push_back(N->getOperand(0));
10408 Opnds.push_back(N->getOperand(1));
10410 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
10411 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
10412 // BFS traverse all OR'd operands.
10413 if (I->getOpcode() == ISD::OR) {
10414 Opnds.push_back(I->getOperand(0));
10415 Opnds.push_back(I->getOperand(1));
10416 // Re-evaluate the number of nodes to be traversed.
10417 e += 2; // 2 more nodes (LHS and RHS) are pushed.
10421 // Quit if a non-EXTRACT_VECTOR_ELT
10422 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10425 // Quit if without a constant index.
10426 SDValue Idx = I->getOperand(1);
10427 if (!isa<ConstantSDNode>(Idx))
10430 SDValue ExtractedFromVec = I->getOperand(0);
10431 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
10432 if (M == VecInMap.end()) {
10433 VT = ExtractedFromVec.getValueType();
10434 // Quit if not 128/256-bit vector.
10435 if (!VT.is128BitVector() && !VT.is256BitVector())
10437 // Quit if not the same type.
10438 if (VecInMap.begin() != VecInMap.end() &&
10439 VT != VecInMap.begin()->first.getValueType())
10441 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
10442 VecIns.push_back(ExtractedFromVec);
10444 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
10447 assert((VT.is128BitVector() || VT.is256BitVector()) &&
10448 "Not extracted from 128-/256-bit vector.");
10450 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
10452 for (DenseMap<SDValue, unsigned>::const_iterator
10453 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
10454 // Quit if not all elements are used.
10455 if (I->second != FullMask)
10459 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
10461 // Cast all vectors into TestVT for PTEST.
10462 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
10463 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
10465 // If more than one full vectors are evaluated, OR them first before PTEST.
10466 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
10467 // Each iteration will OR 2 nodes and append the result until there is only
10468 // 1 node left, i.e. the final OR'd value of all vectors.
10469 SDValue LHS = VecIns[Slot];
10470 SDValue RHS = VecIns[Slot + 1];
10471 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
10474 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
10475 VecIns.back(), VecIns.back());
10478 /// \brief return true if \c Op has a use that doesn't just read flags.
10479 static bool hasNonFlagsUse(SDValue Op) {
10480 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
10482 SDNode *User = *UI;
10483 unsigned UOpNo = UI.getOperandNo();
10484 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
10485 // Look pass truncate.
10486 UOpNo = User->use_begin().getOperandNo();
10487 User = *User->use_begin();
10490 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
10491 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
10497 /// Emit nodes that will be selected as "test Op0,Op0", or something
10499 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
10500 SelectionDAG &DAG) const {
10501 if (Op.getValueType() == MVT::i1)
10502 // KORTEST instruction should be selected
10503 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10504 DAG.getConstant(0, Op.getValueType()));
10506 // CF and OF aren't always set the way we want. Determine which
10507 // of these we need.
10508 bool NeedCF = false;
10509 bool NeedOF = false;
10512 case X86::COND_A: case X86::COND_AE:
10513 case X86::COND_B: case X86::COND_BE:
10516 case X86::COND_G: case X86::COND_GE:
10517 case X86::COND_L: case X86::COND_LE:
10518 case X86::COND_O: case X86::COND_NO: {
10519 // Check if we really need to set the
10520 // Overflow flag. If NoSignedWrap is present
10521 // that is not actually needed.
10522 switch (Op->getOpcode()) {
10527 const BinaryWithFlagsSDNode *BinNode =
10528 cast<BinaryWithFlagsSDNode>(Op.getNode());
10529 if (BinNode->hasNoSignedWrap())
10539 // See if we can use the EFLAGS value from the operand instead of
10540 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
10541 // we prove that the arithmetic won't overflow, we can't use OF or CF.
10542 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
10543 // Emit a CMP with 0, which is the TEST pattern.
10544 //if (Op.getValueType() == MVT::i1)
10545 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
10546 // DAG.getConstant(0, MVT::i1));
10547 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10548 DAG.getConstant(0, Op.getValueType()));
10550 unsigned Opcode = 0;
10551 unsigned NumOperands = 0;
10553 // Truncate operations may prevent the merge of the SETCC instruction
10554 // and the arithmetic instruction before it. Attempt to truncate the operands
10555 // of the arithmetic instruction and use a reduced bit-width instruction.
10556 bool NeedTruncation = false;
10557 SDValue ArithOp = Op;
10558 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
10559 SDValue Arith = Op->getOperand(0);
10560 // Both the trunc and the arithmetic op need to have one user each.
10561 if (Arith->hasOneUse())
10562 switch (Arith.getOpcode()) {
10569 NeedTruncation = true;
10575 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
10576 // which may be the result of a CAST. We use the variable 'Op', which is the
10577 // non-casted variable when we check for possible users.
10578 switch (ArithOp.getOpcode()) {
10580 // Due to an isel shortcoming, be conservative if this add is likely to be
10581 // selected as part of a load-modify-store instruction. When the root node
10582 // in a match is a store, isel doesn't know how to remap non-chain non-flag
10583 // uses of other nodes in the match, such as the ADD in this case. This
10584 // leads to the ADD being left around and reselected, with the result being
10585 // two adds in the output. Alas, even if none our users are stores, that
10586 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
10587 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
10588 // climbing the DAG back to the root, and it doesn't seem to be worth the
10590 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
10591 UE = Op.getNode()->use_end(); UI != UE; ++UI)
10592 if (UI->getOpcode() != ISD::CopyToReg &&
10593 UI->getOpcode() != ISD::SETCC &&
10594 UI->getOpcode() != ISD::STORE)
10597 if (ConstantSDNode *C =
10598 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
10599 // An add of one will be selected as an INC.
10600 if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
10601 Opcode = X86ISD::INC;
10606 // An add of negative one (subtract of one) will be selected as a DEC.
10607 if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
10608 Opcode = X86ISD::DEC;
10614 // Otherwise use a regular EFLAGS-setting add.
10615 Opcode = X86ISD::ADD;
10620 // If we have a constant logical shift that's only used in a comparison
10621 // against zero turn it into an equivalent AND. This allows turning it into
10622 // a TEST instruction later.
10623 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
10624 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
10625 EVT VT = Op.getValueType();
10626 unsigned BitWidth = VT.getSizeInBits();
10627 unsigned ShAmt = Op->getConstantOperandVal(1);
10628 if (ShAmt >= BitWidth) // Avoid undefined shifts.
10630 APInt Mask = ArithOp.getOpcode() == ISD::SRL
10631 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
10632 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
10633 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
10635 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
10636 DAG.getConstant(Mask, VT));
10637 DAG.ReplaceAllUsesWith(Op, New);
10643 // If the primary and result isn't used, don't bother using X86ISD::AND,
10644 // because a TEST instruction will be better.
10645 if (!hasNonFlagsUse(Op))
10651 // Due to the ISEL shortcoming noted above, be conservative if this op is
10652 // likely to be selected as part of a load-modify-store instruction.
10653 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
10654 UE = Op.getNode()->use_end(); UI != UE; ++UI)
10655 if (UI->getOpcode() == ISD::STORE)
10658 // Otherwise use a regular EFLAGS-setting instruction.
10659 switch (ArithOp.getOpcode()) {
10660 default: llvm_unreachable("unexpected operator!");
10661 case ISD::SUB: Opcode = X86ISD::SUB; break;
10662 case ISD::XOR: Opcode = X86ISD::XOR; break;
10663 case ISD::AND: Opcode = X86ISD::AND; break;
10665 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
10666 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
10667 if (EFLAGS.getNode())
10670 Opcode = X86ISD::OR;
10684 return SDValue(Op.getNode(), 1);
10690 // If we found that truncation is beneficial, perform the truncation and
10692 if (NeedTruncation) {
10693 EVT VT = Op.getValueType();
10694 SDValue WideVal = Op->getOperand(0);
10695 EVT WideVT = WideVal.getValueType();
10696 unsigned ConvertedOp = 0;
10697 // Use a target machine opcode to prevent further DAGCombine
10698 // optimizations that may separate the arithmetic operations
10699 // from the setcc node.
10700 switch (WideVal.getOpcode()) {
10702 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
10703 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
10704 case ISD::AND: ConvertedOp = X86ISD::AND; break;
10705 case ISD::OR: ConvertedOp = X86ISD::OR; break;
10706 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
10710 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10711 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
10712 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
10713 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
10714 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
10720 // Emit a CMP with 0, which is the TEST pattern.
10721 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10722 DAG.getConstant(0, Op.getValueType()));
10724 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10725 SmallVector<SDValue, 4> Ops;
10726 for (unsigned i = 0; i != NumOperands; ++i)
10727 Ops.push_back(Op.getOperand(i));
10729 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
10730 DAG.ReplaceAllUsesWith(Op, New);
10731 return SDValue(New.getNode(), 1);
10734 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
10736 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
10737 SDLoc dl, SelectionDAG &DAG) const {
10738 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
10739 if (C->getAPIntValue() == 0)
10740 return EmitTest(Op0, X86CC, dl, DAG);
10742 if (Op0.getValueType() == MVT::i1)
10743 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
10746 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
10747 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
10748 // Do the comparison at i32 if it's smaller, besides the Atom case.
10749 // This avoids subregister aliasing issues. Keep the smaller reference
10750 // if we're optimizing for size, however, as that'll allow better folding
10751 // of memory operations.
10752 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
10753 !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
10754 AttributeSet::FunctionIndex, Attribute::MinSize) &&
10755 !Subtarget->isAtom()) {
10756 unsigned ExtendOp =
10757 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
10758 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
10759 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
10761 // Use SUB instead of CMP to enable CSE between SUB and CMP.
10762 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
10763 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
10765 return SDValue(Sub.getNode(), 1);
10767 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
10770 /// Convert a comparison if required by the subtarget.
10771 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
10772 SelectionDAG &DAG) const {
10773 // If the subtarget does not support the FUCOMI instruction, floating-point
10774 // comparisons have to be converted.
10775 if (Subtarget->hasCMov() ||
10776 Cmp.getOpcode() != X86ISD::CMP ||
10777 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
10778 !Cmp.getOperand(1).getValueType().isFloatingPoint())
10781 // The instruction selector will select an FUCOM instruction instead of
10782 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
10783 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
10784 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
10786 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
10787 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
10788 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
10789 DAG.getConstant(8, MVT::i8));
10790 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
10791 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
10794 static bool isAllOnes(SDValue V) {
10795 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10796 return C && C->isAllOnesValue();
10799 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
10800 /// if it's possible.
10801 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
10802 SDLoc dl, SelectionDAG &DAG) const {
10803 SDValue Op0 = And.getOperand(0);
10804 SDValue Op1 = And.getOperand(1);
10805 if (Op0.getOpcode() == ISD::TRUNCATE)
10806 Op0 = Op0.getOperand(0);
10807 if (Op1.getOpcode() == ISD::TRUNCATE)
10808 Op1 = Op1.getOperand(0);
10811 if (Op1.getOpcode() == ISD::SHL)
10812 std::swap(Op0, Op1);
10813 if (Op0.getOpcode() == ISD::SHL) {
10814 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
10815 if (And00C->getZExtValue() == 1) {
10816 // If we looked past a truncate, check that it's only truncating away
10818 unsigned BitWidth = Op0.getValueSizeInBits();
10819 unsigned AndBitWidth = And.getValueSizeInBits();
10820 if (BitWidth > AndBitWidth) {
10822 DAG.computeKnownBits(Op0, Zeros, Ones);
10823 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
10827 RHS = Op0.getOperand(1);
10829 } else if (Op1.getOpcode() == ISD::Constant) {
10830 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
10831 uint64_t AndRHSVal = AndRHS->getZExtValue();
10832 SDValue AndLHS = Op0;
10834 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
10835 LHS = AndLHS.getOperand(0);
10836 RHS = AndLHS.getOperand(1);
10839 // Use BT if the immediate can't be encoded in a TEST instruction.
10840 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
10842 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
10846 if (LHS.getNode()) {
10847 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
10848 // instruction. Since the shift amount is in-range-or-undefined, we know
10849 // that doing a bittest on the i32 value is ok. We extend to i32 because
10850 // the encoding for the i16 version is larger than the i32 version.
10851 // Also promote i16 to i32 for performance / code size reason.
10852 if (LHS.getValueType() == MVT::i8 ||
10853 LHS.getValueType() == MVT::i16)
10854 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
10856 // If the operand types disagree, extend the shift amount to match. Since
10857 // BT ignores high bits (like shifts) we can use anyextend.
10858 if (LHS.getValueType() != RHS.getValueType())
10859 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
10861 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
10862 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
10863 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10864 DAG.getConstant(Cond, MVT::i8), BT);
10870 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
10872 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
10877 // SSE Condition code mapping:
10886 switch (SetCCOpcode) {
10887 default: llvm_unreachable("Unexpected SETCC condition");
10889 case ISD::SETEQ: SSECC = 0; break;
10891 case ISD::SETGT: Swap = true; // Fallthrough
10893 case ISD::SETOLT: SSECC = 1; break;
10895 case ISD::SETGE: Swap = true; // Fallthrough
10897 case ISD::SETOLE: SSECC = 2; break;
10898 case ISD::SETUO: SSECC = 3; break;
10900 case ISD::SETNE: SSECC = 4; break;
10901 case ISD::SETULE: Swap = true; // Fallthrough
10902 case ISD::SETUGE: SSECC = 5; break;
10903 case ISD::SETULT: Swap = true; // Fallthrough
10904 case ISD::SETUGT: SSECC = 6; break;
10905 case ISD::SETO: SSECC = 7; break;
10907 case ISD::SETONE: SSECC = 8; break;
10910 std::swap(Op0, Op1);
10915 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
10916 // ones, and then concatenate the result back.
10917 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
10918 MVT VT = Op.getSimpleValueType();
10920 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
10921 "Unsupported value type for operation");
10923 unsigned NumElems = VT.getVectorNumElements();
10925 SDValue CC = Op.getOperand(2);
10927 // Extract the LHS vectors
10928 SDValue LHS = Op.getOperand(0);
10929 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10930 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10932 // Extract the RHS vectors
10933 SDValue RHS = Op.getOperand(1);
10934 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10935 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10937 // Issue the operation on the smaller types and concatenate the result back
10938 MVT EltVT = VT.getVectorElementType();
10939 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10940 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10941 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
10942 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
10945 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
10946 const X86Subtarget *Subtarget) {
10947 SDValue Op0 = Op.getOperand(0);
10948 SDValue Op1 = Op.getOperand(1);
10949 SDValue CC = Op.getOperand(2);
10950 MVT VT = Op.getSimpleValueType();
10953 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
10954 Op.getValueType().getScalarType() == MVT::i1 &&
10955 "Cannot set masked compare for this operation");
10957 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10959 bool Unsigned = false;
10962 switch (SetCCOpcode) {
10963 default: llvm_unreachable("Unexpected SETCC condition");
10964 case ISD::SETNE: SSECC = 4; break;
10965 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
10966 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
10967 case ISD::SETLT: Swap = true; //fall-through
10968 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
10969 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
10970 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
10971 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
10972 case ISD::SETULE: Unsigned = true; //fall-through
10973 case ISD::SETLE: SSECC = 2; break;
10977 std::swap(Op0, Op1);
10979 return DAG.getNode(Opc, dl, VT, Op0, Op1);
10980 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
10981 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10982 DAG.getConstant(SSECC, MVT::i8));
10985 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
10986 /// operand \p Op1. If non-trivial (for example because it's not constant)
10987 /// return an empty value.
10988 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
10990 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
10994 MVT VT = Op1.getSimpleValueType();
10995 MVT EVT = VT.getVectorElementType();
10996 unsigned n = VT.getVectorNumElements();
10997 SmallVector<SDValue, 8> ULTOp1;
10999 for (unsigned i = 0; i < n; ++i) {
11000 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
11001 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
11004 // Avoid underflow.
11005 APInt Val = Elt->getAPIntValue();
11009 ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
11012 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
11015 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
11016 SelectionDAG &DAG) {
11017 SDValue Op0 = Op.getOperand(0);
11018 SDValue Op1 = Op.getOperand(1);
11019 SDValue CC = Op.getOperand(2);
11020 MVT VT = Op.getSimpleValueType();
11021 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
11022 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
11027 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
11028 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
11031 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
11032 unsigned Opc = X86ISD::CMPP;
11033 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
11034 assert(VT.getVectorNumElements() <= 16);
11035 Opc = X86ISD::CMPM;
11037 // In the two special cases we can't handle, emit two comparisons.
11040 unsigned CombineOpc;
11041 if (SetCCOpcode == ISD::SETUEQ) {
11042 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
11044 assert(SetCCOpcode == ISD::SETONE);
11045 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
11048 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
11049 DAG.getConstant(CC0, MVT::i8));
11050 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
11051 DAG.getConstant(CC1, MVT::i8));
11052 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
11054 // Handle all other FP comparisons here.
11055 return DAG.getNode(Opc, dl, VT, Op0, Op1,
11056 DAG.getConstant(SSECC, MVT::i8));
11059 // Break 256-bit integer vector compare into smaller ones.
11060 if (VT.is256BitVector() && !Subtarget->hasInt256())
11061 return Lower256IntVSETCC(Op, DAG);
11063 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
11064 EVT OpVT = Op1.getValueType();
11065 if (Subtarget->hasAVX512()) {
11066 if (Op1.getValueType().is512BitVector() ||
11067 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
11068 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
11070 // In AVX-512 architecture setcc returns mask with i1 elements,
11071 // But there is no compare instruction for i8 and i16 elements.
11072 // We are not talking about 512-bit operands in this case, these
11073 // types are illegal.
11075 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
11076 OpVT.getVectorElementType().getSizeInBits() >= 8))
11077 return DAG.getNode(ISD::TRUNCATE, dl, VT,
11078 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
11081 // We are handling one of the integer comparisons here. Since SSE only has
11082 // GT and EQ comparisons for integer, swapping operands and multiple
11083 // operations may be required for some comparisons.
11085 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
11086 bool Subus = false;
11088 switch (SetCCOpcode) {
11089 default: llvm_unreachable("Unexpected SETCC condition");
11090 case ISD::SETNE: Invert = true;
11091 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
11092 case ISD::SETLT: Swap = true;
11093 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
11094 case ISD::SETGE: Swap = true;
11095 case ISD::SETLE: Opc = X86ISD::PCMPGT;
11096 Invert = true; break;
11097 case ISD::SETULT: Swap = true;
11098 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
11099 FlipSigns = true; break;
11100 case ISD::SETUGE: Swap = true;
11101 case ISD::SETULE: Opc = X86ISD::PCMPGT;
11102 FlipSigns = true; Invert = true; break;
11105 // Special case: Use min/max operations for SETULE/SETUGE
11106 MVT VET = VT.getVectorElementType();
11108 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
11109 || (Subtarget->hasSSE2() && (VET == MVT::i8));
11112 switch (SetCCOpcode) {
11114 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
11115 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
11118 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
11121 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
11122 if (!MinMax && hasSubus) {
11123 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
11125 // t = psubus Op0, Op1
11126 // pcmpeq t, <0..0>
11127 switch (SetCCOpcode) {
11129 case ISD::SETULT: {
11130 // If the comparison is against a constant we can turn this into a
11131 // setule. With psubus, setule does not require a swap. This is
11132 // beneficial because the constant in the register is no longer
11133 // destructed as the destination so it can be hoisted out of a loop.
11134 // Only do this pre-AVX since vpcmp* is no longer destructive.
11135 if (Subtarget->hasAVX())
11137 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
11138 if (ULEOp1.getNode()) {
11140 Subus = true; Invert = false; Swap = false;
11144 // Psubus is better than flip-sign because it requires no inversion.
11145 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
11146 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
11150 Opc = X86ISD::SUBUS;
11156 std::swap(Op0, Op1);
11158 // Check that the operation in question is available (most are plain SSE2,
11159 // but PCMPGTQ and PCMPEQQ have different requirements).
11160 if (VT == MVT::v2i64) {
11161 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
11162 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
11164 // First cast everything to the right type.
11165 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
11166 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
11168 // Since SSE has no unsigned integer comparisons, we need to flip the sign
11169 // bits of the inputs before performing those operations. The lower
11170 // compare is always unsigned.
11173 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
11175 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
11176 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
11177 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
11178 Sign, Zero, Sign, Zero);
11180 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
11181 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
11183 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
11184 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
11185 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
11187 // Create masks for only the low parts/high parts of the 64 bit integers.
11188 static const int MaskHi[] = { 1, 1, 3, 3 };
11189 static const int MaskLo[] = { 0, 0, 2, 2 };
11190 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
11191 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
11192 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
11194 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
11195 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
11198 Result = DAG.getNOT(dl, Result, MVT::v4i32);
11200 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
11203 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
11204 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
11205 // pcmpeqd + pshufd + pand.
11206 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
11208 // First cast everything to the right type.
11209 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
11210 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
11213 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
11215 // Make sure the lower and upper halves are both all-ones.
11216 static const int Mask[] = { 1, 0, 3, 2 };
11217 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
11218 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
11221 Result = DAG.getNOT(dl, Result, MVT::v4i32);
11223 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
11227 // Since SSE has no unsigned integer comparisons, we need to flip the sign
11228 // bits of the inputs before performing those operations.
11230 EVT EltVT = VT.getVectorElementType();
11231 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
11232 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
11233 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
11236 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
11238 // If the logical-not of the result is required, perform that now.
11240 Result = DAG.getNOT(dl, Result, VT);
11243 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
11246 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
11247 getZeroVector(VT, Subtarget, DAG, dl));
11252 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
11254 MVT VT = Op.getSimpleValueType();
11256 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
11258 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
11259 && "SetCC type must be 8-bit or 1-bit integer");
11260 SDValue Op0 = Op.getOperand(0);
11261 SDValue Op1 = Op.getOperand(1);
11263 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
11265 // Optimize to BT if possible.
11266 // Lower (X & (1 << N)) == 0 to BT(X, N).
11267 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
11268 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
11269 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
11270 Op1.getOpcode() == ISD::Constant &&
11271 cast<ConstantSDNode>(Op1)->isNullValue() &&
11272 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
11273 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
11274 if (NewSetCC.getNode())
11278 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
11280 if (Op1.getOpcode() == ISD::Constant &&
11281 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
11282 cast<ConstantSDNode>(Op1)->isNullValue()) &&
11283 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
11285 // If the input is a setcc, then reuse the input setcc or use a new one with
11286 // the inverted condition.
11287 if (Op0.getOpcode() == X86ISD::SETCC) {
11288 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
11289 bool Invert = (CC == ISD::SETNE) ^
11290 cast<ConstantSDNode>(Op1)->isNullValue();
11294 CCode = X86::GetOppositeBranchCondition(CCode);
11295 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11296 DAG.getConstant(CCode, MVT::i8),
11297 Op0.getOperand(1));
11299 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
11303 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
11304 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
11305 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
11307 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
11308 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
11311 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
11312 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
11313 if (X86CC == X86::COND_INVALID)
11316 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
11317 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
11318 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11319 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
11321 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
11325 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
11326 static bool isX86LogicalCmp(SDValue Op) {
11327 unsigned Opc = Op.getNode()->getOpcode();
11328 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
11329 Opc == X86ISD::SAHF)
11331 if (Op.getResNo() == 1 &&
11332 (Opc == X86ISD::ADD ||
11333 Opc == X86ISD::SUB ||
11334 Opc == X86ISD::ADC ||
11335 Opc == X86ISD::SBB ||
11336 Opc == X86ISD::SMUL ||
11337 Opc == X86ISD::UMUL ||
11338 Opc == X86ISD::INC ||
11339 Opc == X86ISD::DEC ||
11340 Opc == X86ISD::OR ||
11341 Opc == X86ISD::XOR ||
11342 Opc == X86ISD::AND))
11345 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
11351 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
11352 if (V.getOpcode() != ISD::TRUNCATE)
11355 SDValue VOp0 = V.getOperand(0);
11356 unsigned InBits = VOp0.getValueSizeInBits();
11357 unsigned Bits = V.getValueSizeInBits();
11358 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
11361 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
11362 bool addTest = true;
11363 SDValue Cond = Op.getOperand(0);
11364 SDValue Op1 = Op.getOperand(1);
11365 SDValue Op2 = Op.getOperand(2);
11367 EVT VT = Op1.getValueType();
11370 // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
11371 // are available. Otherwise fp cmovs get lowered into a less efficient branch
11372 // sequence later on.
11373 if (Cond.getOpcode() == ISD::SETCC &&
11374 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
11375 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
11376 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
11377 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
11378 int SSECC = translateX86FSETCC(
11379 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
11382 if (Subtarget->hasAVX512()) {
11383 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
11384 DAG.getConstant(SSECC, MVT::i8));
11385 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
11387 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
11388 DAG.getConstant(SSECC, MVT::i8));
11389 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
11390 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
11391 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
11395 if (Cond.getOpcode() == ISD::SETCC) {
11396 SDValue NewCond = LowerSETCC(Cond, DAG);
11397 if (NewCond.getNode())
11401 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
11402 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
11403 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
11404 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
11405 if (Cond.getOpcode() == X86ISD::SETCC &&
11406 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
11407 isZero(Cond.getOperand(1).getOperand(1))) {
11408 SDValue Cmp = Cond.getOperand(1);
11410 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
11412 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
11413 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
11414 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
11416 SDValue CmpOp0 = Cmp.getOperand(0);
11417 // Apply further optimizations for special cases
11418 // (select (x != 0), -1, 0) -> neg & sbb
11419 // (select (x == 0), 0, -1) -> neg & sbb
11420 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
11421 if (YC->isNullValue() &&
11422 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
11423 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
11424 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
11425 DAG.getConstant(0, CmpOp0.getValueType()),
11427 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
11428 DAG.getConstant(X86::COND_B, MVT::i8),
11429 SDValue(Neg.getNode(), 1));
11433 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
11434 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
11435 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11437 SDValue Res = // Res = 0 or -1.
11438 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
11439 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
11441 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
11442 Res = DAG.getNOT(DL, Res, Res.getValueType());
11444 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
11445 if (!N2C || !N2C->isNullValue())
11446 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
11451 // Look past (and (setcc_carry (cmp ...)), 1).
11452 if (Cond.getOpcode() == ISD::AND &&
11453 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
11454 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11455 if (C && C->getAPIntValue() == 1)
11456 Cond = Cond.getOperand(0);
11459 // If condition flag is set by a X86ISD::CMP, then use it as the condition
11460 // setting operand in place of the X86ISD::SETCC.
11461 unsigned CondOpcode = Cond.getOpcode();
11462 if (CondOpcode == X86ISD::SETCC ||
11463 CondOpcode == X86ISD::SETCC_CARRY) {
11464 CC = Cond.getOperand(0);
11466 SDValue Cmp = Cond.getOperand(1);
11467 unsigned Opc = Cmp.getOpcode();
11468 MVT VT = Op.getSimpleValueType();
11470 bool IllegalFPCMov = false;
11471 if (VT.isFloatingPoint() && !VT.isVector() &&
11472 !isScalarFPTypeInSSEReg(VT)) // FPStack?
11473 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
11475 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
11476 Opc == X86ISD::BT) { // FIXME
11480 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11481 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11482 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11483 Cond.getOperand(0).getValueType() != MVT::i8)) {
11484 SDValue LHS = Cond.getOperand(0);
11485 SDValue RHS = Cond.getOperand(1);
11486 unsigned X86Opcode;
11489 switch (CondOpcode) {
11490 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11491 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11492 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11493 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11494 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11495 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11496 default: llvm_unreachable("unexpected overflowing operator");
11498 if (CondOpcode == ISD::UMULO)
11499 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11502 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11504 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
11506 if (CondOpcode == ISD::UMULO)
11507 Cond = X86Op.getValue(2);
11509 Cond = X86Op.getValue(1);
11511 CC = DAG.getConstant(X86Cond, MVT::i8);
11516 // Look pass the truncate if the high bits are known zero.
11517 if (isTruncWithZeroHighBitsInput(Cond, DAG))
11518 Cond = Cond.getOperand(0);
11520 // We know the result of AND is compared against zero. Try to match
11522 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11523 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
11524 if (NewSetCC.getNode()) {
11525 CC = NewSetCC.getOperand(0);
11526 Cond = NewSetCC.getOperand(1);
11533 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11534 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
11537 // a < b ? -1 : 0 -> RES = ~setcc_carry
11538 // a < b ? 0 : -1 -> RES = setcc_carry
11539 // a >= b ? -1 : 0 -> RES = setcc_carry
11540 // a >= b ? 0 : -1 -> RES = ~setcc_carry
11541 if (Cond.getOpcode() == X86ISD::SUB) {
11542 Cond = ConvertCmpIfNecessary(Cond, DAG);
11543 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
11545 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
11546 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
11547 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
11548 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
11549 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
11550 return DAG.getNOT(DL, Res, Res.getValueType());
11555 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
11556 // widen the cmov and push the truncate through. This avoids introducing a new
11557 // branch during isel and doesn't add any extensions.
11558 if (Op.getValueType() == MVT::i8 &&
11559 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
11560 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
11561 if (T1.getValueType() == T2.getValueType() &&
11562 // Blacklist CopyFromReg to avoid partial register stalls.
11563 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
11564 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
11565 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
11566 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
11570 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
11571 // condition is true.
11572 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
11573 SDValue Ops[] = { Op2, Op1, CC, Cond };
11574 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
11577 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
11578 MVT VT = Op->getSimpleValueType(0);
11579 SDValue In = Op->getOperand(0);
11580 MVT InVT = In.getSimpleValueType();
11583 unsigned int NumElts = VT.getVectorNumElements();
11584 if (NumElts != 8 && NumElts != 16)
11587 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11588 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
11590 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11591 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11593 MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
11594 Constant *C = ConstantInt::get(*DAG.getContext(),
11595 APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
11597 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11598 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11599 SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
11600 MachinePointerInfo::getConstantPool(),
11601 false, false, false, Alignment);
11602 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
11603 if (VT.is512BitVector())
11605 return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
11608 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11609 SelectionDAG &DAG) {
11610 MVT VT = Op->getSimpleValueType(0);
11611 SDValue In = Op->getOperand(0);
11612 MVT InVT = In.getSimpleValueType();
11615 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
11616 return LowerSIGN_EXTEND_AVX512(Op, DAG);
11618 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
11619 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
11620 (VT != MVT::v16i16 || InVT != MVT::v16i8))
11623 if (Subtarget->hasInt256())
11624 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
11626 // Optimize vectors in AVX mode
11627 // Sign extend v8i16 to v8i32 and
11630 // Divide input vector into two parts
11631 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
11632 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
11633 // concat the vectors to original VT
11635 unsigned NumElems = InVT.getVectorNumElements();
11636 SDValue Undef = DAG.getUNDEF(InVT);
11638 SmallVector<int,8> ShufMask1(NumElems, -1);
11639 for (unsigned i = 0; i != NumElems/2; ++i)
11642 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
11644 SmallVector<int,8> ShufMask2(NumElems, -1);
11645 for (unsigned i = 0; i != NumElems/2; ++i)
11646 ShufMask2[i] = i + NumElems/2;
11648 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
11650 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
11651 VT.getVectorNumElements()/2);
11653 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
11654 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
11656 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11659 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
11660 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
11661 // from the AND / OR.
11662 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
11663 Opc = Op.getOpcode();
11664 if (Opc != ISD::OR && Opc != ISD::AND)
11666 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
11667 Op.getOperand(0).hasOneUse() &&
11668 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
11669 Op.getOperand(1).hasOneUse());
11672 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
11673 // 1 and that the SETCC node has a single use.
11674 static bool isXor1OfSetCC(SDValue Op) {
11675 if (Op.getOpcode() != ISD::XOR)
11677 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
11678 if (N1C && N1C->getAPIntValue() == 1) {
11679 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
11680 Op.getOperand(0).hasOneUse();
11685 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
11686 bool addTest = true;
11687 SDValue Chain = Op.getOperand(0);
11688 SDValue Cond = Op.getOperand(1);
11689 SDValue Dest = Op.getOperand(2);
11692 bool Inverted = false;
11694 if (Cond.getOpcode() == ISD::SETCC) {
11695 // Check for setcc([su]{add,sub,mul}o == 0).
11696 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
11697 isa<ConstantSDNode>(Cond.getOperand(1)) &&
11698 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
11699 Cond.getOperand(0).getResNo() == 1 &&
11700 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
11701 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
11702 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
11703 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
11704 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
11705 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
11707 Cond = Cond.getOperand(0);
11709 SDValue NewCond = LowerSETCC(Cond, DAG);
11710 if (NewCond.getNode())
11715 // FIXME: LowerXALUO doesn't handle these!!
11716 else if (Cond.getOpcode() == X86ISD::ADD ||
11717 Cond.getOpcode() == X86ISD::SUB ||
11718 Cond.getOpcode() == X86ISD::SMUL ||
11719 Cond.getOpcode() == X86ISD::UMUL)
11720 Cond = LowerXALUO(Cond, DAG);
11723 // Look pass (and (setcc_carry (cmp ...)), 1).
11724 if (Cond.getOpcode() == ISD::AND &&
11725 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
11726 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11727 if (C && C->getAPIntValue() == 1)
11728 Cond = Cond.getOperand(0);
11731 // If condition flag is set by a X86ISD::CMP, then use it as the condition
11732 // setting operand in place of the X86ISD::SETCC.
11733 unsigned CondOpcode = Cond.getOpcode();
11734 if (CondOpcode == X86ISD::SETCC ||
11735 CondOpcode == X86ISD::SETCC_CARRY) {
11736 CC = Cond.getOperand(0);
11738 SDValue Cmp = Cond.getOperand(1);
11739 unsigned Opc = Cmp.getOpcode();
11740 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
11741 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
11745 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
11749 // These can only come from an arithmetic instruction with overflow,
11750 // e.g. SADDO, UADDO.
11751 Cond = Cond.getNode()->getOperand(1);
11757 CondOpcode = Cond.getOpcode();
11758 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11759 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11760 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11761 Cond.getOperand(0).getValueType() != MVT::i8)) {
11762 SDValue LHS = Cond.getOperand(0);
11763 SDValue RHS = Cond.getOperand(1);
11764 unsigned X86Opcode;
11767 // Keep this in sync with LowerXALUO, otherwise we might create redundant
11768 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
11770 switch (CondOpcode) {
11771 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11773 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11775 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
11778 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11779 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11781 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11783 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
11786 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11787 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11788 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11789 default: llvm_unreachable("unexpected overflowing operator");
11792 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
11793 if (CondOpcode == ISD::UMULO)
11794 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11797 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11799 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
11801 if (CondOpcode == ISD::UMULO)
11802 Cond = X86Op.getValue(2);
11804 Cond = X86Op.getValue(1);
11806 CC = DAG.getConstant(X86Cond, MVT::i8);
11810 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
11811 SDValue Cmp = Cond.getOperand(0).getOperand(1);
11812 if (CondOpc == ISD::OR) {
11813 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
11814 // two branches instead of an explicit OR instruction with a
11816 if (Cmp == Cond.getOperand(1).getOperand(1) &&
11817 isX86LogicalCmp(Cmp)) {
11818 CC = Cond.getOperand(0).getOperand(0);
11819 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11820 Chain, Dest, CC, Cmp);
11821 CC = Cond.getOperand(1).getOperand(0);
11825 } else { // ISD::AND
11826 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
11827 // two branches instead of an explicit AND instruction with a
11828 // separate test. However, we only do this if this block doesn't
11829 // have a fall-through edge, because this requires an explicit
11830 // jmp when the condition is false.
11831 if (Cmp == Cond.getOperand(1).getOperand(1) &&
11832 isX86LogicalCmp(Cmp) &&
11833 Op.getNode()->hasOneUse()) {
11834 X86::CondCode CCode =
11835 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11836 CCode = X86::GetOppositeBranchCondition(CCode);
11837 CC = DAG.getConstant(CCode, MVT::i8);
11838 SDNode *User = *Op.getNode()->use_begin();
11839 // Look for an unconditional branch following this conditional branch.
11840 // We need this because we need to reverse the successors in order
11841 // to implement FCMP_OEQ.
11842 if (User->getOpcode() == ISD::BR) {
11843 SDValue FalseBB = User->getOperand(1);
11845 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11846 assert(NewBR == User);
11850 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11851 Chain, Dest, CC, Cmp);
11852 X86::CondCode CCode =
11853 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
11854 CCode = X86::GetOppositeBranchCondition(CCode);
11855 CC = DAG.getConstant(CCode, MVT::i8);
11861 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
11862 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
11863 // It should be transformed during dag combiner except when the condition
11864 // is set by a arithmetics with overflow node.
11865 X86::CondCode CCode =
11866 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11867 CCode = X86::GetOppositeBranchCondition(CCode);
11868 CC = DAG.getConstant(CCode, MVT::i8);
11869 Cond = Cond.getOperand(0).getOperand(1);
11871 } else if (Cond.getOpcode() == ISD::SETCC &&
11872 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
11873 // For FCMP_OEQ, we can emit
11874 // two branches instead of an explicit AND instruction with a
11875 // separate test. However, we only do this if this block doesn't
11876 // have a fall-through edge, because this requires an explicit
11877 // jmp when the condition is false.
11878 if (Op.getNode()->hasOneUse()) {
11879 SDNode *User = *Op.getNode()->use_begin();
11880 // Look for an unconditional branch following this conditional branch.
11881 // We need this because we need to reverse the successors in order
11882 // to implement FCMP_OEQ.
11883 if (User->getOpcode() == ISD::BR) {
11884 SDValue FalseBB = User->getOperand(1);
11886 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11887 assert(NewBR == User);
11891 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11892 Cond.getOperand(0), Cond.getOperand(1));
11893 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11894 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11895 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11896 Chain, Dest, CC, Cmp);
11897 CC = DAG.getConstant(X86::COND_P, MVT::i8);
11902 } else if (Cond.getOpcode() == ISD::SETCC &&
11903 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
11904 // For FCMP_UNE, we can emit
11905 // two branches instead of an explicit AND instruction with a
11906 // separate test. However, we only do this if this block doesn't
11907 // have a fall-through edge, because this requires an explicit
11908 // jmp when the condition is false.
11909 if (Op.getNode()->hasOneUse()) {
11910 SDNode *User = *Op.getNode()->use_begin();
11911 // Look for an unconditional branch following this conditional branch.
11912 // We need this because we need to reverse the successors in order
11913 // to implement FCMP_UNE.
11914 if (User->getOpcode() == ISD::BR) {
11915 SDValue FalseBB = User->getOperand(1);
11917 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11918 assert(NewBR == User);
11921 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11922 Cond.getOperand(0), Cond.getOperand(1));
11923 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11924 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11925 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11926 Chain, Dest, CC, Cmp);
11927 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
11937 // Look pass the truncate if the high bits are known zero.
11938 if (isTruncWithZeroHighBitsInput(Cond, DAG))
11939 Cond = Cond.getOperand(0);
11941 // We know the result of AND is compared against zero. Try to match
11943 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11944 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
11945 if (NewSetCC.getNode()) {
11946 CC = NewSetCC.getOperand(0);
11947 Cond = NewSetCC.getOperand(1);
11954 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
11955 CC = DAG.getConstant(X86Cond, MVT::i8);
11956 Cond = EmitTest(Cond, X86Cond, dl, DAG);
11958 Cond = ConvertCmpIfNecessary(Cond, DAG);
11959 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11960 Chain, Dest, CC, Cond);
11963 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
11964 // Calls to _alloca is needed to probe the stack when allocating more than 4k
11965 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
11966 // that the guard pages used by the OS virtual memory manager are allocated in
11967 // correct sequence.
11969 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
11970 SelectionDAG &DAG) const {
11971 MachineFunction &MF = DAG.getMachineFunction();
11972 bool SplitStack = MF.shouldSplitStack();
11973 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
11978 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11979 SDNode* Node = Op.getNode();
11981 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
11982 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
11983 " not tell us which reg is the stack pointer!");
11984 EVT VT = Node->getValueType(0);
11985 SDValue Tmp1 = SDValue(Node, 0);
11986 SDValue Tmp2 = SDValue(Node, 1);
11987 SDValue Tmp3 = Node->getOperand(2);
11988 SDValue Chain = Tmp1.getOperand(0);
11990 // Chain the dynamic stack allocation so that it doesn't modify the stack
11991 // pointer when other instructions are using the stack.
11992 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
11995 SDValue Size = Tmp2.getOperand(1);
11996 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
11997 Chain = SP.getValue(1);
11998 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
11999 const TargetFrameLowering &TFI = *DAG.getTarget().getFrameLowering();
12000 unsigned StackAlign = TFI.getStackAlignment();
12001 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
12002 if (Align > StackAlign)
12003 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
12004 DAG.getConstant(-(uint64_t)Align, VT));
12005 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
12007 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
12008 DAG.getIntPtrConstant(0, true), SDValue(),
12011 SDValue Ops[2] = { Tmp1, Tmp2 };
12012 return DAG.getMergeValues(Ops, dl);
12016 SDValue Chain = Op.getOperand(0);
12017 SDValue Size = Op.getOperand(1);
12018 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
12019 EVT VT = Op.getNode()->getValueType(0);
12021 bool Is64Bit = Subtarget->is64Bit();
12022 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
12025 MachineRegisterInfo &MRI = MF.getRegInfo();
12028 // The 64 bit implementation of segmented stacks needs to clobber both r10
12029 // r11. This makes it impossible to use it along with nested parameters.
12030 const Function *F = MF.getFunction();
12032 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
12034 if (I->hasNestAttr())
12035 report_fatal_error("Cannot use segmented stacks with functions that "
12036 "have nested arguments.");
12039 const TargetRegisterClass *AddrRegClass =
12040 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
12041 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
12042 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
12043 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
12044 DAG.getRegister(Vreg, SPTy));
12045 SDValue Ops1[2] = { Value, Chain };
12046 return DAG.getMergeValues(Ops1, dl);
12049 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
12051 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
12052 Flag = Chain.getValue(1);
12053 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12055 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
12057 const X86RegisterInfo *RegInfo =
12058 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
12059 unsigned SPReg = RegInfo->getStackRegister();
12060 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
12061 Chain = SP.getValue(1);
12064 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
12065 DAG.getConstant(-(uint64_t)Align, VT));
12066 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
12069 SDValue Ops1[2] = { SP, Chain };
12070 return DAG.getMergeValues(Ops1, dl);
12074 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
12075 MachineFunction &MF = DAG.getMachineFunction();
12076 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
12078 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
12081 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
12082 // vastart just stores the address of the VarArgsFrameIndex slot into the
12083 // memory location argument.
12084 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
12086 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
12087 MachinePointerInfo(SV), false, false, 0);
12091 // gp_offset (0 - 6 * 8)
12092 // fp_offset (48 - 48 + 8 * 16)
12093 // overflow_arg_area (point to parameters coming in memory).
12095 SmallVector<SDValue, 8> MemOps;
12096 SDValue FIN = Op.getOperand(1);
12098 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
12099 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
12101 FIN, MachinePointerInfo(SV), false, false, 0);
12102 MemOps.push_back(Store);
12105 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
12106 FIN, DAG.getIntPtrConstant(4));
12107 Store = DAG.getStore(Op.getOperand(0), DL,
12108 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
12110 FIN, MachinePointerInfo(SV, 4), false, false, 0);
12111 MemOps.push_back(Store);
12113 // Store ptr to overflow_arg_area
12114 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
12115 FIN, DAG.getIntPtrConstant(4));
12116 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
12118 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
12119 MachinePointerInfo(SV, 8),
12121 MemOps.push_back(Store);
12123 // Store ptr to reg_save_area.
12124 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
12125 FIN, DAG.getIntPtrConstant(8));
12126 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
12128 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
12129 MachinePointerInfo(SV, 16), false, false, 0);
12130 MemOps.push_back(Store);
12131 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
12134 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
12135 assert(Subtarget->is64Bit() &&
12136 "LowerVAARG only handles 64-bit va_arg!");
12137 assert((Subtarget->isTargetLinux() ||
12138 Subtarget->isTargetDarwin()) &&
12139 "Unhandled target in LowerVAARG");
12140 assert(Op.getNode()->getNumOperands() == 4);
12141 SDValue Chain = Op.getOperand(0);
12142 SDValue SrcPtr = Op.getOperand(1);
12143 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
12144 unsigned Align = Op.getConstantOperandVal(3);
12147 EVT ArgVT = Op.getNode()->getValueType(0);
12148 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
12149 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
12152 // Decide which area this value should be read from.
12153 // TODO: Implement the AMD64 ABI in its entirety. This simple
12154 // selection mechanism works only for the basic types.
12155 if (ArgVT == MVT::f80) {
12156 llvm_unreachable("va_arg for f80 not yet implemented");
12157 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
12158 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
12159 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
12160 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
12162 llvm_unreachable("Unhandled argument type in LowerVAARG");
12165 if (ArgMode == 2) {
12166 // Sanity Check: Make sure using fp_offset makes sense.
12167 assert(!DAG.getTarget().Options.UseSoftFloat &&
12168 !(DAG.getMachineFunction()
12169 .getFunction()->getAttributes()
12170 .hasAttribute(AttributeSet::FunctionIndex,
12171 Attribute::NoImplicitFloat)) &&
12172 Subtarget->hasSSE1());
12175 // Insert VAARG_64 node into the DAG
12176 // VAARG_64 returns two values: Variable Argument Address, Chain
12177 SmallVector<SDValue, 11> InstOps;
12178 InstOps.push_back(Chain);
12179 InstOps.push_back(SrcPtr);
12180 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
12181 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
12182 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
12183 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
12184 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
12185 VTs, InstOps, MVT::i64,
12186 MachinePointerInfo(SV),
12188 /*Volatile=*/false,
12190 /*WriteMem=*/true);
12191 Chain = VAARG.getValue(1);
12193 // Load the next argument and return it
12194 return DAG.getLoad(ArgVT, dl,
12197 MachinePointerInfo(),
12198 false, false, false, 0);
12201 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
12202 SelectionDAG &DAG) {
12203 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
12204 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
12205 SDValue Chain = Op.getOperand(0);
12206 SDValue DstPtr = Op.getOperand(1);
12207 SDValue SrcPtr = Op.getOperand(2);
12208 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
12209 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
12212 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
12213 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
12215 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
12218 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
12219 // amount is a constant. Takes immediate version of shift as input.
12220 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
12221 SDValue SrcOp, uint64_t ShiftAmt,
12222 SelectionDAG &DAG) {
12223 MVT ElementType = VT.getVectorElementType();
12225 // Fold this packed shift into its first operand if ShiftAmt is 0.
12229 // Check for ShiftAmt >= element width
12230 if (ShiftAmt >= ElementType.getSizeInBits()) {
12231 if (Opc == X86ISD::VSRAI)
12232 ShiftAmt = ElementType.getSizeInBits() - 1;
12234 return DAG.getConstant(0, VT);
12237 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
12238 && "Unknown target vector shift-by-constant node");
12240 // Fold this packed vector shift into a build vector if SrcOp is a
12241 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
12242 if (VT == SrcOp.getSimpleValueType() &&
12243 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
12244 SmallVector<SDValue, 8> Elts;
12245 unsigned NumElts = SrcOp->getNumOperands();
12246 ConstantSDNode *ND;
12249 default: llvm_unreachable(nullptr);
12250 case X86ISD::VSHLI:
12251 for (unsigned i=0; i!=NumElts; ++i) {
12252 SDValue CurrentOp = SrcOp->getOperand(i);
12253 if (CurrentOp->getOpcode() == ISD::UNDEF) {
12254 Elts.push_back(CurrentOp);
12257 ND = cast<ConstantSDNode>(CurrentOp);
12258 const APInt &C = ND->getAPIntValue();
12259 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
12262 case X86ISD::VSRLI:
12263 for (unsigned i=0; i!=NumElts; ++i) {
12264 SDValue CurrentOp = SrcOp->getOperand(i);
12265 if (CurrentOp->getOpcode() == ISD::UNDEF) {
12266 Elts.push_back(CurrentOp);
12269 ND = cast<ConstantSDNode>(CurrentOp);
12270 const APInt &C = ND->getAPIntValue();
12271 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
12274 case X86ISD::VSRAI:
12275 for (unsigned i=0; i!=NumElts; ++i) {
12276 SDValue CurrentOp = SrcOp->getOperand(i);
12277 if (CurrentOp->getOpcode() == ISD::UNDEF) {
12278 Elts.push_back(CurrentOp);
12281 ND = cast<ConstantSDNode>(CurrentOp);
12282 const APInt &C = ND->getAPIntValue();
12283 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
12288 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
12291 return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
12294 // getTargetVShiftNode - Handle vector element shifts where the shift amount
12295 // may or may not be a constant. Takes immediate version of shift as input.
12296 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
12297 SDValue SrcOp, SDValue ShAmt,
12298 SelectionDAG &DAG) {
12299 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
12301 // Catch shift-by-constant.
12302 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
12303 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
12304 CShAmt->getZExtValue(), DAG);
12306 // Change opcode to non-immediate version
12308 default: llvm_unreachable("Unknown target vector shift node");
12309 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
12310 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
12311 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
12314 // Need to build a vector containing shift amount
12315 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
12318 ShOps[1] = DAG.getConstant(0, MVT::i32);
12319 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
12320 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
12322 // The return type has to be a 128-bit type with the same element
12323 // type as the input type.
12324 MVT EltVT = VT.getVectorElementType();
12325 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
12327 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
12328 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
12331 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
12333 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12335 default: return SDValue(); // Don't custom lower most intrinsics.
12336 // Comparison intrinsics.
12337 case Intrinsic::x86_sse_comieq_ss:
12338 case Intrinsic::x86_sse_comilt_ss:
12339 case Intrinsic::x86_sse_comile_ss:
12340 case Intrinsic::x86_sse_comigt_ss:
12341 case Intrinsic::x86_sse_comige_ss:
12342 case Intrinsic::x86_sse_comineq_ss:
12343 case Intrinsic::x86_sse_ucomieq_ss:
12344 case Intrinsic::x86_sse_ucomilt_ss:
12345 case Intrinsic::x86_sse_ucomile_ss:
12346 case Intrinsic::x86_sse_ucomigt_ss:
12347 case Intrinsic::x86_sse_ucomige_ss:
12348 case Intrinsic::x86_sse_ucomineq_ss:
12349 case Intrinsic::x86_sse2_comieq_sd:
12350 case Intrinsic::x86_sse2_comilt_sd:
12351 case Intrinsic::x86_sse2_comile_sd:
12352 case Intrinsic::x86_sse2_comigt_sd:
12353 case Intrinsic::x86_sse2_comige_sd:
12354 case Intrinsic::x86_sse2_comineq_sd:
12355 case Intrinsic::x86_sse2_ucomieq_sd:
12356 case Intrinsic::x86_sse2_ucomilt_sd:
12357 case Intrinsic::x86_sse2_ucomile_sd:
12358 case Intrinsic::x86_sse2_ucomigt_sd:
12359 case Intrinsic::x86_sse2_ucomige_sd:
12360 case Intrinsic::x86_sse2_ucomineq_sd: {
12364 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12365 case Intrinsic::x86_sse_comieq_ss:
12366 case Intrinsic::x86_sse2_comieq_sd:
12367 Opc = X86ISD::COMI;
12370 case Intrinsic::x86_sse_comilt_ss:
12371 case Intrinsic::x86_sse2_comilt_sd:
12372 Opc = X86ISD::COMI;
12375 case Intrinsic::x86_sse_comile_ss:
12376 case Intrinsic::x86_sse2_comile_sd:
12377 Opc = X86ISD::COMI;
12380 case Intrinsic::x86_sse_comigt_ss:
12381 case Intrinsic::x86_sse2_comigt_sd:
12382 Opc = X86ISD::COMI;
12385 case Intrinsic::x86_sse_comige_ss:
12386 case Intrinsic::x86_sse2_comige_sd:
12387 Opc = X86ISD::COMI;
12390 case Intrinsic::x86_sse_comineq_ss:
12391 case Intrinsic::x86_sse2_comineq_sd:
12392 Opc = X86ISD::COMI;
12395 case Intrinsic::x86_sse_ucomieq_ss:
12396 case Intrinsic::x86_sse2_ucomieq_sd:
12397 Opc = X86ISD::UCOMI;
12400 case Intrinsic::x86_sse_ucomilt_ss:
12401 case Intrinsic::x86_sse2_ucomilt_sd:
12402 Opc = X86ISD::UCOMI;
12405 case Intrinsic::x86_sse_ucomile_ss:
12406 case Intrinsic::x86_sse2_ucomile_sd:
12407 Opc = X86ISD::UCOMI;
12410 case Intrinsic::x86_sse_ucomigt_ss:
12411 case Intrinsic::x86_sse2_ucomigt_sd:
12412 Opc = X86ISD::UCOMI;
12415 case Intrinsic::x86_sse_ucomige_ss:
12416 case Intrinsic::x86_sse2_ucomige_sd:
12417 Opc = X86ISD::UCOMI;
12420 case Intrinsic::x86_sse_ucomineq_ss:
12421 case Intrinsic::x86_sse2_ucomineq_sd:
12422 Opc = X86ISD::UCOMI;
12427 SDValue LHS = Op.getOperand(1);
12428 SDValue RHS = Op.getOperand(2);
12429 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
12430 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
12431 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
12432 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12433 DAG.getConstant(X86CC, MVT::i8), Cond);
12434 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12437 // Arithmetic intrinsics.
12438 case Intrinsic::x86_sse2_pmulu_dq:
12439 case Intrinsic::x86_avx2_pmulu_dq:
12440 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
12441 Op.getOperand(1), Op.getOperand(2));
12443 case Intrinsic::x86_sse41_pmuldq:
12444 case Intrinsic::x86_avx2_pmul_dq:
12445 return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
12446 Op.getOperand(1), Op.getOperand(2));
12448 case Intrinsic::x86_sse2_pmulhu_w:
12449 case Intrinsic::x86_avx2_pmulhu_w:
12450 return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
12451 Op.getOperand(1), Op.getOperand(2));
12453 case Intrinsic::x86_sse2_pmulh_w:
12454 case Intrinsic::x86_avx2_pmulh_w:
12455 return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
12456 Op.getOperand(1), Op.getOperand(2));
12458 // SSE2/AVX2 sub with unsigned saturation intrinsics
12459 case Intrinsic::x86_sse2_psubus_b:
12460 case Intrinsic::x86_sse2_psubus_w:
12461 case Intrinsic::x86_avx2_psubus_b:
12462 case Intrinsic::x86_avx2_psubus_w:
12463 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
12464 Op.getOperand(1), Op.getOperand(2));
12466 // SSE3/AVX horizontal add/sub intrinsics
12467 case Intrinsic::x86_sse3_hadd_ps:
12468 case Intrinsic::x86_sse3_hadd_pd:
12469 case Intrinsic::x86_avx_hadd_ps_256:
12470 case Intrinsic::x86_avx_hadd_pd_256:
12471 case Intrinsic::x86_sse3_hsub_ps:
12472 case Intrinsic::x86_sse3_hsub_pd:
12473 case Intrinsic::x86_avx_hsub_ps_256:
12474 case Intrinsic::x86_avx_hsub_pd_256:
12475 case Intrinsic::x86_ssse3_phadd_w_128:
12476 case Intrinsic::x86_ssse3_phadd_d_128:
12477 case Intrinsic::x86_avx2_phadd_w:
12478 case Intrinsic::x86_avx2_phadd_d:
12479 case Intrinsic::x86_ssse3_phsub_w_128:
12480 case Intrinsic::x86_ssse3_phsub_d_128:
12481 case Intrinsic::x86_avx2_phsub_w:
12482 case Intrinsic::x86_avx2_phsub_d: {
12485 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12486 case Intrinsic::x86_sse3_hadd_ps:
12487 case Intrinsic::x86_sse3_hadd_pd:
12488 case Intrinsic::x86_avx_hadd_ps_256:
12489 case Intrinsic::x86_avx_hadd_pd_256:
12490 Opcode = X86ISD::FHADD;
12492 case Intrinsic::x86_sse3_hsub_ps:
12493 case Intrinsic::x86_sse3_hsub_pd:
12494 case Intrinsic::x86_avx_hsub_ps_256:
12495 case Intrinsic::x86_avx_hsub_pd_256:
12496 Opcode = X86ISD::FHSUB;
12498 case Intrinsic::x86_ssse3_phadd_w_128:
12499 case Intrinsic::x86_ssse3_phadd_d_128:
12500 case Intrinsic::x86_avx2_phadd_w:
12501 case Intrinsic::x86_avx2_phadd_d:
12502 Opcode = X86ISD::HADD;
12504 case Intrinsic::x86_ssse3_phsub_w_128:
12505 case Intrinsic::x86_ssse3_phsub_d_128:
12506 case Intrinsic::x86_avx2_phsub_w:
12507 case Intrinsic::x86_avx2_phsub_d:
12508 Opcode = X86ISD::HSUB;
12511 return DAG.getNode(Opcode, dl, Op.getValueType(),
12512 Op.getOperand(1), Op.getOperand(2));
12515 // SSE2/SSE41/AVX2 integer max/min intrinsics.
12516 case Intrinsic::x86_sse2_pmaxu_b:
12517 case Intrinsic::x86_sse41_pmaxuw:
12518 case Intrinsic::x86_sse41_pmaxud:
12519 case Intrinsic::x86_avx2_pmaxu_b:
12520 case Intrinsic::x86_avx2_pmaxu_w:
12521 case Intrinsic::x86_avx2_pmaxu_d:
12522 case Intrinsic::x86_sse2_pminu_b:
12523 case Intrinsic::x86_sse41_pminuw:
12524 case Intrinsic::x86_sse41_pminud:
12525 case Intrinsic::x86_avx2_pminu_b:
12526 case Intrinsic::x86_avx2_pminu_w:
12527 case Intrinsic::x86_avx2_pminu_d:
12528 case Intrinsic::x86_sse41_pmaxsb:
12529 case Intrinsic::x86_sse2_pmaxs_w:
12530 case Intrinsic::x86_sse41_pmaxsd:
12531 case Intrinsic::x86_avx2_pmaxs_b:
12532 case Intrinsic::x86_avx2_pmaxs_w:
12533 case Intrinsic::x86_avx2_pmaxs_d:
12534 case Intrinsic::x86_sse41_pminsb:
12535 case Intrinsic::x86_sse2_pmins_w:
12536 case Intrinsic::x86_sse41_pminsd:
12537 case Intrinsic::x86_avx2_pmins_b:
12538 case Intrinsic::x86_avx2_pmins_w:
12539 case Intrinsic::x86_avx2_pmins_d: {
12542 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12543 case Intrinsic::x86_sse2_pmaxu_b:
12544 case Intrinsic::x86_sse41_pmaxuw:
12545 case Intrinsic::x86_sse41_pmaxud:
12546 case Intrinsic::x86_avx2_pmaxu_b:
12547 case Intrinsic::x86_avx2_pmaxu_w:
12548 case Intrinsic::x86_avx2_pmaxu_d:
12549 Opcode = X86ISD::UMAX;
12551 case Intrinsic::x86_sse2_pminu_b:
12552 case Intrinsic::x86_sse41_pminuw:
12553 case Intrinsic::x86_sse41_pminud:
12554 case Intrinsic::x86_avx2_pminu_b:
12555 case Intrinsic::x86_avx2_pminu_w:
12556 case Intrinsic::x86_avx2_pminu_d:
12557 Opcode = X86ISD::UMIN;
12559 case Intrinsic::x86_sse41_pmaxsb:
12560 case Intrinsic::x86_sse2_pmaxs_w:
12561 case Intrinsic::x86_sse41_pmaxsd:
12562 case Intrinsic::x86_avx2_pmaxs_b:
12563 case Intrinsic::x86_avx2_pmaxs_w:
12564 case Intrinsic::x86_avx2_pmaxs_d:
12565 Opcode = X86ISD::SMAX;
12567 case Intrinsic::x86_sse41_pminsb:
12568 case Intrinsic::x86_sse2_pmins_w:
12569 case Intrinsic::x86_sse41_pminsd:
12570 case Intrinsic::x86_avx2_pmins_b:
12571 case Intrinsic::x86_avx2_pmins_w:
12572 case Intrinsic::x86_avx2_pmins_d:
12573 Opcode = X86ISD::SMIN;
12576 return DAG.getNode(Opcode, dl, Op.getValueType(),
12577 Op.getOperand(1), Op.getOperand(2));
12580 // SSE/SSE2/AVX floating point max/min intrinsics.
12581 case Intrinsic::x86_sse_max_ps:
12582 case Intrinsic::x86_sse2_max_pd:
12583 case Intrinsic::x86_avx_max_ps_256:
12584 case Intrinsic::x86_avx_max_pd_256:
12585 case Intrinsic::x86_sse_min_ps:
12586 case Intrinsic::x86_sse2_min_pd:
12587 case Intrinsic::x86_avx_min_ps_256:
12588 case Intrinsic::x86_avx_min_pd_256: {
12591 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12592 case Intrinsic::x86_sse_max_ps:
12593 case Intrinsic::x86_sse2_max_pd:
12594 case Intrinsic::x86_avx_max_ps_256:
12595 case Intrinsic::x86_avx_max_pd_256:
12596 Opcode = X86ISD::FMAX;
12598 case Intrinsic::x86_sse_min_ps:
12599 case Intrinsic::x86_sse2_min_pd:
12600 case Intrinsic::x86_avx_min_ps_256:
12601 case Intrinsic::x86_avx_min_pd_256:
12602 Opcode = X86ISD::FMIN;
12605 return DAG.getNode(Opcode, dl, Op.getValueType(),
12606 Op.getOperand(1), Op.getOperand(2));
12609 // AVX2 variable shift intrinsics
12610 case Intrinsic::x86_avx2_psllv_d:
12611 case Intrinsic::x86_avx2_psllv_q:
12612 case Intrinsic::x86_avx2_psllv_d_256:
12613 case Intrinsic::x86_avx2_psllv_q_256:
12614 case Intrinsic::x86_avx2_psrlv_d:
12615 case Intrinsic::x86_avx2_psrlv_q:
12616 case Intrinsic::x86_avx2_psrlv_d_256:
12617 case Intrinsic::x86_avx2_psrlv_q_256:
12618 case Intrinsic::x86_avx2_psrav_d:
12619 case Intrinsic::x86_avx2_psrav_d_256: {
12622 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12623 case Intrinsic::x86_avx2_psllv_d:
12624 case Intrinsic::x86_avx2_psllv_q:
12625 case Intrinsic::x86_avx2_psllv_d_256:
12626 case Intrinsic::x86_avx2_psllv_q_256:
12629 case Intrinsic::x86_avx2_psrlv_d:
12630 case Intrinsic::x86_avx2_psrlv_q:
12631 case Intrinsic::x86_avx2_psrlv_d_256:
12632 case Intrinsic::x86_avx2_psrlv_q_256:
12635 case Intrinsic::x86_avx2_psrav_d:
12636 case Intrinsic::x86_avx2_psrav_d_256:
12640 return DAG.getNode(Opcode, dl, Op.getValueType(),
12641 Op.getOperand(1), Op.getOperand(2));
12644 case Intrinsic::x86_sse2_packssdw_128:
12645 case Intrinsic::x86_sse2_packsswb_128:
12646 case Intrinsic::x86_avx2_packssdw:
12647 case Intrinsic::x86_avx2_packsswb:
12648 return DAG.getNode(X86ISD::PACKSS, dl, Op.getValueType(),
12649 Op.getOperand(1), Op.getOperand(2));
12651 case Intrinsic::x86_sse2_packuswb_128:
12652 case Intrinsic::x86_sse41_packusdw:
12653 case Intrinsic::x86_avx2_packuswb:
12654 case Intrinsic::x86_avx2_packusdw:
12655 return DAG.getNode(X86ISD::PACKUS, dl, Op.getValueType(),
12656 Op.getOperand(1), Op.getOperand(2));
12658 case Intrinsic::x86_ssse3_pshuf_b_128:
12659 case Intrinsic::x86_avx2_pshuf_b:
12660 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
12661 Op.getOperand(1), Op.getOperand(2));
12663 case Intrinsic::x86_ssse3_psign_b_128:
12664 case Intrinsic::x86_ssse3_psign_w_128:
12665 case Intrinsic::x86_ssse3_psign_d_128:
12666 case Intrinsic::x86_avx2_psign_b:
12667 case Intrinsic::x86_avx2_psign_w:
12668 case Intrinsic::x86_avx2_psign_d:
12669 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
12670 Op.getOperand(1), Op.getOperand(2));
12672 case Intrinsic::x86_sse41_insertps:
12673 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
12674 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
12676 case Intrinsic::x86_avx_vperm2f128_ps_256:
12677 case Intrinsic::x86_avx_vperm2f128_pd_256:
12678 case Intrinsic::x86_avx_vperm2f128_si_256:
12679 case Intrinsic::x86_avx2_vperm2i128:
12680 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
12681 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
12683 case Intrinsic::x86_avx2_permd:
12684 case Intrinsic::x86_avx2_permps:
12685 // Operands intentionally swapped. Mask is last operand to intrinsic,
12686 // but second operand for node/instruction.
12687 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
12688 Op.getOperand(2), Op.getOperand(1));
12690 case Intrinsic::x86_sse_sqrt_ps:
12691 case Intrinsic::x86_sse2_sqrt_pd:
12692 case Intrinsic::x86_avx_sqrt_ps_256:
12693 case Intrinsic::x86_avx_sqrt_pd_256:
12694 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
12696 // ptest and testp intrinsics. The intrinsic these come from are designed to
12697 // return an integer value, not just an instruction so lower it to the ptest
12698 // or testp pattern and a setcc for the result.
12699 case Intrinsic::x86_sse41_ptestz:
12700 case Intrinsic::x86_sse41_ptestc:
12701 case Intrinsic::x86_sse41_ptestnzc:
12702 case Intrinsic::x86_avx_ptestz_256:
12703 case Intrinsic::x86_avx_ptestc_256:
12704 case Intrinsic::x86_avx_ptestnzc_256:
12705 case Intrinsic::x86_avx_vtestz_ps:
12706 case Intrinsic::x86_avx_vtestc_ps:
12707 case Intrinsic::x86_avx_vtestnzc_ps:
12708 case Intrinsic::x86_avx_vtestz_pd:
12709 case Intrinsic::x86_avx_vtestc_pd:
12710 case Intrinsic::x86_avx_vtestnzc_pd:
12711 case Intrinsic::x86_avx_vtestz_ps_256:
12712 case Intrinsic::x86_avx_vtestc_ps_256:
12713 case Intrinsic::x86_avx_vtestnzc_ps_256:
12714 case Intrinsic::x86_avx_vtestz_pd_256:
12715 case Intrinsic::x86_avx_vtestc_pd_256:
12716 case Intrinsic::x86_avx_vtestnzc_pd_256: {
12717 bool IsTestPacked = false;
12720 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
12721 case Intrinsic::x86_avx_vtestz_ps:
12722 case Intrinsic::x86_avx_vtestz_pd:
12723 case Intrinsic::x86_avx_vtestz_ps_256:
12724 case Intrinsic::x86_avx_vtestz_pd_256:
12725 IsTestPacked = true; // Fallthrough
12726 case Intrinsic::x86_sse41_ptestz:
12727 case Intrinsic::x86_avx_ptestz_256:
12729 X86CC = X86::COND_E;
12731 case Intrinsic::x86_avx_vtestc_ps:
12732 case Intrinsic::x86_avx_vtestc_pd:
12733 case Intrinsic::x86_avx_vtestc_ps_256:
12734 case Intrinsic::x86_avx_vtestc_pd_256:
12735 IsTestPacked = true; // Fallthrough
12736 case Intrinsic::x86_sse41_ptestc:
12737 case Intrinsic::x86_avx_ptestc_256:
12739 X86CC = X86::COND_B;
12741 case Intrinsic::x86_avx_vtestnzc_ps:
12742 case Intrinsic::x86_avx_vtestnzc_pd:
12743 case Intrinsic::x86_avx_vtestnzc_ps_256:
12744 case Intrinsic::x86_avx_vtestnzc_pd_256:
12745 IsTestPacked = true; // Fallthrough
12746 case Intrinsic::x86_sse41_ptestnzc:
12747 case Intrinsic::x86_avx_ptestnzc_256:
12749 X86CC = X86::COND_A;
12753 SDValue LHS = Op.getOperand(1);
12754 SDValue RHS = Op.getOperand(2);
12755 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
12756 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
12757 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12758 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
12759 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12761 case Intrinsic::x86_avx512_kortestz_w:
12762 case Intrinsic::x86_avx512_kortestc_w: {
12763 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
12764 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
12765 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
12766 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12767 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
12768 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
12769 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12772 // SSE/AVX shift intrinsics
12773 case Intrinsic::x86_sse2_psll_w:
12774 case Intrinsic::x86_sse2_psll_d:
12775 case Intrinsic::x86_sse2_psll_q:
12776 case Intrinsic::x86_avx2_psll_w:
12777 case Intrinsic::x86_avx2_psll_d:
12778 case Intrinsic::x86_avx2_psll_q:
12779 case Intrinsic::x86_sse2_psrl_w:
12780 case Intrinsic::x86_sse2_psrl_d:
12781 case Intrinsic::x86_sse2_psrl_q:
12782 case Intrinsic::x86_avx2_psrl_w:
12783 case Intrinsic::x86_avx2_psrl_d:
12784 case Intrinsic::x86_avx2_psrl_q:
12785 case Intrinsic::x86_sse2_psra_w:
12786 case Intrinsic::x86_sse2_psra_d:
12787 case Intrinsic::x86_avx2_psra_w:
12788 case Intrinsic::x86_avx2_psra_d: {
12791 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12792 case Intrinsic::x86_sse2_psll_w:
12793 case Intrinsic::x86_sse2_psll_d:
12794 case Intrinsic::x86_sse2_psll_q:
12795 case Intrinsic::x86_avx2_psll_w:
12796 case Intrinsic::x86_avx2_psll_d:
12797 case Intrinsic::x86_avx2_psll_q:
12798 Opcode = X86ISD::VSHL;
12800 case Intrinsic::x86_sse2_psrl_w:
12801 case Intrinsic::x86_sse2_psrl_d:
12802 case Intrinsic::x86_sse2_psrl_q:
12803 case Intrinsic::x86_avx2_psrl_w:
12804 case Intrinsic::x86_avx2_psrl_d:
12805 case Intrinsic::x86_avx2_psrl_q:
12806 Opcode = X86ISD::VSRL;
12808 case Intrinsic::x86_sse2_psra_w:
12809 case Intrinsic::x86_sse2_psra_d:
12810 case Intrinsic::x86_avx2_psra_w:
12811 case Intrinsic::x86_avx2_psra_d:
12812 Opcode = X86ISD::VSRA;
12815 return DAG.getNode(Opcode, dl, Op.getValueType(),
12816 Op.getOperand(1), Op.getOperand(2));
12819 // SSE/AVX immediate shift intrinsics
12820 case Intrinsic::x86_sse2_pslli_w:
12821 case Intrinsic::x86_sse2_pslli_d:
12822 case Intrinsic::x86_sse2_pslli_q:
12823 case Intrinsic::x86_avx2_pslli_w:
12824 case Intrinsic::x86_avx2_pslli_d:
12825 case Intrinsic::x86_avx2_pslli_q:
12826 case Intrinsic::x86_sse2_psrli_w:
12827 case Intrinsic::x86_sse2_psrli_d:
12828 case Intrinsic::x86_sse2_psrli_q:
12829 case Intrinsic::x86_avx2_psrli_w:
12830 case Intrinsic::x86_avx2_psrli_d:
12831 case Intrinsic::x86_avx2_psrli_q:
12832 case Intrinsic::x86_sse2_psrai_w:
12833 case Intrinsic::x86_sse2_psrai_d:
12834 case Intrinsic::x86_avx2_psrai_w:
12835 case Intrinsic::x86_avx2_psrai_d: {
12838 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12839 case Intrinsic::x86_sse2_pslli_w:
12840 case Intrinsic::x86_sse2_pslli_d:
12841 case Intrinsic::x86_sse2_pslli_q:
12842 case Intrinsic::x86_avx2_pslli_w:
12843 case Intrinsic::x86_avx2_pslli_d:
12844 case Intrinsic::x86_avx2_pslli_q:
12845 Opcode = X86ISD::VSHLI;
12847 case Intrinsic::x86_sse2_psrli_w:
12848 case Intrinsic::x86_sse2_psrli_d:
12849 case Intrinsic::x86_sse2_psrli_q:
12850 case Intrinsic::x86_avx2_psrli_w:
12851 case Intrinsic::x86_avx2_psrli_d:
12852 case Intrinsic::x86_avx2_psrli_q:
12853 Opcode = X86ISD::VSRLI;
12855 case Intrinsic::x86_sse2_psrai_w:
12856 case Intrinsic::x86_sse2_psrai_d:
12857 case Intrinsic::x86_avx2_psrai_w:
12858 case Intrinsic::x86_avx2_psrai_d:
12859 Opcode = X86ISD::VSRAI;
12862 return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
12863 Op.getOperand(1), Op.getOperand(2), DAG);
12866 case Intrinsic::x86_sse42_pcmpistria128:
12867 case Intrinsic::x86_sse42_pcmpestria128:
12868 case Intrinsic::x86_sse42_pcmpistric128:
12869 case Intrinsic::x86_sse42_pcmpestric128:
12870 case Intrinsic::x86_sse42_pcmpistrio128:
12871 case Intrinsic::x86_sse42_pcmpestrio128:
12872 case Intrinsic::x86_sse42_pcmpistris128:
12873 case Intrinsic::x86_sse42_pcmpestris128:
12874 case Intrinsic::x86_sse42_pcmpistriz128:
12875 case Intrinsic::x86_sse42_pcmpestriz128: {
12879 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12880 case Intrinsic::x86_sse42_pcmpistria128:
12881 Opcode = X86ISD::PCMPISTRI;
12882 X86CC = X86::COND_A;
12884 case Intrinsic::x86_sse42_pcmpestria128:
12885 Opcode = X86ISD::PCMPESTRI;
12886 X86CC = X86::COND_A;
12888 case Intrinsic::x86_sse42_pcmpistric128:
12889 Opcode = X86ISD::PCMPISTRI;
12890 X86CC = X86::COND_B;
12892 case Intrinsic::x86_sse42_pcmpestric128:
12893 Opcode = X86ISD::PCMPESTRI;
12894 X86CC = X86::COND_B;
12896 case Intrinsic::x86_sse42_pcmpistrio128:
12897 Opcode = X86ISD::PCMPISTRI;
12898 X86CC = X86::COND_O;
12900 case Intrinsic::x86_sse42_pcmpestrio128:
12901 Opcode = X86ISD::PCMPESTRI;
12902 X86CC = X86::COND_O;
12904 case Intrinsic::x86_sse42_pcmpistris128:
12905 Opcode = X86ISD::PCMPISTRI;
12906 X86CC = X86::COND_S;
12908 case Intrinsic::x86_sse42_pcmpestris128:
12909 Opcode = X86ISD::PCMPESTRI;
12910 X86CC = X86::COND_S;
12912 case Intrinsic::x86_sse42_pcmpistriz128:
12913 Opcode = X86ISD::PCMPISTRI;
12914 X86CC = X86::COND_E;
12916 case Intrinsic::x86_sse42_pcmpestriz128:
12917 Opcode = X86ISD::PCMPESTRI;
12918 X86CC = X86::COND_E;
12921 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12922 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12923 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
12924 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12925 DAG.getConstant(X86CC, MVT::i8),
12926 SDValue(PCMP.getNode(), 1));
12927 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12930 case Intrinsic::x86_sse42_pcmpistri128:
12931 case Intrinsic::x86_sse42_pcmpestri128: {
12933 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
12934 Opcode = X86ISD::PCMPISTRI;
12936 Opcode = X86ISD::PCMPESTRI;
12938 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12939 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12940 return DAG.getNode(Opcode, dl, VTs, NewOps);
12942 case Intrinsic::x86_fma_vfmadd_ps:
12943 case Intrinsic::x86_fma_vfmadd_pd:
12944 case Intrinsic::x86_fma_vfmsub_ps:
12945 case Intrinsic::x86_fma_vfmsub_pd:
12946 case Intrinsic::x86_fma_vfnmadd_ps:
12947 case Intrinsic::x86_fma_vfnmadd_pd:
12948 case Intrinsic::x86_fma_vfnmsub_ps:
12949 case Intrinsic::x86_fma_vfnmsub_pd:
12950 case Intrinsic::x86_fma_vfmaddsub_ps:
12951 case Intrinsic::x86_fma_vfmaddsub_pd:
12952 case Intrinsic::x86_fma_vfmsubadd_ps:
12953 case Intrinsic::x86_fma_vfmsubadd_pd:
12954 case Intrinsic::x86_fma_vfmadd_ps_256:
12955 case Intrinsic::x86_fma_vfmadd_pd_256:
12956 case Intrinsic::x86_fma_vfmsub_ps_256:
12957 case Intrinsic::x86_fma_vfmsub_pd_256:
12958 case Intrinsic::x86_fma_vfnmadd_ps_256:
12959 case Intrinsic::x86_fma_vfnmadd_pd_256:
12960 case Intrinsic::x86_fma_vfnmsub_ps_256:
12961 case Intrinsic::x86_fma_vfnmsub_pd_256:
12962 case Intrinsic::x86_fma_vfmaddsub_ps_256:
12963 case Intrinsic::x86_fma_vfmaddsub_pd_256:
12964 case Intrinsic::x86_fma_vfmsubadd_ps_256:
12965 case Intrinsic::x86_fma_vfmsubadd_pd_256:
12966 case Intrinsic::x86_fma_vfmadd_ps_512:
12967 case Intrinsic::x86_fma_vfmadd_pd_512:
12968 case Intrinsic::x86_fma_vfmsub_ps_512:
12969 case Intrinsic::x86_fma_vfmsub_pd_512:
12970 case Intrinsic::x86_fma_vfnmadd_ps_512:
12971 case Intrinsic::x86_fma_vfnmadd_pd_512:
12972 case Intrinsic::x86_fma_vfnmsub_ps_512:
12973 case Intrinsic::x86_fma_vfnmsub_pd_512:
12974 case Intrinsic::x86_fma_vfmaddsub_ps_512:
12975 case Intrinsic::x86_fma_vfmaddsub_pd_512:
12976 case Intrinsic::x86_fma_vfmsubadd_ps_512:
12977 case Intrinsic::x86_fma_vfmsubadd_pd_512: {
12980 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12981 case Intrinsic::x86_fma_vfmadd_ps:
12982 case Intrinsic::x86_fma_vfmadd_pd:
12983 case Intrinsic::x86_fma_vfmadd_ps_256:
12984 case Intrinsic::x86_fma_vfmadd_pd_256:
12985 case Intrinsic::x86_fma_vfmadd_ps_512:
12986 case Intrinsic::x86_fma_vfmadd_pd_512:
12987 Opc = X86ISD::FMADD;
12989 case Intrinsic::x86_fma_vfmsub_ps:
12990 case Intrinsic::x86_fma_vfmsub_pd:
12991 case Intrinsic::x86_fma_vfmsub_ps_256:
12992 case Intrinsic::x86_fma_vfmsub_pd_256:
12993 case Intrinsic::x86_fma_vfmsub_ps_512:
12994 case Intrinsic::x86_fma_vfmsub_pd_512:
12995 Opc = X86ISD::FMSUB;
12997 case Intrinsic::x86_fma_vfnmadd_ps:
12998 case Intrinsic::x86_fma_vfnmadd_pd:
12999 case Intrinsic::x86_fma_vfnmadd_ps_256:
13000 case Intrinsic::x86_fma_vfnmadd_pd_256:
13001 case Intrinsic::x86_fma_vfnmadd_ps_512:
13002 case Intrinsic::x86_fma_vfnmadd_pd_512:
13003 Opc = X86ISD::FNMADD;
13005 case Intrinsic::x86_fma_vfnmsub_ps:
13006 case Intrinsic::x86_fma_vfnmsub_pd:
13007 case Intrinsic::x86_fma_vfnmsub_ps_256:
13008 case Intrinsic::x86_fma_vfnmsub_pd_256:
13009 case Intrinsic::x86_fma_vfnmsub_ps_512:
13010 case Intrinsic::x86_fma_vfnmsub_pd_512:
13011 Opc = X86ISD::FNMSUB;
13013 case Intrinsic::x86_fma_vfmaddsub_ps:
13014 case Intrinsic::x86_fma_vfmaddsub_pd:
13015 case Intrinsic::x86_fma_vfmaddsub_ps_256:
13016 case Intrinsic::x86_fma_vfmaddsub_pd_256:
13017 case Intrinsic::x86_fma_vfmaddsub_ps_512:
13018 case Intrinsic::x86_fma_vfmaddsub_pd_512:
13019 Opc = X86ISD::FMADDSUB;
13021 case Intrinsic::x86_fma_vfmsubadd_ps:
13022 case Intrinsic::x86_fma_vfmsubadd_pd:
13023 case Intrinsic::x86_fma_vfmsubadd_ps_256:
13024 case Intrinsic::x86_fma_vfmsubadd_pd_256:
13025 case Intrinsic::x86_fma_vfmsubadd_ps_512:
13026 case Intrinsic::x86_fma_vfmsubadd_pd_512:
13027 Opc = X86ISD::FMSUBADD;
13031 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
13032 Op.getOperand(2), Op.getOperand(3));
13037 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
13038 SDValue Src, SDValue Mask, SDValue Base,
13039 SDValue Index, SDValue ScaleOp, SDValue Chain,
13040 const X86Subtarget * Subtarget) {
13042 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
13043 assert(C && "Invalid scale type");
13044 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
13045 EVT MaskVT = MVT::getVectorVT(MVT::i1,
13046 Index.getSimpleValueType().getVectorNumElements());
13048 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
13050 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
13052 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
13053 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
13054 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
13055 SDValue Segment = DAG.getRegister(0, MVT::i32);
13056 if (Src.getOpcode() == ISD::UNDEF)
13057 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
13058 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
13059 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
13060 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
13061 return DAG.getMergeValues(RetOps, dl);
13064 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
13065 SDValue Src, SDValue Mask, SDValue Base,
13066 SDValue Index, SDValue ScaleOp, SDValue Chain) {
13068 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
13069 assert(C && "Invalid scale type");
13070 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
13071 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
13072 SDValue Segment = DAG.getRegister(0, MVT::i32);
13073 EVT MaskVT = MVT::getVectorVT(MVT::i1,
13074 Index.getSimpleValueType().getVectorNumElements());
13076 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
13078 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
13080 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
13081 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
13082 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
13083 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
13084 return SDValue(Res, 1);
13087 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
13088 SDValue Mask, SDValue Base, SDValue Index,
13089 SDValue ScaleOp, SDValue Chain) {
13091 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
13092 assert(C && "Invalid scale type");
13093 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
13094 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
13095 SDValue Segment = DAG.getRegister(0, MVT::i32);
13097 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
13099 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
13101 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
13103 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
13104 //SDVTList VTs = DAG.getVTList(MVT::Other);
13105 SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
13106 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
13107 return SDValue(Res, 0);
13110 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
13111 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
13112 // also used to custom lower READCYCLECOUNTER nodes.
13113 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
13114 SelectionDAG &DAG, const X86Subtarget *Subtarget,
13115 SmallVectorImpl<SDValue> &Results) {
13116 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13117 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
13120 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
13121 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
13122 // and the EAX register is loaded with the low-order 32 bits.
13123 if (Subtarget->is64Bit()) {
13124 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
13125 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
13128 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
13129 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
13132 SDValue Chain = HI.getValue(1);
13134 if (Opcode == X86ISD::RDTSCP_DAG) {
13135 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
13137 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
13138 // the ECX register. Add 'ecx' explicitly to the chain.
13139 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
13141 // Explicitly store the content of ECX at the location passed in input
13142 // to the 'rdtscp' intrinsic.
13143 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
13144 MachinePointerInfo(), false, false, 0);
13147 if (Subtarget->is64Bit()) {
13148 // The EDX register is loaded with the high-order 32 bits of the MSR, and
13149 // the EAX register is loaded with the low-order 32 bits.
13150 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
13151 DAG.getConstant(32, MVT::i8));
13152 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
13153 Results.push_back(Chain);
13157 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
13158 SDValue Ops[] = { LO, HI };
13159 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
13160 Results.push_back(Pair);
13161 Results.push_back(Chain);
13164 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
13165 SelectionDAG &DAG) {
13166 SmallVector<SDValue, 2> Results;
13168 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
13170 return DAG.getMergeValues(Results, DL);
13173 enum IntrinsicType {
13174 GATHER, SCATTER, PREFETCH, RDSEED, RDRAND, RDTSC, XTEST
13177 struct IntrinsicData {
13178 IntrinsicData(IntrinsicType IType, unsigned IOpc0, unsigned IOpc1)
13179 :Type(IType), Opc0(IOpc0), Opc1(IOpc1) {}
13180 IntrinsicType Type;
13185 std::map < unsigned, IntrinsicData> IntrMap;
13186 static void InitIntinsicsMap() {
13187 static bool Initialized = false;
13190 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
13191 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
13192 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
13193 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
13194 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpd_512,
13195 IntrinsicData(GATHER, X86::VGATHERQPDZrm, 0)));
13196 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpd_512,
13197 IntrinsicData(GATHER, X86::VGATHERDPDZrm, 0)));
13198 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dps_512,
13199 IntrinsicData(GATHER, X86::VGATHERDPSZrm, 0)));
13200 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpi_512,
13201 IntrinsicData(GATHER, X86::VPGATHERQDZrm, 0)));
13202 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpq_512,
13203 IntrinsicData(GATHER, X86::VPGATHERQQZrm, 0)));
13204 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpi_512,
13205 IntrinsicData(GATHER, X86::VPGATHERDDZrm, 0)));
13206 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpq_512,
13207 IntrinsicData(GATHER, X86::VPGATHERDQZrm, 0)));
13209 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qps_512,
13210 IntrinsicData(SCATTER, X86::VSCATTERQPSZmr, 0)));
13211 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpd_512,
13212 IntrinsicData(SCATTER, X86::VSCATTERQPDZmr, 0)));
13213 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpd_512,
13214 IntrinsicData(SCATTER, X86::VSCATTERDPDZmr, 0)));
13215 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dps_512,
13216 IntrinsicData(SCATTER, X86::VSCATTERDPSZmr, 0)));
13217 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpi_512,
13218 IntrinsicData(SCATTER, X86::VPSCATTERQDZmr, 0)));
13219 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpq_512,
13220 IntrinsicData(SCATTER, X86::VPSCATTERQQZmr, 0)));
13221 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpi_512,
13222 IntrinsicData(SCATTER, X86::VPSCATTERDDZmr, 0)));
13223 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpq_512,
13224 IntrinsicData(SCATTER, X86::VPSCATTERDQZmr, 0)));
13226 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qps_512,
13227 IntrinsicData(PREFETCH, X86::VGATHERPF0QPSm,
13228 X86::VGATHERPF1QPSm)));
13229 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qpd_512,
13230 IntrinsicData(PREFETCH, X86::VGATHERPF0QPDm,
13231 X86::VGATHERPF1QPDm)));
13232 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dpd_512,
13233 IntrinsicData(PREFETCH, X86::VGATHERPF0DPDm,
13234 X86::VGATHERPF1DPDm)));
13235 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dps_512,
13236 IntrinsicData(PREFETCH, X86::VGATHERPF0DPSm,
13237 X86::VGATHERPF1DPSm)));
13238 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qps_512,
13239 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPSm,
13240 X86::VSCATTERPF1QPSm)));
13241 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qpd_512,
13242 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPDm,
13243 X86::VSCATTERPF1QPDm)));
13244 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dpd_512,
13245 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPDm,
13246 X86::VSCATTERPF1DPDm)));
13247 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dps_512,
13248 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPSm,
13249 X86::VSCATTERPF1DPSm)));
13250 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_16,
13251 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
13252 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_32,
13253 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
13254 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_64,
13255 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
13256 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_16,
13257 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
13258 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_32,
13259 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
13260 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_64,
13261 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
13262 IntrMap.insert(std::make_pair(Intrinsic::x86_xtest,
13263 IntrinsicData(XTEST, X86ISD::XTEST, 0)));
13264 IntrMap.insert(std::make_pair(Intrinsic::x86_rdtsc,
13265 IntrinsicData(RDTSC, X86ISD::RDTSC_DAG, 0)));
13266 IntrMap.insert(std::make_pair(Intrinsic::x86_rdtscp,
13267 IntrinsicData(RDTSC, X86ISD::RDTSCP_DAG, 0)));
13268 Initialized = true;
13271 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
13272 SelectionDAG &DAG) {
13273 InitIntinsicsMap();
13274 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
13275 std::map < unsigned, IntrinsicData>::const_iterator itr = IntrMap.find(IntNo);
13276 if (itr == IntrMap.end())
13280 IntrinsicData Intr = itr->second;
13281 switch(Intr.Type) {
13284 // Emit the node with the right value type.
13285 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
13286 SDValue Result = DAG.getNode(Intr.Opc0, dl, VTs, Op.getOperand(0));
13288 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
13289 // Otherwise return the value from Rand, which is always 0, casted to i32.
13290 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
13291 DAG.getConstant(1, Op->getValueType(1)),
13292 DAG.getConstant(X86::COND_B, MVT::i32),
13293 SDValue(Result.getNode(), 1) };
13294 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
13295 DAG.getVTList(Op->getValueType(1), MVT::Glue),
13298 // Return { result, isValid, chain }.
13299 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
13300 SDValue(Result.getNode(), 2));
13303 //gather(v1, mask, index, base, scale);
13304 SDValue Chain = Op.getOperand(0);
13305 SDValue Src = Op.getOperand(2);
13306 SDValue Base = Op.getOperand(3);
13307 SDValue Index = Op.getOperand(4);
13308 SDValue Mask = Op.getOperand(5);
13309 SDValue Scale = Op.getOperand(6);
13310 return getGatherNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
13314 //scatter(base, mask, index, v1, scale);
13315 SDValue Chain = Op.getOperand(0);
13316 SDValue Base = Op.getOperand(2);
13317 SDValue Mask = Op.getOperand(3);
13318 SDValue Index = Op.getOperand(4);
13319 SDValue Src = Op.getOperand(5);
13320 SDValue Scale = Op.getOperand(6);
13321 return getScatterNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
13324 SDValue Hint = Op.getOperand(6);
13326 if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
13327 (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
13328 llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
13329 unsigned Opcode = (HintVal ? Intr.Opc1 : Intr.Opc0);
13330 SDValue Chain = Op.getOperand(0);
13331 SDValue Mask = Op.getOperand(2);
13332 SDValue Index = Op.getOperand(3);
13333 SDValue Base = Op.getOperand(4);
13334 SDValue Scale = Op.getOperand(5);
13335 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
13337 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
13339 SmallVector<SDValue, 2> Results;
13340 getReadTimeStampCounter(Op.getNode(), dl, Intr.Opc0, DAG, Subtarget, Results);
13341 return DAG.getMergeValues(Results, dl);
13343 // XTEST intrinsics.
13345 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
13346 SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
13347 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13348 DAG.getConstant(X86::COND_NE, MVT::i8),
13350 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
13351 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
13352 Ret, SDValue(InTrans.getNode(), 1));
13355 llvm_unreachable("Unknown Intrinsic Type");
13358 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
13359 SelectionDAG &DAG) const {
13360 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13361 MFI->setReturnAddressIsTaken(true);
13363 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
13366 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13368 EVT PtrVT = getPointerTy();
13371 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
13372 const X86RegisterInfo *RegInfo =
13373 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13374 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
13375 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
13376 DAG.getNode(ISD::ADD, dl, PtrVT,
13377 FrameAddr, Offset),
13378 MachinePointerInfo(), false, false, false, 0);
13381 // Just load the return address.
13382 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
13383 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
13384 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
13387 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
13388 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13389 MFI->setFrameAddressIsTaken(true);
13391 EVT VT = Op.getValueType();
13392 SDLoc dl(Op); // FIXME probably not meaningful
13393 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13394 const X86RegisterInfo *RegInfo =
13395 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13396 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
13397 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
13398 (FrameReg == X86::EBP && VT == MVT::i32)) &&
13399 "Invalid Frame Register!");
13400 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
13402 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
13403 MachinePointerInfo(),
13404 false, false, false, 0);
13408 // FIXME? Maybe this could be a TableGen attribute on some registers and
13409 // this table could be generated automatically from RegInfo.
13410 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
13412 unsigned Reg = StringSwitch<unsigned>(RegName)
13413 .Case("esp", X86::ESP)
13414 .Case("rsp", X86::RSP)
13418 report_fatal_error("Invalid register name global variable");
13421 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
13422 SelectionDAG &DAG) const {
13423 const X86RegisterInfo *RegInfo =
13424 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13425 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
13428 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
13429 SDValue Chain = Op.getOperand(0);
13430 SDValue Offset = Op.getOperand(1);
13431 SDValue Handler = Op.getOperand(2);
13434 EVT PtrVT = getPointerTy();
13435 const X86RegisterInfo *RegInfo =
13436 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13437 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
13438 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
13439 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
13440 "Invalid Frame Register!");
13441 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
13442 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
13444 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
13445 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
13446 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
13447 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
13449 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
13451 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
13452 DAG.getRegister(StoreAddrReg, PtrVT));
13455 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
13456 SelectionDAG &DAG) const {
13458 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
13459 DAG.getVTList(MVT::i32, MVT::Other),
13460 Op.getOperand(0), Op.getOperand(1));
13463 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
13464 SelectionDAG &DAG) const {
13466 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
13467 Op.getOperand(0), Op.getOperand(1));
13470 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
13471 return Op.getOperand(0);
13474 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
13475 SelectionDAG &DAG) const {
13476 SDValue Root = Op.getOperand(0);
13477 SDValue Trmp = Op.getOperand(1); // trampoline
13478 SDValue FPtr = Op.getOperand(2); // nested function
13479 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
13482 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
13483 const TargetRegisterInfo* TRI = DAG.getTarget().getRegisterInfo();
13485 if (Subtarget->is64Bit()) {
13486 SDValue OutChains[6];
13488 // Large code-model.
13489 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
13490 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
13492 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
13493 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
13495 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
13497 // Load the pointer to the nested function into R11.
13498 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
13499 SDValue Addr = Trmp;
13500 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13501 Addr, MachinePointerInfo(TrmpAddr),
13504 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13505 DAG.getConstant(2, MVT::i64));
13506 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
13507 MachinePointerInfo(TrmpAddr, 2),
13510 // Load the 'nest' parameter value into R10.
13511 // R10 is specified in X86CallingConv.td
13512 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
13513 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13514 DAG.getConstant(10, MVT::i64));
13515 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13516 Addr, MachinePointerInfo(TrmpAddr, 10),
13519 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13520 DAG.getConstant(12, MVT::i64));
13521 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
13522 MachinePointerInfo(TrmpAddr, 12),
13525 // Jump to the nested function.
13526 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
13527 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13528 DAG.getConstant(20, MVT::i64));
13529 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13530 Addr, MachinePointerInfo(TrmpAddr, 20),
13533 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
13534 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13535 DAG.getConstant(22, MVT::i64));
13536 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
13537 MachinePointerInfo(TrmpAddr, 22),
13540 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
13542 const Function *Func =
13543 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
13544 CallingConv::ID CC = Func->getCallingConv();
13549 llvm_unreachable("Unsupported calling convention");
13550 case CallingConv::C:
13551 case CallingConv::X86_StdCall: {
13552 // Pass 'nest' parameter in ECX.
13553 // Must be kept in sync with X86CallingConv.td
13554 NestReg = X86::ECX;
13556 // Check that ECX wasn't needed by an 'inreg' parameter.
13557 FunctionType *FTy = Func->getFunctionType();
13558 const AttributeSet &Attrs = Func->getAttributes();
13560 if (!Attrs.isEmpty() && !Func->isVarArg()) {
13561 unsigned InRegCount = 0;
13564 for (FunctionType::param_iterator I = FTy->param_begin(),
13565 E = FTy->param_end(); I != E; ++I, ++Idx)
13566 if (Attrs.hasAttribute(Idx, Attribute::InReg))
13567 // FIXME: should only count parameters that are lowered to integers.
13568 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
13570 if (InRegCount > 2) {
13571 report_fatal_error("Nest register in use - reduce number of inreg"
13577 case CallingConv::X86_FastCall:
13578 case CallingConv::X86_ThisCall:
13579 case CallingConv::Fast:
13580 // Pass 'nest' parameter in EAX.
13581 // Must be kept in sync with X86CallingConv.td
13582 NestReg = X86::EAX;
13586 SDValue OutChains[4];
13587 SDValue Addr, Disp;
13589 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13590 DAG.getConstant(10, MVT::i32));
13591 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
13593 // This is storing the opcode for MOV32ri.
13594 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
13595 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
13596 OutChains[0] = DAG.getStore(Root, dl,
13597 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
13598 Trmp, MachinePointerInfo(TrmpAddr),
13601 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13602 DAG.getConstant(1, MVT::i32));
13603 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
13604 MachinePointerInfo(TrmpAddr, 1),
13607 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
13608 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13609 DAG.getConstant(5, MVT::i32));
13610 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
13611 MachinePointerInfo(TrmpAddr, 5),
13614 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13615 DAG.getConstant(6, MVT::i32));
13616 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
13617 MachinePointerInfo(TrmpAddr, 6),
13620 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
13624 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
13625 SelectionDAG &DAG) const {
13627 The rounding mode is in bits 11:10 of FPSR, and has the following
13629 00 Round to nearest
13634 FLT_ROUNDS, on the other hand, expects the following:
13641 To perform the conversion, we do:
13642 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
13645 MachineFunction &MF = DAG.getMachineFunction();
13646 const TargetMachine &TM = MF.getTarget();
13647 const TargetFrameLowering &TFI = *TM.getFrameLowering();
13648 unsigned StackAlignment = TFI.getStackAlignment();
13649 MVT VT = Op.getSimpleValueType();
13652 // Save FP Control Word to stack slot
13653 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
13654 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
13656 MachineMemOperand *MMO =
13657 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
13658 MachineMemOperand::MOStore, 2, 2);
13660 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
13661 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
13662 DAG.getVTList(MVT::Other),
13663 Ops, MVT::i16, MMO);
13665 // Load FP Control Word from stack slot
13666 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
13667 MachinePointerInfo(), false, false, false, 0);
13669 // Transform as necessary
13671 DAG.getNode(ISD::SRL, DL, MVT::i16,
13672 DAG.getNode(ISD::AND, DL, MVT::i16,
13673 CWD, DAG.getConstant(0x800, MVT::i16)),
13674 DAG.getConstant(11, MVT::i8));
13676 DAG.getNode(ISD::SRL, DL, MVT::i16,
13677 DAG.getNode(ISD::AND, DL, MVT::i16,
13678 CWD, DAG.getConstant(0x400, MVT::i16)),
13679 DAG.getConstant(9, MVT::i8));
13682 DAG.getNode(ISD::AND, DL, MVT::i16,
13683 DAG.getNode(ISD::ADD, DL, MVT::i16,
13684 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
13685 DAG.getConstant(1, MVT::i16)),
13686 DAG.getConstant(3, MVT::i16));
13688 return DAG.getNode((VT.getSizeInBits() < 16 ?
13689 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
13692 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
13693 MVT VT = Op.getSimpleValueType();
13695 unsigned NumBits = VT.getSizeInBits();
13698 Op = Op.getOperand(0);
13699 if (VT == MVT::i8) {
13700 // Zero extend to i32 since there is not an i8 bsr.
13702 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13705 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
13706 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13707 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13709 // If src is zero (i.e. bsr sets ZF), returns NumBits.
13712 DAG.getConstant(NumBits+NumBits-1, OpVT),
13713 DAG.getConstant(X86::COND_E, MVT::i8),
13716 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
13718 // Finally xor with NumBits-1.
13719 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13722 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13726 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
13727 MVT VT = Op.getSimpleValueType();
13729 unsigned NumBits = VT.getSizeInBits();
13732 Op = Op.getOperand(0);
13733 if (VT == MVT::i8) {
13734 // Zero extend to i32 since there is not an i8 bsr.
13736 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13739 // Issue a bsr (scan bits in reverse).
13740 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13741 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13743 // And xor with NumBits-1.
13744 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13747 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13751 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
13752 MVT VT = Op.getSimpleValueType();
13753 unsigned NumBits = VT.getSizeInBits();
13755 Op = Op.getOperand(0);
13757 // Issue a bsf (scan bits forward) which also sets EFLAGS.
13758 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13759 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
13761 // If src is zero (i.e. bsf sets ZF), returns NumBits.
13764 DAG.getConstant(NumBits, VT),
13765 DAG.getConstant(X86::COND_E, MVT::i8),
13768 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
13771 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
13772 // ones, and then concatenate the result back.
13773 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
13774 MVT VT = Op.getSimpleValueType();
13776 assert(VT.is256BitVector() && VT.isInteger() &&
13777 "Unsupported value type for operation");
13779 unsigned NumElems = VT.getVectorNumElements();
13782 // Extract the LHS vectors
13783 SDValue LHS = Op.getOperand(0);
13784 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13785 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13787 // Extract the RHS vectors
13788 SDValue RHS = Op.getOperand(1);
13789 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13790 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13792 MVT EltVT = VT.getVectorElementType();
13793 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13795 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13796 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
13797 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
13800 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
13801 assert(Op.getSimpleValueType().is256BitVector() &&
13802 Op.getSimpleValueType().isInteger() &&
13803 "Only handle AVX 256-bit vector integer operation");
13804 return Lower256IntArith(Op, DAG);
13807 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
13808 assert(Op.getSimpleValueType().is256BitVector() &&
13809 Op.getSimpleValueType().isInteger() &&
13810 "Only handle AVX 256-bit vector integer operation");
13811 return Lower256IntArith(Op, DAG);
13814 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
13815 SelectionDAG &DAG) {
13817 MVT VT = Op.getSimpleValueType();
13819 // Decompose 256-bit ops into smaller 128-bit ops.
13820 if (VT.is256BitVector() && !Subtarget->hasInt256())
13821 return Lower256IntArith(Op, DAG);
13823 SDValue A = Op.getOperand(0);
13824 SDValue B = Op.getOperand(1);
13826 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
13827 if (VT == MVT::v4i32) {
13828 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
13829 "Should not custom lower when pmuldq is available!");
13831 // Extract the odd parts.
13832 static const int UnpackMask[] = { 1, -1, 3, -1 };
13833 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
13834 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
13836 // Multiply the even parts.
13837 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
13838 // Now multiply odd parts.
13839 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
13841 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
13842 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
13844 // Merge the two vectors back together with a shuffle. This expands into 2
13846 static const int ShufMask[] = { 0, 4, 2, 6 };
13847 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
13850 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
13851 "Only know how to lower V2I64/V4I64/V8I64 multiply");
13853 // Ahi = psrlqi(a, 32);
13854 // Bhi = psrlqi(b, 32);
13856 // AloBlo = pmuludq(a, b);
13857 // AloBhi = pmuludq(a, Bhi);
13858 // AhiBlo = pmuludq(Ahi, b);
13860 // AloBhi = psllqi(AloBhi, 32);
13861 // AhiBlo = psllqi(AhiBlo, 32);
13862 // return AloBlo + AloBhi + AhiBlo;
13864 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
13865 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
13867 // Bit cast to 32-bit vectors for MULUDQ
13868 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
13869 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
13870 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
13871 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
13872 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
13873 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
13875 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
13876 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
13877 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
13879 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
13880 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
13882 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
13883 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
13886 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
13887 assert(Subtarget->isTargetWin64() && "Unexpected target");
13888 EVT VT = Op.getValueType();
13889 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
13890 "Unexpected return type for lowering");
13894 switch (Op->getOpcode()) {
13895 default: llvm_unreachable("Unexpected request for libcall!");
13896 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
13897 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
13898 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
13899 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
13900 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
13901 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
13905 SDValue InChain = DAG.getEntryNode();
13907 TargetLowering::ArgListTy Args;
13908 TargetLowering::ArgListEntry Entry;
13909 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
13910 EVT ArgVT = Op->getOperand(i).getValueType();
13911 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
13912 "Unexpected argument type for lowering");
13913 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
13914 Entry.Node = StackPtr;
13915 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
13917 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13918 Entry.Ty = PointerType::get(ArgTy,0);
13919 Entry.isSExt = false;
13920 Entry.isZExt = false;
13921 Args.push_back(Entry);
13924 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
13927 TargetLowering::CallLoweringInfo CLI(DAG);
13928 CLI.setDebugLoc(dl).setChain(InChain)
13929 .setCallee(getLibcallCallingConv(LC),
13930 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
13932 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
13934 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
13935 return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
13938 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
13939 SelectionDAG &DAG) {
13940 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
13941 EVT VT = Op0.getValueType();
13944 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
13945 (VT == MVT::v8i32 && Subtarget->hasInt256()));
13947 // Get the high parts.
13948 const int Mask[] = {1, 2, 3, 4, 5, 6, 7, 8};
13949 SDValue Hi0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
13950 SDValue Hi1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
13952 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
13954 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
13955 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
13957 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
13958 SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
13959 DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
13960 SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
13961 DAG.getNode(Opcode, dl, MulVT, Hi0, Hi1));
13963 // Shuffle it back into the right order.
13964 const int HighMask[] = {1, 5, 3, 7, 9, 13, 11, 15};
13965 SDValue Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
13966 const int LowMask[] = {0, 4, 2, 6, 8, 12, 10, 14};
13967 SDValue Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
13969 // If we have a signed multiply but no PMULDQ fix up the high parts of a
13970 // unsigned multiply.
13971 if (IsSigned && !Subtarget->hasSSE41()) {
13973 DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
13974 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
13975 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
13976 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
13977 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
13979 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
13980 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
13983 return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Highs, Lows);
13986 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
13987 const X86Subtarget *Subtarget) {
13988 MVT VT = Op.getSimpleValueType();
13990 SDValue R = Op.getOperand(0);
13991 SDValue Amt = Op.getOperand(1);
13993 // Optimize shl/srl/sra with constant shift amount.
13994 if (isSplatVector(Amt.getNode())) {
13995 SDValue SclrAmt = Amt->getOperand(0);
13996 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
13997 uint64_t ShiftAmt = C->getZExtValue();
13999 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
14000 (Subtarget->hasInt256() &&
14001 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
14002 (Subtarget->hasAVX512() &&
14003 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
14004 if (Op.getOpcode() == ISD::SHL)
14005 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
14007 if (Op.getOpcode() == ISD::SRL)
14008 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
14010 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
14011 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
14015 if (VT == MVT::v16i8) {
14016 if (Op.getOpcode() == ISD::SHL) {
14017 // Make a large shift.
14018 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
14019 MVT::v8i16, R, ShiftAmt,
14021 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
14022 // Zero out the rightmost bits.
14023 SmallVector<SDValue, 16> V(16,
14024 DAG.getConstant(uint8_t(-1U << ShiftAmt),
14026 return DAG.getNode(ISD::AND, dl, VT, SHL,
14027 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
14029 if (Op.getOpcode() == ISD::SRL) {
14030 // Make a large shift.
14031 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
14032 MVT::v8i16, R, ShiftAmt,
14034 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
14035 // Zero out the leftmost bits.
14036 SmallVector<SDValue, 16> V(16,
14037 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
14039 return DAG.getNode(ISD::AND, dl, VT, SRL,
14040 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
14042 if (Op.getOpcode() == ISD::SRA) {
14043 if (ShiftAmt == 7) {
14044 // R s>> 7 === R s< 0
14045 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
14046 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
14049 // R s>> a === ((R u>> a) ^ m) - m
14050 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
14051 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
14053 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
14054 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
14055 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
14058 llvm_unreachable("Unknown shift opcode.");
14061 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
14062 if (Op.getOpcode() == ISD::SHL) {
14063 // Make a large shift.
14064 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
14065 MVT::v16i16, R, ShiftAmt,
14067 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
14068 // Zero out the rightmost bits.
14069 SmallVector<SDValue, 32> V(32,
14070 DAG.getConstant(uint8_t(-1U << ShiftAmt),
14072 return DAG.getNode(ISD::AND, dl, VT, SHL,
14073 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
14075 if (Op.getOpcode() == ISD::SRL) {
14076 // Make a large shift.
14077 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
14078 MVT::v16i16, R, ShiftAmt,
14080 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
14081 // Zero out the leftmost bits.
14082 SmallVector<SDValue, 32> V(32,
14083 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
14085 return DAG.getNode(ISD::AND, dl, VT, SRL,
14086 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
14088 if (Op.getOpcode() == ISD::SRA) {
14089 if (ShiftAmt == 7) {
14090 // R s>> 7 === R s< 0
14091 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
14092 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
14095 // R s>> a === ((R u>> a) ^ m) - m
14096 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
14097 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
14099 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
14100 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
14101 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
14104 llvm_unreachable("Unknown shift opcode.");
14109 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
14110 if (!Subtarget->is64Bit() &&
14111 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
14112 Amt.getOpcode() == ISD::BITCAST &&
14113 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
14114 Amt = Amt.getOperand(0);
14115 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
14116 VT.getVectorNumElements();
14117 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
14118 uint64_t ShiftAmt = 0;
14119 for (unsigned i = 0; i != Ratio; ++i) {
14120 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
14124 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
14126 // Check remaining shift amounts.
14127 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
14128 uint64_t ShAmt = 0;
14129 for (unsigned j = 0; j != Ratio; ++j) {
14130 ConstantSDNode *C =
14131 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
14135 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
14137 if (ShAmt != ShiftAmt)
14140 switch (Op.getOpcode()) {
14142 llvm_unreachable("Unknown shift opcode!");
14144 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
14147 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
14150 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
14158 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
14159 const X86Subtarget* Subtarget) {
14160 MVT VT = Op.getSimpleValueType();
14162 SDValue R = Op.getOperand(0);
14163 SDValue Amt = Op.getOperand(1);
14165 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
14166 VT == MVT::v4i32 || VT == MVT::v8i16 ||
14167 (Subtarget->hasInt256() &&
14168 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
14169 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
14170 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
14172 EVT EltVT = VT.getVectorElementType();
14174 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
14175 unsigned NumElts = VT.getVectorNumElements();
14177 for (i = 0; i != NumElts; ++i) {
14178 if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
14182 for (j = i; j != NumElts; ++j) {
14183 SDValue Arg = Amt.getOperand(j);
14184 if (Arg.getOpcode() == ISD::UNDEF) continue;
14185 if (Arg != Amt.getOperand(i))
14188 if (i != NumElts && j == NumElts)
14189 BaseShAmt = Amt.getOperand(i);
14191 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
14192 Amt = Amt.getOperand(0);
14193 if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
14194 cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
14195 SDValue InVec = Amt.getOperand(0);
14196 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
14197 unsigned NumElts = InVec.getValueType().getVectorNumElements();
14199 for (; i != NumElts; ++i) {
14200 SDValue Arg = InVec.getOperand(i);
14201 if (Arg.getOpcode() == ISD::UNDEF) continue;
14205 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
14206 if (ConstantSDNode *C =
14207 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
14208 unsigned SplatIdx =
14209 cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
14210 if (C->getZExtValue() == SplatIdx)
14211 BaseShAmt = InVec.getOperand(1);
14214 if (!BaseShAmt.getNode())
14215 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
14216 DAG.getIntPtrConstant(0));
14220 if (BaseShAmt.getNode()) {
14221 if (EltVT.bitsGT(MVT::i32))
14222 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
14223 else if (EltVT.bitsLT(MVT::i32))
14224 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
14226 switch (Op.getOpcode()) {
14228 llvm_unreachable("Unknown shift opcode!");
14230 switch (VT.SimpleTy) {
14231 default: return SDValue();
14240 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
14243 switch (VT.SimpleTy) {
14244 default: return SDValue();
14251 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
14254 switch (VT.SimpleTy) {
14255 default: return SDValue();
14264 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
14270 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
14271 if (!Subtarget->is64Bit() &&
14272 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
14273 (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
14274 Amt.getOpcode() == ISD::BITCAST &&
14275 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
14276 Amt = Amt.getOperand(0);
14277 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
14278 VT.getVectorNumElements();
14279 std::vector<SDValue> Vals(Ratio);
14280 for (unsigned i = 0; i != Ratio; ++i)
14281 Vals[i] = Amt.getOperand(i);
14282 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
14283 for (unsigned j = 0; j != Ratio; ++j)
14284 if (Vals[j] != Amt.getOperand(i + j))
14287 switch (Op.getOpcode()) {
14289 llvm_unreachable("Unknown shift opcode!");
14291 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
14293 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
14295 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
14302 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
14303 SelectionDAG &DAG) {
14305 MVT VT = Op.getSimpleValueType();
14307 SDValue R = Op.getOperand(0);
14308 SDValue Amt = Op.getOperand(1);
14311 if (!Subtarget->hasSSE2())
14314 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
14318 V = LowerScalarVariableShift(Op, DAG, Subtarget);
14322 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
14324 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
14325 if (Subtarget->hasInt256()) {
14326 if (Op.getOpcode() == ISD::SRL &&
14327 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
14328 VT == MVT::v4i64 || VT == MVT::v8i32))
14330 if (Op.getOpcode() == ISD::SHL &&
14331 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
14332 VT == MVT::v4i64 || VT == MVT::v8i32))
14334 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
14338 // If possible, lower this packed shift into a vector multiply instead of
14339 // expanding it into a sequence of scalar shifts.
14340 // Do this only if the vector shift count is a constant build_vector.
14341 if (Op.getOpcode() == ISD::SHL &&
14342 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
14343 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
14344 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
14345 SmallVector<SDValue, 8> Elts;
14346 EVT SVT = VT.getScalarType();
14347 unsigned SVTBits = SVT.getSizeInBits();
14348 const APInt &One = APInt(SVTBits, 1);
14349 unsigned NumElems = VT.getVectorNumElements();
14351 for (unsigned i=0; i !=NumElems; ++i) {
14352 SDValue Op = Amt->getOperand(i);
14353 if (Op->getOpcode() == ISD::UNDEF) {
14354 Elts.push_back(Op);
14358 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
14359 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
14360 uint64_t ShAmt = C.getZExtValue();
14361 if (ShAmt >= SVTBits) {
14362 Elts.push_back(DAG.getUNDEF(SVT));
14365 Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
14367 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14368 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
14371 // Lower SHL with variable shift amount.
14372 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
14373 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
14375 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
14376 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
14377 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
14378 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
14381 // If possible, lower this shift as a sequence of two shifts by
14382 // constant plus a MOVSS/MOVSD instead of scalarizing it.
14384 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
14386 // Could be rewritten as:
14387 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
14389 // The advantage is that the two shifts from the example would be
14390 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
14391 // the vector shift into four scalar shifts plus four pairs of vector
14393 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
14394 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
14395 unsigned TargetOpcode = X86ISD::MOVSS;
14396 bool CanBeSimplified;
14397 // The splat value for the first packed shift (the 'X' from the example).
14398 SDValue Amt1 = Amt->getOperand(0);
14399 // The splat value for the second packed shift (the 'Y' from the example).
14400 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
14401 Amt->getOperand(2);
14403 // See if it is possible to replace this node with a sequence of
14404 // two shifts followed by a MOVSS/MOVSD
14405 if (VT == MVT::v4i32) {
14406 // Check if it is legal to use a MOVSS.
14407 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
14408 Amt2 == Amt->getOperand(3);
14409 if (!CanBeSimplified) {
14410 // Otherwise, check if we can still simplify this node using a MOVSD.
14411 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
14412 Amt->getOperand(2) == Amt->getOperand(3);
14413 TargetOpcode = X86ISD::MOVSD;
14414 Amt2 = Amt->getOperand(2);
14417 // Do similar checks for the case where the machine value type
14419 CanBeSimplified = Amt1 == Amt->getOperand(1);
14420 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
14421 CanBeSimplified = Amt2 == Amt->getOperand(i);
14423 if (!CanBeSimplified) {
14424 TargetOpcode = X86ISD::MOVSD;
14425 CanBeSimplified = true;
14426 Amt2 = Amt->getOperand(4);
14427 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
14428 CanBeSimplified = Amt1 == Amt->getOperand(i);
14429 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
14430 CanBeSimplified = Amt2 == Amt->getOperand(j);
14434 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
14435 isa<ConstantSDNode>(Amt2)) {
14436 // Replace this node with two shifts followed by a MOVSS/MOVSD.
14437 EVT CastVT = MVT::v4i32;
14439 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
14440 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
14442 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
14443 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
14444 if (TargetOpcode == X86ISD::MOVSD)
14445 CastVT = MVT::v2i64;
14446 SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
14447 SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
14448 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
14450 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
14454 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
14455 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
14458 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
14459 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
14461 // Turn 'a' into a mask suitable for VSELECT
14462 SDValue VSelM = DAG.getConstant(0x80, VT);
14463 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
14464 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
14466 SDValue CM1 = DAG.getConstant(0x0f, VT);
14467 SDValue CM2 = DAG.getConstant(0x3f, VT);
14469 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
14470 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
14471 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
14472 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
14473 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
14476 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
14477 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
14478 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
14480 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
14481 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
14482 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
14483 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
14484 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
14487 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
14488 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
14489 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
14491 // return VSELECT(r, r+r, a);
14492 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
14493 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
14497 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
14498 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
14499 // solution better.
14500 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
14501 MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
14503 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
14504 R = DAG.getNode(ExtOpc, dl, NewVT, R);
14505 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
14506 return DAG.getNode(ISD::TRUNCATE, dl, VT,
14507 DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
14510 // Decompose 256-bit shifts into smaller 128-bit shifts.
14511 if (VT.is256BitVector()) {
14512 unsigned NumElems = VT.getVectorNumElements();
14513 MVT EltVT = VT.getVectorElementType();
14514 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14516 // Extract the two vectors
14517 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
14518 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
14520 // Recreate the shift amount vectors
14521 SDValue Amt1, Amt2;
14522 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
14523 // Constant shift amount
14524 SmallVector<SDValue, 4> Amt1Csts;
14525 SmallVector<SDValue, 4> Amt2Csts;
14526 for (unsigned i = 0; i != NumElems/2; ++i)
14527 Amt1Csts.push_back(Amt->getOperand(i));
14528 for (unsigned i = NumElems/2; i != NumElems; ++i)
14529 Amt2Csts.push_back(Amt->getOperand(i));
14531 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
14532 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
14534 // Variable shift amount
14535 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
14536 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
14539 // Issue new vector shifts for the smaller types
14540 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
14541 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
14543 // Concatenate the result back
14544 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
14550 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
14551 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
14552 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
14553 // looks for this combo and may remove the "setcc" instruction if the "setcc"
14554 // has only one use.
14555 SDNode *N = Op.getNode();
14556 SDValue LHS = N->getOperand(0);
14557 SDValue RHS = N->getOperand(1);
14558 unsigned BaseOp = 0;
14561 switch (Op.getOpcode()) {
14562 default: llvm_unreachable("Unknown ovf instruction!");
14564 // A subtract of one will be selected as a INC. Note that INC doesn't
14565 // set CF, so we can't do this for UADDO.
14566 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14568 BaseOp = X86ISD::INC;
14569 Cond = X86::COND_O;
14572 BaseOp = X86ISD::ADD;
14573 Cond = X86::COND_O;
14576 BaseOp = X86ISD::ADD;
14577 Cond = X86::COND_B;
14580 // A subtract of one will be selected as a DEC. Note that DEC doesn't
14581 // set CF, so we can't do this for USUBO.
14582 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14584 BaseOp = X86ISD::DEC;
14585 Cond = X86::COND_O;
14588 BaseOp = X86ISD::SUB;
14589 Cond = X86::COND_O;
14592 BaseOp = X86ISD::SUB;
14593 Cond = X86::COND_B;
14596 BaseOp = X86ISD::SMUL;
14597 Cond = X86::COND_O;
14599 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
14600 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
14602 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
14605 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14606 DAG.getConstant(X86::COND_O, MVT::i32),
14607 SDValue(Sum.getNode(), 2));
14609 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
14613 // Also sets EFLAGS.
14614 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
14615 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
14618 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
14619 DAG.getConstant(Cond, MVT::i32),
14620 SDValue(Sum.getNode(), 1));
14622 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
14625 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
14626 SelectionDAG &DAG) const {
14628 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
14629 MVT VT = Op.getSimpleValueType();
14631 if (!Subtarget->hasSSE2() || !VT.isVector())
14634 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
14635 ExtraVT.getScalarType().getSizeInBits();
14637 switch (VT.SimpleTy) {
14638 default: return SDValue();
14641 if (!Subtarget->hasFp256())
14643 if (!Subtarget->hasInt256()) {
14644 // needs to be split
14645 unsigned NumElems = VT.getVectorNumElements();
14647 // Extract the LHS vectors
14648 SDValue LHS = Op.getOperand(0);
14649 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14650 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14652 MVT EltVT = VT.getVectorElementType();
14653 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14655 EVT ExtraEltVT = ExtraVT.getVectorElementType();
14656 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
14657 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
14659 SDValue Extra = DAG.getValueType(ExtraVT);
14661 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
14662 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
14664 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
14669 SDValue Op0 = Op.getOperand(0);
14670 SDValue Op00 = Op0.getOperand(0);
14672 // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
14673 if (Op0.getOpcode() == ISD::BITCAST &&
14674 Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
14675 // (sext (vzext x)) -> (vsext x)
14676 Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
14677 if (Tmp1.getNode()) {
14678 EVT ExtraEltVT = ExtraVT.getVectorElementType();
14679 // This folding is only valid when the in-reg type is a vector of i8,
14681 if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
14682 ExtraEltVT == MVT::i32) {
14683 SDValue Tmp1Op0 = Tmp1.getOperand(0);
14684 assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
14685 "This optimization is invalid without a VZEXT.");
14686 return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
14692 // If the above didn't work, then just use Shift-Left + Shift-Right.
14693 Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
14695 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
14701 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
14702 SelectionDAG &DAG) {
14704 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
14705 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
14706 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
14707 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
14709 // The only fence that needs an instruction is a sequentially-consistent
14710 // cross-thread fence.
14711 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
14712 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
14713 // no-sse2). There isn't any reason to disable it if the target processor
14715 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
14716 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
14718 SDValue Chain = Op.getOperand(0);
14719 SDValue Zero = DAG.getConstant(0, MVT::i32);
14721 DAG.getRegister(X86::ESP, MVT::i32), // Base
14722 DAG.getTargetConstant(1, MVT::i8), // Scale
14723 DAG.getRegister(0, MVT::i32), // Index
14724 DAG.getTargetConstant(0, MVT::i32), // Disp
14725 DAG.getRegister(0, MVT::i32), // Segment.
14729 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
14730 return SDValue(Res, 0);
14733 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
14734 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
14737 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
14738 SelectionDAG &DAG) {
14739 MVT T = Op.getSimpleValueType();
14743 switch(T.SimpleTy) {
14744 default: llvm_unreachable("Invalid value type!");
14745 case MVT::i8: Reg = X86::AL; size = 1; break;
14746 case MVT::i16: Reg = X86::AX; size = 2; break;
14747 case MVT::i32: Reg = X86::EAX; size = 4; break;
14749 assert(Subtarget->is64Bit() && "Node not type legal!");
14750 Reg = X86::RAX; size = 8;
14753 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
14754 Op.getOperand(2), SDValue());
14755 SDValue Ops[] = { cpIn.getValue(0),
14758 DAG.getTargetConstant(size, MVT::i8),
14759 cpIn.getValue(1) };
14760 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14761 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
14762 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
14766 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
14767 SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
14768 MVT::i32, cpOut.getValue(2));
14769 SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
14770 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
14772 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
14773 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
14774 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
14778 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
14779 SelectionDAG &DAG) {
14780 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
14781 MVT DstVT = Op.getSimpleValueType();
14783 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
14784 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14785 if (DstVT != MVT::f64)
14786 // This conversion needs to be expanded.
14789 SDValue InVec = Op->getOperand(0);
14791 unsigned NumElts = SrcVT.getVectorNumElements();
14792 EVT SVT = SrcVT.getVectorElementType();
14794 // Widen the vector in input in the case of MVT::v2i32.
14795 // Example: from MVT::v2i32 to MVT::v4i32.
14796 SmallVector<SDValue, 16> Elts;
14797 for (unsigned i = 0, e = NumElts; i != e; ++i)
14798 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
14799 DAG.getIntPtrConstant(i)));
14801 // Explicitly mark the extra elements as Undef.
14802 SDValue Undef = DAG.getUNDEF(SVT);
14803 for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
14804 Elts.push_back(Undef);
14806 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
14807 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
14808 SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
14809 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
14810 DAG.getIntPtrConstant(0));
14813 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
14814 Subtarget->hasMMX() && "Unexpected custom BITCAST");
14815 assert((DstVT == MVT::i64 ||
14816 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
14817 "Unexpected custom BITCAST");
14818 // i64 <=> MMX conversions are Legal.
14819 if (SrcVT==MVT::i64 && DstVT.isVector())
14821 if (DstVT==MVT::i64 && SrcVT.isVector())
14823 // MMX <=> MMX conversions are Legal.
14824 if (SrcVT.isVector() && DstVT.isVector())
14826 // All other conversions need to be expanded.
14830 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
14831 SDNode *Node = Op.getNode();
14833 EVT T = Node->getValueType(0);
14834 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
14835 DAG.getConstant(0, T), Node->getOperand(2));
14836 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
14837 cast<AtomicSDNode>(Node)->getMemoryVT(),
14838 Node->getOperand(0),
14839 Node->getOperand(1), negOp,
14840 cast<AtomicSDNode>(Node)->getMemOperand(),
14841 cast<AtomicSDNode>(Node)->getOrdering(),
14842 cast<AtomicSDNode>(Node)->getSynchScope());
14845 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
14846 SDNode *Node = Op.getNode();
14848 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14850 // Convert seq_cst store -> xchg
14851 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
14852 // FIXME: On 32-bit, store -> fist or movq would be more efficient
14853 // (The only way to get a 16-byte store is cmpxchg16b)
14854 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
14855 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
14856 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14857 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
14858 cast<AtomicSDNode>(Node)->getMemoryVT(),
14859 Node->getOperand(0),
14860 Node->getOperand(1), Node->getOperand(2),
14861 cast<AtomicSDNode>(Node)->getMemOperand(),
14862 cast<AtomicSDNode>(Node)->getOrdering(),
14863 cast<AtomicSDNode>(Node)->getSynchScope());
14864 return Swap.getValue(1);
14866 // Other atomic stores have a simple pattern.
14870 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
14871 EVT VT = Op.getNode()->getSimpleValueType(0);
14873 // Let legalize expand this if it isn't a legal type yet.
14874 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14877 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14880 bool ExtraOp = false;
14881 switch (Op.getOpcode()) {
14882 default: llvm_unreachable("Invalid code");
14883 case ISD::ADDC: Opc = X86ISD::ADD; break;
14884 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
14885 case ISD::SUBC: Opc = X86ISD::SUB; break;
14886 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
14890 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14892 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14893 Op.getOperand(1), Op.getOperand(2));
14896 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
14897 SelectionDAG &DAG) {
14898 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
14900 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
14901 // which returns the values as { float, float } (in XMM0) or
14902 // { double, double } (which is returned in XMM0, XMM1).
14904 SDValue Arg = Op.getOperand(0);
14905 EVT ArgVT = Arg.getValueType();
14906 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14908 TargetLowering::ArgListTy Args;
14909 TargetLowering::ArgListEntry Entry;
14913 Entry.isSExt = false;
14914 Entry.isZExt = false;
14915 Args.push_back(Entry);
14917 bool isF64 = ArgVT == MVT::f64;
14918 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
14919 // the small struct {f32, f32} is returned in (eax, edx). For f64,
14920 // the results are returned via SRet in memory.
14921 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
14922 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14923 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
14925 Type *RetTy = isF64
14926 ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
14927 : (Type*)VectorType::get(ArgTy, 4);
14929 TargetLowering::CallLoweringInfo CLI(DAG);
14930 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
14931 .setCallee(CallingConv::C, RetTy, Callee, &Args, 0);
14933 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
14936 // Returned in xmm0 and xmm1.
14937 return CallResult.first;
14939 // Returned in bits 0:31 and 32:64 xmm0.
14940 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14941 CallResult.first, DAG.getIntPtrConstant(0));
14942 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14943 CallResult.first, DAG.getIntPtrConstant(1));
14944 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
14945 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
14948 /// LowerOperation - Provide custom lowering hooks for some operations.
14950 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
14951 switch (Op.getOpcode()) {
14952 default: llvm_unreachable("Should not custom lower this!");
14953 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
14954 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
14955 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
14956 return LowerCMP_SWAP(Op, Subtarget, DAG);
14957 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
14958 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
14959 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
14960 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
14961 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
14962 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
14963 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
14964 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
14965 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
14966 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
14967 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
14968 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
14969 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
14970 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
14971 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
14972 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
14973 case ISD::SHL_PARTS:
14974 case ISD::SRA_PARTS:
14975 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
14976 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
14977 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
14978 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
14979 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
14980 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
14981 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
14982 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
14983 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
14984 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
14985 case ISD::FABS: return LowerFABS(Op, DAG);
14986 case ISD::FNEG: return LowerFNEG(Op, DAG);
14987 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
14988 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
14989 case ISD::SETCC: return LowerSETCC(Op, DAG);
14990 case ISD::SELECT: return LowerSELECT(Op, DAG);
14991 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
14992 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
14993 case ISD::VASTART: return LowerVASTART(Op, DAG);
14994 case ISD::VAARG: return LowerVAARG(Op, DAG);
14995 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
14996 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
14997 case ISD::INTRINSIC_VOID:
14998 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
14999 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
15000 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
15001 case ISD::FRAME_TO_ARGS_OFFSET:
15002 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
15003 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
15004 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
15005 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
15006 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
15007 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
15008 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
15009 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
15010 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
15011 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
15012 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
15013 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
15014 case ISD::UMUL_LOHI:
15015 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
15018 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
15024 case ISD::UMULO: return LowerXALUO(Op, DAG);
15025 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
15026 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
15030 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
15031 case ISD::ADD: return LowerADD(Op, DAG);
15032 case ISD::SUB: return LowerSUB(Op, DAG);
15033 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
15037 static void ReplaceATOMIC_LOAD(SDNode *Node,
15038 SmallVectorImpl<SDValue> &Results,
15039 SelectionDAG &DAG) {
15041 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
15043 // Convert wide load -> cmpxchg8b/cmpxchg16b
15044 // FIXME: On 32-bit, load -> fild or movq would be more efficient
15045 // (The only way to get a 16-byte load is cmpxchg16b)
15046 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
15047 SDValue Zero = DAG.getConstant(0, VT);
15048 SDVTList VTs = DAG.getVTList(VT, MVT::i1, MVT::Other);
15050 DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, VT, VTs,
15051 Node->getOperand(0), Node->getOperand(1), Zero, Zero,
15052 cast<AtomicSDNode>(Node)->getMemOperand(),
15053 cast<AtomicSDNode>(Node)->getOrdering(),
15054 cast<AtomicSDNode>(Node)->getOrdering(),
15055 cast<AtomicSDNode>(Node)->getSynchScope());
15056 Results.push_back(Swap.getValue(0));
15057 Results.push_back(Swap.getValue(2));
15061 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
15062 SelectionDAG &DAG, unsigned NewOp) {
15064 assert (Node->getValueType(0) == MVT::i64 &&
15065 "Only know how to expand i64 atomics");
15067 SDValue Chain = Node->getOperand(0);
15068 SDValue In1 = Node->getOperand(1);
15069 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
15070 Node->getOperand(2), DAG.getIntPtrConstant(0));
15071 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
15072 Node->getOperand(2), DAG.getIntPtrConstant(1));
15073 SDValue Ops[] = { Chain, In1, In2L, In2H };
15074 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
15076 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, MVT::i64,
15077 cast<MemSDNode>(Node)->getMemOperand());
15078 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
15079 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF));
15080 Results.push_back(Result.getValue(2));
15083 /// ReplaceNodeResults - Replace a node with an illegal result type
15084 /// with a new node built out of custom code.
15085 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
15086 SmallVectorImpl<SDValue>&Results,
15087 SelectionDAG &DAG) const {
15089 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15090 switch (N->getOpcode()) {
15092 llvm_unreachable("Do not know how to custom type legalize this operation!");
15093 case ISD::SIGN_EXTEND_INREG:
15098 // We don't want to expand or promote these.
15105 case ISD::UDIVREM: {
15106 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
15107 Results.push_back(V);
15110 case ISD::FP_TO_SINT:
15111 case ISD::FP_TO_UINT: {
15112 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
15114 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
15117 std::pair<SDValue,SDValue> Vals =
15118 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
15119 SDValue FIST = Vals.first, StackSlot = Vals.second;
15120 if (FIST.getNode()) {
15121 EVT VT = N->getValueType(0);
15122 // Return a load from the stack slot.
15123 if (StackSlot.getNode())
15124 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
15125 MachinePointerInfo(),
15126 false, false, false, 0));
15128 Results.push_back(FIST);
15132 case ISD::UINT_TO_FP: {
15133 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
15134 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
15135 N->getValueType(0) != MVT::v2f32)
15137 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
15139 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
15141 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
15142 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
15143 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
15144 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
15145 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
15146 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
15149 case ISD::FP_ROUND: {
15150 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
15152 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
15153 Results.push_back(V);
15156 case ISD::INTRINSIC_W_CHAIN: {
15157 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
15159 default : llvm_unreachable("Do not know how to custom type "
15160 "legalize this intrinsic operation!");
15161 case Intrinsic::x86_rdtsc:
15162 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
15164 case Intrinsic::x86_rdtscp:
15165 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
15169 case ISD::READCYCLECOUNTER: {
15170 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
15173 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
15174 EVT T = N->getValueType(0);
15175 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
15176 bool Regs64bit = T == MVT::i128;
15177 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
15178 SDValue cpInL, cpInH;
15179 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
15180 DAG.getConstant(0, HalfT));
15181 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
15182 DAG.getConstant(1, HalfT));
15183 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
15184 Regs64bit ? X86::RAX : X86::EAX,
15186 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
15187 Regs64bit ? X86::RDX : X86::EDX,
15188 cpInH, cpInL.getValue(1));
15189 SDValue swapInL, swapInH;
15190 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
15191 DAG.getConstant(0, HalfT));
15192 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
15193 DAG.getConstant(1, HalfT));
15194 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
15195 Regs64bit ? X86::RBX : X86::EBX,
15196 swapInL, cpInH.getValue(1));
15197 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
15198 Regs64bit ? X86::RCX : X86::ECX,
15199 swapInH, swapInL.getValue(1));
15200 SDValue Ops[] = { swapInH.getValue(0),
15202 swapInH.getValue(1) };
15203 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15204 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
15205 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
15206 X86ISD::LCMPXCHG8_DAG;
15207 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
15208 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
15209 Regs64bit ? X86::RAX : X86::EAX,
15210 HalfT, Result.getValue(1));
15211 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
15212 Regs64bit ? X86::RDX : X86::EDX,
15213 HalfT, cpOutL.getValue(2));
15214 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
15216 SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
15217 MVT::i32, cpOutH.getValue(2));
15219 DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15220 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
15221 Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
15223 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
15224 Results.push_back(Success);
15225 Results.push_back(EFLAGS.getValue(1));
15228 case ISD::ATOMIC_LOAD_ADD:
15229 case ISD::ATOMIC_LOAD_AND:
15230 case ISD::ATOMIC_LOAD_NAND:
15231 case ISD::ATOMIC_LOAD_OR:
15232 case ISD::ATOMIC_LOAD_SUB:
15233 case ISD::ATOMIC_LOAD_XOR:
15234 case ISD::ATOMIC_LOAD_MAX:
15235 case ISD::ATOMIC_LOAD_MIN:
15236 case ISD::ATOMIC_LOAD_UMAX:
15237 case ISD::ATOMIC_LOAD_UMIN:
15238 case ISD::ATOMIC_SWAP: {
15240 switch (N->getOpcode()) {
15241 default: llvm_unreachable("Unexpected opcode");
15242 case ISD::ATOMIC_LOAD_ADD:
15243 Opc = X86ISD::ATOMADD64_DAG;
15245 case ISD::ATOMIC_LOAD_AND:
15246 Opc = X86ISD::ATOMAND64_DAG;
15248 case ISD::ATOMIC_LOAD_NAND:
15249 Opc = X86ISD::ATOMNAND64_DAG;
15251 case ISD::ATOMIC_LOAD_OR:
15252 Opc = X86ISD::ATOMOR64_DAG;
15254 case ISD::ATOMIC_LOAD_SUB:
15255 Opc = X86ISD::ATOMSUB64_DAG;
15257 case ISD::ATOMIC_LOAD_XOR:
15258 Opc = X86ISD::ATOMXOR64_DAG;
15260 case ISD::ATOMIC_LOAD_MAX:
15261 Opc = X86ISD::ATOMMAX64_DAG;
15263 case ISD::ATOMIC_LOAD_MIN:
15264 Opc = X86ISD::ATOMMIN64_DAG;
15266 case ISD::ATOMIC_LOAD_UMAX:
15267 Opc = X86ISD::ATOMUMAX64_DAG;
15269 case ISD::ATOMIC_LOAD_UMIN:
15270 Opc = X86ISD::ATOMUMIN64_DAG;
15272 case ISD::ATOMIC_SWAP:
15273 Opc = X86ISD::ATOMSWAP64_DAG;
15276 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
15279 case ISD::ATOMIC_LOAD: {
15280 ReplaceATOMIC_LOAD(N, Results, DAG);
15283 case ISD::BITCAST: {
15284 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
15285 EVT DstVT = N->getValueType(0);
15286 EVT SrcVT = N->getOperand(0)->getValueType(0);
15288 if (SrcVT != MVT::f64 ||
15289 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
15292 unsigned NumElts = DstVT.getVectorNumElements();
15293 EVT SVT = DstVT.getVectorElementType();
15294 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
15295 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
15296 MVT::v2f64, N->getOperand(0));
15297 SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
15299 SmallVector<SDValue, 8> Elts;
15300 for (unsigned i = 0, e = NumElts; i != e; ++i)
15301 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
15302 ToVecInt, DAG.getIntPtrConstant(i)));
15304 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
15309 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
15311 default: return nullptr;
15312 case X86ISD::BSF: return "X86ISD::BSF";
15313 case X86ISD::BSR: return "X86ISD::BSR";
15314 case X86ISD::SHLD: return "X86ISD::SHLD";
15315 case X86ISD::SHRD: return "X86ISD::SHRD";
15316 case X86ISD::FAND: return "X86ISD::FAND";
15317 case X86ISD::FANDN: return "X86ISD::FANDN";
15318 case X86ISD::FOR: return "X86ISD::FOR";
15319 case X86ISD::FXOR: return "X86ISD::FXOR";
15320 case X86ISD::FSRL: return "X86ISD::FSRL";
15321 case X86ISD::FILD: return "X86ISD::FILD";
15322 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
15323 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
15324 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
15325 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
15326 case X86ISD::FLD: return "X86ISD::FLD";
15327 case X86ISD::FST: return "X86ISD::FST";
15328 case X86ISD::CALL: return "X86ISD::CALL";
15329 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
15330 case X86ISD::RDTSCP_DAG: return "X86ISD::RDTSCP_DAG";
15331 case X86ISD::BT: return "X86ISD::BT";
15332 case X86ISD::CMP: return "X86ISD::CMP";
15333 case X86ISD::COMI: return "X86ISD::COMI";
15334 case X86ISD::UCOMI: return "X86ISD::UCOMI";
15335 case X86ISD::CMPM: return "X86ISD::CMPM";
15336 case X86ISD::CMPMU: return "X86ISD::CMPMU";
15337 case X86ISD::SETCC: return "X86ISD::SETCC";
15338 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
15339 case X86ISD::FSETCC: return "X86ISD::FSETCC";
15340 case X86ISD::CMOV: return "X86ISD::CMOV";
15341 case X86ISD::BRCOND: return "X86ISD::BRCOND";
15342 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
15343 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
15344 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
15345 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
15346 case X86ISD::Wrapper: return "X86ISD::Wrapper";
15347 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
15348 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
15349 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
15350 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
15351 case X86ISD::PINSRB: return "X86ISD::PINSRB";
15352 case X86ISD::PINSRW: return "X86ISD::PINSRW";
15353 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
15354 case X86ISD::ANDNP: return "X86ISD::ANDNP";
15355 case X86ISD::PSIGN: return "X86ISD::PSIGN";
15356 case X86ISD::BLENDV: return "X86ISD::BLENDV";
15357 case X86ISD::BLENDI: return "X86ISD::BLENDI";
15358 case X86ISD::SUBUS: return "X86ISD::SUBUS";
15359 case X86ISD::HADD: return "X86ISD::HADD";
15360 case X86ISD::HSUB: return "X86ISD::HSUB";
15361 case X86ISD::FHADD: return "X86ISD::FHADD";
15362 case X86ISD::FHSUB: return "X86ISD::FHSUB";
15363 case X86ISD::UMAX: return "X86ISD::UMAX";
15364 case X86ISD::UMIN: return "X86ISD::UMIN";
15365 case X86ISD::SMAX: return "X86ISD::SMAX";
15366 case X86ISD::SMIN: return "X86ISD::SMIN";
15367 case X86ISD::FMAX: return "X86ISD::FMAX";
15368 case X86ISD::FMIN: return "X86ISD::FMIN";
15369 case X86ISD::FMAXC: return "X86ISD::FMAXC";
15370 case X86ISD::FMINC: return "X86ISD::FMINC";
15371 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
15372 case X86ISD::FRCP: return "X86ISD::FRCP";
15373 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
15374 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
15375 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
15376 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
15377 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
15378 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
15379 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
15380 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
15381 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
15382 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
15383 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
15384 case X86ISD::LCMPXCHG16_DAG: return "X86ISD::LCMPXCHG16_DAG";
15385 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
15386 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
15387 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
15388 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
15389 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
15390 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
15391 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
15392 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
15393 case X86ISD::VZEXT: return "X86ISD::VZEXT";
15394 case X86ISD::VSEXT: return "X86ISD::VSEXT";
15395 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
15396 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
15397 case X86ISD::VINSERT: return "X86ISD::VINSERT";
15398 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
15399 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
15400 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
15401 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
15402 case X86ISD::VSHL: return "X86ISD::VSHL";
15403 case X86ISD::VSRL: return "X86ISD::VSRL";
15404 case X86ISD::VSRA: return "X86ISD::VSRA";
15405 case X86ISD::VSHLI: return "X86ISD::VSHLI";
15406 case X86ISD::VSRLI: return "X86ISD::VSRLI";
15407 case X86ISD::VSRAI: return "X86ISD::VSRAI";
15408 case X86ISD::CMPP: return "X86ISD::CMPP";
15409 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
15410 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
15411 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
15412 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
15413 case X86ISD::ADD: return "X86ISD::ADD";
15414 case X86ISD::SUB: return "X86ISD::SUB";
15415 case X86ISD::ADC: return "X86ISD::ADC";
15416 case X86ISD::SBB: return "X86ISD::SBB";
15417 case X86ISD::SMUL: return "X86ISD::SMUL";
15418 case X86ISD::UMUL: return "X86ISD::UMUL";
15419 case X86ISD::INC: return "X86ISD::INC";
15420 case X86ISD::DEC: return "X86ISD::DEC";
15421 case X86ISD::OR: return "X86ISD::OR";
15422 case X86ISD::XOR: return "X86ISD::XOR";
15423 case X86ISD::AND: return "X86ISD::AND";
15424 case X86ISD::BEXTR: return "X86ISD::BEXTR";
15425 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
15426 case X86ISD::PTEST: return "X86ISD::PTEST";
15427 case X86ISD::TESTP: return "X86ISD::TESTP";
15428 case X86ISD::TESTM: return "X86ISD::TESTM";
15429 case X86ISD::TESTNM: return "X86ISD::TESTNM";
15430 case X86ISD::KORTEST: return "X86ISD::KORTEST";
15431 case X86ISD::PACKSS: return "X86ISD::PACKSS";
15432 case X86ISD::PACKUS: return "X86ISD::PACKUS";
15433 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
15434 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
15435 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
15436 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
15437 case X86ISD::SHUFP: return "X86ISD::SHUFP";
15438 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
15439 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
15440 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
15441 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
15442 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
15443 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
15444 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
15445 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
15446 case X86ISD::MOVSD: return "X86ISD::MOVSD";
15447 case X86ISD::MOVSS: return "X86ISD::MOVSS";
15448 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
15449 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
15450 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
15451 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
15452 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
15453 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
15454 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
15455 case X86ISD::VPERMV: return "X86ISD::VPERMV";
15456 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
15457 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
15458 case X86ISD::VPERMI: return "X86ISD::VPERMI";
15459 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
15460 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
15461 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
15462 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
15463 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
15464 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
15465 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
15466 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
15467 case X86ISD::SAHF: return "X86ISD::SAHF";
15468 case X86ISD::RDRAND: return "X86ISD::RDRAND";
15469 case X86ISD::RDSEED: return "X86ISD::RDSEED";
15470 case X86ISD::FMADD: return "X86ISD::FMADD";
15471 case X86ISD::FMSUB: return "X86ISD::FMSUB";
15472 case X86ISD::FNMADD: return "X86ISD::FNMADD";
15473 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
15474 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
15475 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
15476 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
15477 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
15478 case X86ISD::XTEST: return "X86ISD::XTEST";
15482 // isLegalAddressingMode - Return true if the addressing mode represented
15483 // by AM is legal for this target, for a load/store of the specified type.
15484 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
15486 // X86 supports extremely general addressing modes.
15487 CodeModel::Model M = getTargetMachine().getCodeModel();
15488 Reloc::Model R = getTargetMachine().getRelocationModel();
15490 // X86 allows a sign-extended 32-bit immediate field as a displacement.
15491 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
15496 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
15498 // If a reference to this global requires an extra load, we can't fold it.
15499 if (isGlobalStubReference(GVFlags))
15502 // If BaseGV requires a register for the PIC base, we cannot also have a
15503 // BaseReg specified.
15504 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
15507 // If lower 4G is not available, then we must use rip-relative addressing.
15508 if ((M != CodeModel::Small || R != Reloc::Static) &&
15509 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
15513 switch (AM.Scale) {
15519 // These scales always work.
15524 // These scales are formed with basereg+scalereg. Only accept if there is
15529 default: // Other stuff never works.
15536 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
15537 unsigned Bits = Ty->getScalarSizeInBits();
15539 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
15540 // particularly cheaper than those without.
15544 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
15545 // variable shifts just as cheap as scalar ones.
15546 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
15549 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
15550 // fully general vector.
15554 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
15555 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15557 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
15558 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
15559 return NumBits1 > NumBits2;
15562 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
15563 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15566 if (!isTypeLegal(EVT::getEVT(Ty1)))
15569 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
15571 // Assuming the caller doesn't have a zeroext or signext return parameter,
15572 // truncation all the way down to i1 is valid.
15576 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
15577 return isInt<32>(Imm);
15580 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
15581 // Can also use sub to handle negated immediates.
15582 return isInt<32>(Imm);
15585 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
15586 if (!VT1.isInteger() || !VT2.isInteger())
15588 unsigned NumBits1 = VT1.getSizeInBits();
15589 unsigned NumBits2 = VT2.getSizeInBits();
15590 return NumBits1 > NumBits2;
15593 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
15594 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
15595 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
15598 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
15599 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
15600 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
15603 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
15604 EVT VT1 = Val.getValueType();
15605 if (isZExtFree(VT1, VT2))
15608 if (Val.getOpcode() != ISD::LOAD)
15611 if (!VT1.isSimple() || !VT1.isInteger() ||
15612 !VT2.isSimple() || !VT2.isInteger())
15615 switch (VT1.getSimpleVT().SimpleTy) {
15620 // X86 has 8, 16, and 32-bit zero-extending loads.
15628 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
15629 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
15632 VT = VT.getScalarType();
15634 if (!VT.isSimple())
15637 switch (VT.getSimpleVT().SimpleTy) {
15648 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
15649 // i16 instructions are longer (0x66 prefix) and potentially slower.
15650 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
15653 /// isShuffleMaskLegal - Targets can use this to indicate that they only
15654 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
15655 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
15656 /// are assumed to be legal.
15658 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
15660 if (!VT.isSimple())
15663 MVT SVT = VT.getSimpleVT();
15665 // Very little shuffling can be done for 64-bit vectors right now.
15666 if (VT.getSizeInBits() == 64)
15669 // If this is a single-input shuffle with no 128 bit lane crossings we can
15670 // lower it into pshufb.
15671 if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
15672 (SVT.is256BitVector() && Subtarget->hasInt256())) {
15673 bool isLegal = true;
15674 for (unsigned I = 0, E = M.size(); I != E; ++I) {
15675 if (M[I] >= (int)SVT.getVectorNumElements() ||
15676 ShuffleCrosses128bitLane(SVT, I, M[I])) {
15685 // FIXME: blends, shifts.
15686 return (SVT.getVectorNumElements() == 2 ||
15687 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
15688 isMOVLMask(M, SVT) ||
15689 isSHUFPMask(M, SVT) ||
15690 isPSHUFDMask(M, SVT) ||
15691 isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
15692 isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
15693 isPALIGNRMask(M, SVT, Subtarget) ||
15694 isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
15695 isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
15696 isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
15697 isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
15698 isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
15702 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
15704 if (!VT.isSimple())
15707 MVT SVT = VT.getSimpleVT();
15708 unsigned NumElts = SVT.getVectorNumElements();
15709 // FIXME: This collection of masks seems suspect.
15712 if (NumElts == 4 && SVT.is128BitVector()) {
15713 return (isMOVLMask(Mask, SVT) ||
15714 isCommutedMOVLMask(Mask, SVT, true) ||
15715 isSHUFPMask(Mask, SVT) ||
15716 isSHUFPMask(Mask, SVT, /* Commuted */ true));
15721 //===----------------------------------------------------------------------===//
15722 // X86 Scheduler Hooks
15723 //===----------------------------------------------------------------------===//
15725 /// Utility function to emit xbegin specifying the start of an RTM region.
15726 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
15727 const TargetInstrInfo *TII) {
15728 DebugLoc DL = MI->getDebugLoc();
15730 const BasicBlock *BB = MBB->getBasicBlock();
15731 MachineFunction::iterator I = MBB;
15734 // For the v = xbegin(), we generate
15745 MachineBasicBlock *thisMBB = MBB;
15746 MachineFunction *MF = MBB->getParent();
15747 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15748 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15749 MF->insert(I, mainMBB);
15750 MF->insert(I, sinkMBB);
15752 // Transfer the remainder of BB and its successor edges to sinkMBB.
15753 sinkMBB->splice(sinkMBB->begin(), MBB,
15754 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15755 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15759 // # fallthrough to mainMBB
15760 // # abortion to sinkMBB
15761 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
15762 thisMBB->addSuccessor(mainMBB);
15763 thisMBB->addSuccessor(sinkMBB);
15767 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
15768 mainMBB->addSuccessor(sinkMBB);
15771 // EAX is live into the sinkMBB
15772 sinkMBB->addLiveIn(X86::EAX);
15773 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15774 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15777 MI->eraseFromParent();
15781 // Get CMPXCHG opcode for the specified data type.
15782 static unsigned getCmpXChgOpcode(EVT VT) {
15783 switch (VT.getSimpleVT().SimpleTy) {
15784 case MVT::i8: return X86::LCMPXCHG8;
15785 case MVT::i16: return X86::LCMPXCHG16;
15786 case MVT::i32: return X86::LCMPXCHG32;
15787 case MVT::i64: return X86::LCMPXCHG64;
15791 llvm_unreachable("Invalid operand size!");
15794 // Get LOAD opcode for the specified data type.
15795 static unsigned getLoadOpcode(EVT VT) {
15796 switch (VT.getSimpleVT().SimpleTy) {
15797 case MVT::i8: return X86::MOV8rm;
15798 case MVT::i16: return X86::MOV16rm;
15799 case MVT::i32: return X86::MOV32rm;
15800 case MVT::i64: return X86::MOV64rm;
15804 llvm_unreachable("Invalid operand size!");
15807 // Get opcode of the non-atomic one from the specified atomic instruction.
15808 static unsigned getNonAtomicOpcode(unsigned Opc) {
15810 case X86::ATOMAND8: return X86::AND8rr;
15811 case X86::ATOMAND16: return X86::AND16rr;
15812 case X86::ATOMAND32: return X86::AND32rr;
15813 case X86::ATOMAND64: return X86::AND64rr;
15814 case X86::ATOMOR8: return X86::OR8rr;
15815 case X86::ATOMOR16: return X86::OR16rr;
15816 case X86::ATOMOR32: return X86::OR32rr;
15817 case X86::ATOMOR64: return X86::OR64rr;
15818 case X86::ATOMXOR8: return X86::XOR8rr;
15819 case X86::ATOMXOR16: return X86::XOR16rr;
15820 case X86::ATOMXOR32: return X86::XOR32rr;
15821 case X86::ATOMXOR64: return X86::XOR64rr;
15823 llvm_unreachable("Unhandled atomic-load-op opcode!");
15826 // Get opcode of the non-atomic one from the specified atomic instruction with
15828 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
15829 unsigned &ExtraOpc) {
15831 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr;
15832 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr;
15833 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr;
15834 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr;
15835 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr;
15836 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
15837 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
15838 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
15839 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr;
15840 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
15841 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
15842 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
15843 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr;
15844 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
15845 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
15846 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
15847 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr;
15848 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
15849 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
15850 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
15852 llvm_unreachable("Unhandled atomic-load-op opcode!");
15855 // Get opcode of the non-atomic one from the specified atomic instruction for
15856 // 64-bit data type on 32-bit target.
15857 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
15859 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr;
15860 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr;
15861 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr;
15862 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr;
15863 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr;
15864 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
15865 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr;
15866 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr;
15867 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr;
15868 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr;
15870 llvm_unreachable("Unhandled atomic-load-op opcode!");
15873 // Get opcode of the non-atomic one from the specified atomic instruction for
15874 // 64-bit data type on 32-bit target with extra opcode.
15875 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
15877 unsigned &ExtraOpc) {
15879 case X86::ATOMNAND6432:
15880 ExtraOpc = X86::NOT32r;
15881 HiOpc = X86::AND32rr;
15882 return X86::AND32rr;
15884 llvm_unreachable("Unhandled atomic-load-op opcode!");
15887 // Get pseudo CMOV opcode from the specified data type.
15888 static unsigned getPseudoCMOVOpc(EVT VT) {
15889 switch (VT.getSimpleVT().SimpleTy) {
15890 case MVT::i8: return X86::CMOV_GR8;
15891 case MVT::i16: return X86::CMOV_GR16;
15892 case MVT::i32: return X86::CMOV_GR32;
15896 llvm_unreachable("Unknown CMOV opcode!");
15899 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
15900 // They will be translated into a spin-loop or compare-exchange loop from
15903 // dst = atomic-fetch-op MI.addr, MI.val
15909 // t1 = LOAD MI.addr
15911 // t4 = phi(t1, t3 / loop)
15912 // t2 = OP MI.val, t4
15914 // LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
15920 MachineBasicBlock *
15921 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
15922 MachineBasicBlock *MBB) const {
15923 MachineFunction *MF = MBB->getParent();
15924 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
15925 DebugLoc DL = MI->getDebugLoc();
15927 MachineRegisterInfo &MRI = MF->getRegInfo();
15929 const BasicBlock *BB = MBB->getBasicBlock();
15930 MachineFunction::iterator I = MBB;
15933 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
15934 "Unexpected number of operands");
15936 assert(MI->hasOneMemOperand() &&
15937 "Expected atomic-load-op to have one memoperand");
15939 // Memory Reference
15940 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15941 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15943 unsigned DstReg, SrcReg;
15944 unsigned MemOpndSlot;
15946 unsigned CurOp = 0;
15948 DstReg = MI->getOperand(CurOp++).getReg();
15949 MemOpndSlot = CurOp;
15950 CurOp += X86::AddrNumOperands;
15951 SrcReg = MI->getOperand(CurOp++).getReg();
15953 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15954 MVT::SimpleValueType VT = *RC->vt_begin();
15955 unsigned t1 = MRI.createVirtualRegister(RC);
15956 unsigned t2 = MRI.createVirtualRegister(RC);
15957 unsigned t3 = MRI.createVirtualRegister(RC);
15958 unsigned t4 = MRI.createVirtualRegister(RC);
15959 unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
15961 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
15962 unsigned LOADOpc = getLoadOpcode(VT);
15964 // For the atomic load-arith operator, we generate
15967 // t1 = LOAD [MI.addr]
15969 // t4 = phi(t1 / thisMBB, t3 / mainMBB)
15970 // t1 = OP MI.val, EAX
15972 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
15978 MachineBasicBlock *thisMBB = MBB;
15979 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15980 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15981 MF->insert(I, mainMBB);
15982 MF->insert(I, sinkMBB);
15984 MachineInstrBuilder MIB;
15986 // Transfer the remainder of BB and its successor edges to sinkMBB.
15987 sinkMBB->splice(sinkMBB->begin(), MBB,
15988 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15989 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15992 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
15993 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15994 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15996 NewMO.setIsKill(false);
15997 MIB.addOperand(NewMO);
15999 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
16000 unsigned flags = (*MMOI)->getFlags();
16001 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
16002 MachineMemOperand *MMO =
16003 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
16004 (*MMOI)->getSize(),
16005 (*MMOI)->getBaseAlignment(),
16006 (*MMOI)->getTBAAInfo(),
16007 (*MMOI)->getRanges());
16008 MIB.addMemOperand(MMO);
16011 thisMBB->addSuccessor(mainMBB);
16014 MachineBasicBlock *origMainMBB = mainMBB;
16017 MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
16018 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
16020 unsigned Opc = MI->getOpcode();
16023 llvm_unreachable("Unhandled atomic-load-op opcode!");
16024 case X86::ATOMAND8:
16025 case X86::ATOMAND16:
16026 case X86::ATOMAND32:
16027 case X86::ATOMAND64:
16029 case X86::ATOMOR16:
16030 case X86::ATOMOR32:
16031 case X86::ATOMOR64:
16032 case X86::ATOMXOR8:
16033 case X86::ATOMXOR16:
16034 case X86::ATOMXOR32:
16035 case X86::ATOMXOR64: {
16036 unsigned ARITHOpc = getNonAtomicOpcode(Opc);
16037 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
16041 case X86::ATOMNAND8:
16042 case X86::ATOMNAND16:
16043 case X86::ATOMNAND32:
16044 case X86::ATOMNAND64: {
16045 unsigned Tmp = MRI.createVirtualRegister(RC);
16047 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
16048 BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
16050 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
16053 case X86::ATOMMAX8:
16054 case X86::ATOMMAX16:
16055 case X86::ATOMMAX32:
16056 case X86::ATOMMAX64:
16057 case X86::ATOMMIN8:
16058 case X86::ATOMMIN16:
16059 case X86::ATOMMIN32:
16060 case X86::ATOMMIN64:
16061 case X86::ATOMUMAX8:
16062 case X86::ATOMUMAX16:
16063 case X86::ATOMUMAX32:
16064 case X86::ATOMUMAX64:
16065 case X86::ATOMUMIN8:
16066 case X86::ATOMUMIN16:
16067 case X86::ATOMUMIN32:
16068 case X86::ATOMUMIN64: {
16070 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
16072 BuildMI(mainMBB, DL, TII->get(CMPOpc))
16076 if (Subtarget->hasCMov()) {
16077 if (VT != MVT::i8) {
16079 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
16083 // Promote i8 to i32 to use CMOV32
16084 const TargetRegisterInfo* TRI = MF->getTarget().getRegisterInfo();
16085 const TargetRegisterClass *RC32 =
16086 TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
16087 unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
16088 unsigned AccReg32 = MRI.createVirtualRegister(RC32);
16089 unsigned Tmp = MRI.createVirtualRegister(RC32);
16091 unsigned Undef = MRI.createVirtualRegister(RC32);
16092 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
16094 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
16097 .addImm(X86::sub_8bit);
16098 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
16101 .addImm(X86::sub_8bit);
16103 BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
16107 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
16108 .addReg(Tmp, 0, X86::sub_8bit);
16111 // Use pseudo select and lower them.
16112 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
16113 "Invalid atomic-load-op transformation!");
16114 unsigned SelOpc = getPseudoCMOVOpc(VT);
16115 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
16116 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
16117 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
16118 .addReg(SrcReg).addReg(t4)
16120 mainMBB = EmitLoweredSelect(MIB, mainMBB);
16121 // Replace the original PHI node as mainMBB is changed after CMOV
16123 BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
16124 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
16125 Phi->eraseFromParent();
16131 // Copy PhyReg back from virtual register.
16132 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
16135 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
16136 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16137 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
16139 NewMO.setIsKill(false);
16140 MIB.addOperand(NewMO);
16143 MIB.setMemRefs(MMOBegin, MMOEnd);
16145 // Copy PhyReg back to virtual register.
16146 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
16149 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
16151 mainMBB->addSuccessor(origMainMBB);
16152 mainMBB->addSuccessor(sinkMBB);
16155 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16156 TII->get(TargetOpcode::COPY), DstReg)
16159 MI->eraseFromParent();
16163 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
16164 // instructions. They will be translated into a spin-loop or compare-exchange
16168 // dst = atomic-fetch-op MI.addr, MI.val
16174 // t1L = LOAD [MI.addr + 0]
16175 // t1H = LOAD [MI.addr + 4]
16177 // t4L = phi(t1L, t3L / loop)
16178 // t4H = phi(t1H, t3H / loop)
16179 // t2L = OP MI.val.lo, t4L
16180 // t2H = OP MI.val.hi, t4H
16185 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
16193 MachineBasicBlock *
16194 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
16195 MachineBasicBlock *MBB) const {
16196 MachineFunction *MF = MBB->getParent();
16197 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
16198 DebugLoc DL = MI->getDebugLoc();
16200 MachineRegisterInfo &MRI = MF->getRegInfo();
16202 const BasicBlock *BB = MBB->getBasicBlock();
16203 MachineFunction::iterator I = MBB;
16206 assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
16207 "Unexpected number of operands");
16209 assert(MI->hasOneMemOperand() &&
16210 "Expected atomic-load-op32 to have one memoperand");
16212 // Memory Reference
16213 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16214 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16216 unsigned DstLoReg, DstHiReg;
16217 unsigned SrcLoReg, SrcHiReg;
16218 unsigned MemOpndSlot;
16220 unsigned CurOp = 0;
16222 DstLoReg = MI->getOperand(CurOp++).getReg();
16223 DstHiReg = MI->getOperand(CurOp++).getReg();
16224 MemOpndSlot = CurOp;
16225 CurOp += X86::AddrNumOperands;
16226 SrcLoReg = MI->getOperand(CurOp++).getReg();
16227 SrcHiReg = MI->getOperand(CurOp++).getReg();
16229 const TargetRegisterClass *RC = &X86::GR32RegClass;
16230 const TargetRegisterClass *RC8 = &X86::GR8RegClass;
16232 unsigned t1L = MRI.createVirtualRegister(RC);
16233 unsigned t1H = MRI.createVirtualRegister(RC);
16234 unsigned t2L = MRI.createVirtualRegister(RC);
16235 unsigned t2H = MRI.createVirtualRegister(RC);
16236 unsigned t3L = MRI.createVirtualRegister(RC);
16237 unsigned t3H = MRI.createVirtualRegister(RC);
16238 unsigned t4L = MRI.createVirtualRegister(RC);
16239 unsigned t4H = MRI.createVirtualRegister(RC);
16241 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
16242 unsigned LOADOpc = X86::MOV32rm;
16244 // For the atomic load-arith operator, we generate
16247 // t1L = LOAD [MI.addr + 0]
16248 // t1H = LOAD [MI.addr + 4]
16250 // t4L = phi(t1L / thisMBB, t3L / mainMBB)
16251 // t4H = phi(t1H / thisMBB, t3H / mainMBB)
16252 // t2L = OP MI.val.lo, t4L
16253 // t2H = OP MI.val.hi, t4H
16256 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
16264 MachineBasicBlock *thisMBB = MBB;
16265 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16266 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16267 MF->insert(I, mainMBB);
16268 MF->insert(I, sinkMBB);
16270 MachineInstrBuilder MIB;
16272 // Transfer the remainder of BB and its successor edges to sinkMBB.
16273 sinkMBB->splice(sinkMBB->begin(), MBB,
16274 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16275 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16279 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
16280 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16281 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
16283 NewMO.setIsKill(false);
16284 MIB.addOperand(NewMO);
16286 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
16287 unsigned flags = (*MMOI)->getFlags();
16288 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
16289 MachineMemOperand *MMO =
16290 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
16291 (*MMOI)->getSize(),
16292 (*MMOI)->getBaseAlignment(),
16293 (*MMOI)->getTBAAInfo(),
16294 (*MMOI)->getRanges());
16295 MIB.addMemOperand(MMO);
16297 MachineInstr *LowMI = MIB;
16300 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
16301 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16302 if (i == X86::AddrDisp) {
16303 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
16305 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
16307 NewMO.setIsKill(false);
16308 MIB.addOperand(NewMO);
16311 MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
16313 thisMBB->addSuccessor(mainMBB);
16316 MachineBasicBlock *origMainMBB = mainMBB;
16319 MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
16320 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
16321 MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
16322 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
16324 unsigned Opc = MI->getOpcode();
16327 llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
16328 case X86::ATOMAND6432:
16329 case X86::ATOMOR6432:
16330 case X86::ATOMXOR6432:
16331 case X86::ATOMADD6432:
16332 case X86::ATOMSUB6432: {
16334 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
16335 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
16337 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
16341 case X86::ATOMNAND6432: {
16342 unsigned HiOpc, NOTOpc;
16343 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
16344 unsigned TmpL = MRI.createVirtualRegister(RC);
16345 unsigned TmpH = MRI.createVirtualRegister(RC);
16346 BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
16348 BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
16350 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
16351 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
16354 case X86::ATOMMAX6432:
16355 case X86::ATOMMIN6432:
16356 case X86::ATOMUMAX6432:
16357 case X86::ATOMUMIN6432: {
16359 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
16360 unsigned cL = MRI.createVirtualRegister(RC8);
16361 unsigned cH = MRI.createVirtualRegister(RC8);
16362 unsigned cL32 = MRI.createVirtualRegister(RC);
16363 unsigned cH32 = MRI.createVirtualRegister(RC);
16364 unsigned cc = MRI.createVirtualRegister(RC);
16365 // cl := cmp src_lo, lo
16366 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
16367 .addReg(SrcLoReg).addReg(t4L);
16368 BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
16369 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
16370 // ch := cmp src_hi, hi
16371 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
16372 .addReg(SrcHiReg).addReg(t4H);
16373 BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
16374 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
16375 // cc := if (src_hi == hi) ? cl : ch;
16376 if (Subtarget->hasCMov()) {
16377 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
16378 .addReg(cH32).addReg(cL32);
16380 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
16381 .addReg(cH32).addReg(cL32)
16382 .addImm(X86::COND_E);
16383 mainMBB = EmitLoweredSelect(MIB, mainMBB);
16385 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
16386 if (Subtarget->hasCMov()) {
16387 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
16388 .addReg(SrcLoReg).addReg(t4L);
16389 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
16390 .addReg(SrcHiReg).addReg(t4H);
16392 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
16393 .addReg(SrcLoReg).addReg(t4L)
16394 .addImm(X86::COND_NE);
16395 mainMBB = EmitLoweredSelect(MIB, mainMBB);
16396 // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
16397 // 2nd CMOV lowering.
16398 mainMBB->addLiveIn(X86::EFLAGS);
16399 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
16400 .addReg(SrcHiReg).addReg(t4H)
16401 .addImm(X86::COND_NE);
16402 mainMBB = EmitLoweredSelect(MIB, mainMBB);
16403 // Replace the original PHI node as mainMBB is changed after CMOV
16405 BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
16406 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
16407 BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
16408 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
16409 PhiL->eraseFromParent();
16410 PhiH->eraseFromParent();
16414 case X86::ATOMSWAP6432: {
16416 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
16417 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
16418 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
16423 // Copy EDX:EAX back from HiReg:LoReg
16424 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
16425 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
16426 // Copy ECX:EBX from t1H:t1L
16427 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
16428 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
16430 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
16431 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16432 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
16434 NewMO.setIsKill(false);
16435 MIB.addOperand(NewMO);
16437 MIB.setMemRefs(MMOBegin, MMOEnd);
16439 // Copy EDX:EAX back to t3H:t3L
16440 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
16441 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
16443 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
16445 mainMBB->addSuccessor(origMainMBB);
16446 mainMBB->addSuccessor(sinkMBB);
16449 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16450 TII->get(TargetOpcode::COPY), DstLoReg)
16452 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16453 TII->get(TargetOpcode::COPY), DstHiReg)
16456 MI->eraseFromParent();
16460 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
16461 // or XMM0_V32I8 in AVX all of this code can be replaced with that
16462 // in the .td file.
16463 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
16464 const TargetInstrInfo *TII) {
16466 switch (MI->getOpcode()) {
16467 default: llvm_unreachable("illegal opcode!");
16468 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
16469 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
16470 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
16471 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
16472 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
16473 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
16474 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
16475 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
16478 DebugLoc dl = MI->getDebugLoc();
16479 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
16481 unsigned NumArgs = MI->getNumOperands();
16482 for (unsigned i = 1; i < NumArgs; ++i) {
16483 MachineOperand &Op = MI->getOperand(i);
16484 if (!(Op.isReg() && Op.isImplicit()))
16485 MIB.addOperand(Op);
16487 if (MI->hasOneMemOperand())
16488 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
16490 BuildMI(*BB, MI, dl,
16491 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16492 .addReg(X86::XMM0);
16494 MI->eraseFromParent();
16498 // FIXME: Custom handling because TableGen doesn't support multiple implicit
16499 // defs in an instruction pattern
16500 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
16501 const TargetInstrInfo *TII) {
16503 switch (MI->getOpcode()) {
16504 default: llvm_unreachable("illegal opcode!");
16505 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
16506 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
16507 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
16508 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
16509 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
16510 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
16511 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
16512 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
16515 DebugLoc dl = MI->getDebugLoc();
16516 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
16518 unsigned NumArgs = MI->getNumOperands(); // remove the results
16519 for (unsigned i = 1; i < NumArgs; ++i) {
16520 MachineOperand &Op = MI->getOperand(i);
16521 if (!(Op.isReg() && Op.isImplicit()))
16522 MIB.addOperand(Op);
16524 if (MI->hasOneMemOperand())
16525 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
16527 BuildMI(*BB, MI, dl,
16528 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16531 MI->eraseFromParent();
16535 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
16536 const TargetInstrInfo *TII,
16537 const X86Subtarget* Subtarget) {
16538 DebugLoc dl = MI->getDebugLoc();
16540 // Address into RAX/EAX, other two args into ECX, EDX.
16541 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
16542 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
16543 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
16544 for (int i = 0; i < X86::AddrNumOperands; ++i)
16545 MIB.addOperand(MI->getOperand(i));
16547 unsigned ValOps = X86::AddrNumOperands;
16548 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
16549 .addReg(MI->getOperand(ValOps).getReg());
16550 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
16551 .addReg(MI->getOperand(ValOps+1).getReg());
16553 // The instruction doesn't actually take any operands though.
16554 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
16556 MI->eraseFromParent(); // The pseudo is gone now.
16560 MachineBasicBlock *
16561 X86TargetLowering::EmitVAARG64WithCustomInserter(
16563 MachineBasicBlock *MBB) const {
16564 // Emit va_arg instruction on X86-64.
16566 // Operands to this pseudo-instruction:
16567 // 0 ) Output : destination address (reg)
16568 // 1-5) Input : va_list address (addr, i64mem)
16569 // 6 ) ArgSize : Size (in bytes) of vararg type
16570 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
16571 // 8 ) Align : Alignment of type
16572 // 9 ) EFLAGS (implicit-def)
16574 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
16575 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
16577 unsigned DestReg = MI->getOperand(0).getReg();
16578 MachineOperand &Base = MI->getOperand(1);
16579 MachineOperand &Scale = MI->getOperand(2);
16580 MachineOperand &Index = MI->getOperand(3);
16581 MachineOperand &Disp = MI->getOperand(4);
16582 MachineOperand &Segment = MI->getOperand(5);
16583 unsigned ArgSize = MI->getOperand(6).getImm();
16584 unsigned ArgMode = MI->getOperand(7).getImm();
16585 unsigned Align = MI->getOperand(8).getImm();
16587 // Memory Reference
16588 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
16589 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16590 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16592 // Machine Information
16593 const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
16594 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
16595 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
16596 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
16597 DebugLoc DL = MI->getDebugLoc();
16599 // struct va_list {
16602 // i64 overflow_area (address)
16603 // i64 reg_save_area (address)
16605 // sizeof(va_list) = 24
16606 // alignment(va_list) = 8
16608 unsigned TotalNumIntRegs = 6;
16609 unsigned TotalNumXMMRegs = 8;
16610 bool UseGPOffset = (ArgMode == 1);
16611 bool UseFPOffset = (ArgMode == 2);
16612 unsigned MaxOffset = TotalNumIntRegs * 8 +
16613 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
16615 /* Align ArgSize to a multiple of 8 */
16616 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
16617 bool NeedsAlign = (Align > 8);
16619 MachineBasicBlock *thisMBB = MBB;
16620 MachineBasicBlock *overflowMBB;
16621 MachineBasicBlock *offsetMBB;
16622 MachineBasicBlock *endMBB;
16624 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
16625 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
16626 unsigned OffsetReg = 0;
16628 if (!UseGPOffset && !UseFPOffset) {
16629 // If we only pull from the overflow region, we don't create a branch.
16630 // We don't need to alter control flow.
16631 OffsetDestReg = 0; // unused
16632 OverflowDestReg = DestReg;
16634 offsetMBB = nullptr;
16635 overflowMBB = thisMBB;
16638 // First emit code to check if gp_offset (or fp_offset) is below the bound.
16639 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
16640 // If not, pull from overflow_area. (branch to overflowMBB)
16645 // offsetMBB overflowMBB
16650 // Registers for the PHI in endMBB
16651 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
16652 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
16654 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
16655 MachineFunction *MF = MBB->getParent();
16656 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16657 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16658 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16660 MachineFunction::iterator MBBIter = MBB;
16663 // Insert the new basic blocks
16664 MF->insert(MBBIter, offsetMBB);
16665 MF->insert(MBBIter, overflowMBB);
16666 MF->insert(MBBIter, endMBB);
16668 // Transfer the remainder of MBB and its successor edges to endMBB.
16669 endMBB->splice(endMBB->begin(), thisMBB,
16670 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
16671 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
16673 // Make offsetMBB and overflowMBB successors of thisMBB
16674 thisMBB->addSuccessor(offsetMBB);
16675 thisMBB->addSuccessor(overflowMBB);
16677 // endMBB is a successor of both offsetMBB and overflowMBB
16678 offsetMBB->addSuccessor(endMBB);
16679 overflowMBB->addSuccessor(endMBB);
16681 // Load the offset value into a register
16682 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
16683 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
16687 .addDisp(Disp, UseFPOffset ? 4 : 0)
16688 .addOperand(Segment)
16689 .setMemRefs(MMOBegin, MMOEnd);
16691 // Check if there is enough room left to pull this argument.
16692 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
16694 .addImm(MaxOffset + 8 - ArgSizeA8);
16696 // Branch to "overflowMBB" if offset >= max
16697 // Fall through to "offsetMBB" otherwise
16698 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
16699 .addMBB(overflowMBB);
16702 // In offsetMBB, emit code to use the reg_save_area.
16704 assert(OffsetReg != 0);
16706 // Read the reg_save_area address.
16707 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
16708 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
16713 .addOperand(Segment)
16714 .setMemRefs(MMOBegin, MMOEnd);
16716 // Zero-extend the offset
16717 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
16718 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
16721 .addImm(X86::sub_32bit);
16723 // Add the offset to the reg_save_area to get the final address.
16724 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
16725 .addReg(OffsetReg64)
16726 .addReg(RegSaveReg);
16728 // Compute the offset for the next argument
16729 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
16730 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
16732 .addImm(UseFPOffset ? 16 : 8);
16734 // Store it back into the va_list.
16735 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
16739 .addDisp(Disp, UseFPOffset ? 4 : 0)
16740 .addOperand(Segment)
16741 .addReg(NextOffsetReg)
16742 .setMemRefs(MMOBegin, MMOEnd);
16745 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
16750 // Emit code to use overflow area
16753 // Load the overflow_area address into a register.
16754 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
16755 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
16760 .addOperand(Segment)
16761 .setMemRefs(MMOBegin, MMOEnd);
16763 // If we need to align it, do so. Otherwise, just copy the address
16764 // to OverflowDestReg.
16766 // Align the overflow address
16767 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
16768 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
16770 // aligned_addr = (addr + (align-1)) & ~(align-1)
16771 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
16772 .addReg(OverflowAddrReg)
16775 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
16777 .addImm(~(uint64_t)(Align-1));
16779 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
16780 .addReg(OverflowAddrReg);
16783 // Compute the next overflow address after this argument.
16784 // (the overflow address should be kept 8-byte aligned)
16785 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
16786 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
16787 .addReg(OverflowDestReg)
16788 .addImm(ArgSizeA8);
16790 // Store the new overflow address.
16791 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
16796 .addOperand(Segment)
16797 .addReg(NextAddrReg)
16798 .setMemRefs(MMOBegin, MMOEnd);
16800 // If we branched, emit the PHI to the front of endMBB.
16802 BuildMI(*endMBB, endMBB->begin(), DL,
16803 TII->get(X86::PHI), DestReg)
16804 .addReg(OffsetDestReg).addMBB(offsetMBB)
16805 .addReg(OverflowDestReg).addMBB(overflowMBB);
16808 // Erase the pseudo instruction
16809 MI->eraseFromParent();
16814 MachineBasicBlock *
16815 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
16817 MachineBasicBlock *MBB) const {
16818 // Emit code to save XMM registers to the stack. The ABI says that the
16819 // number of registers to save is given in %al, so it's theoretically
16820 // possible to do an indirect jump trick to avoid saving all of them,
16821 // however this code takes a simpler approach and just executes all
16822 // of the stores if %al is non-zero. It's less code, and it's probably
16823 // easier on the hardware branch predictor, and stores aren't all that
16824 // expensive anyway.
16826 // Create the new basic blocks. One block contains all the XMM stores,
16827 // and one block is the final destination regardless of whether any
16828 // stores were performed.
16829 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
16830 MachineFunction *F = MBB->getParent();
16831 MachineFunction::iterator MBBIter = MBB;
16833 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
16834 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
16835 F->insert(MBBIter, XMMSaveMBB);
16836 F->insert(MBBIter, EndMBB);
16838 // Transfer the remainder of MBB and its successor edges to EndMBB.
16839 EndMBB->splice(EndMBB->begin(), MBB,
16840 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16841 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
16843 // The original block will now fall through to the XMM save block.
16844 MBB->addSuccessor(XMMSaveMBB);
16845 // The XMMSaveMBB will fall through to the end block.
16846 XMMSaveMBB->addSuccessor(EndMBB);
16848 // Now add the instructions.
16849 const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
16850 DebugLoc DL = MI->getDebugLoc();
16852 unsigned CountReg = MI->getOperand(0).getReg();
16853 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
16854 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
16856 if (!Subtarget->isTargetWin64()) {
16857 // If %al is 0, branch around the XMM save block.
16858 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
16859 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
16860 MBB->addSuccessor(EndMBB);
16863 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
16864 // that was just emitted, but clearly shouldn't be "saved".
16865 assert((MI->getNumOperands() <= 3 ||
16866 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
16867 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
16868 && "Expected last argument to be EFLAGS");
16869 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
16870 // In the XMM save block, save all the XMM argument registers.
16871 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
16872 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
16873 MachineMemOperand *MMO =
16874 F->getMachineMemOperand(
16875 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
16876 MachineMemOperand::MOStore,
16877 /*Size=*/16, /*Align=*/16);
16878 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
16879 .addFrameIndex(RegSaveFrameIndex)
16880 .addImm(/*Scale=*/1)
16881 .addReg(/*IndexReg=*/0)
16882 .addImm(/*Disp=*/Offset)
16883 .addReg(/*Segment=*/0)
16884 .addReg(MI->getOperand(i).getReg())
16885 .addMemOperand(MMO);
16888 MI->eraseFromParent(); // The pseudo instruction is gone now.
16893 // The EFLAGS operand of SelectItr might be missing a kill marker
16894 // because there were multiple uses of EFLAGS, and ISel didn't know
16895 // which to mark. Figure out whether SelectItr should have had a
16896 // kill marker, and set it if it should. Returns the correct kill
16898 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
16899 MachineBasicBlock* BB,
16900 const TargetRegisterInfo* TRI) {
16901 // Scan forward through BB for a use/def of EFLAGS.
16902 MachineBasicBlock::iterator miI(std::next(SelectItr));
16903 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
16904 const MachineInstr& mi = *miI;
16905 if (mi.readsRegister(X86::EFLAGS))
16907 if (mi.definesRegister(X86::EFLAGS))
16908 break; // Should have kill-flag - update below.
16911 // If we hit the end of the block, check whether EFLAGS is live into a
16913 if (miI == BB->end()) {
16914 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
16915 sEnd = BB->succ_end();
16916 sItr != sEnd; ++sItr) {
16917 MachineBasicBlock* succ = *sItr;
16918 if (succ->isLiveIn(X86::EFLAGS))
16923 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
16924 // out. SelectMI should have a kill flag on EFLAGS.
16925 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
16929 MachineBasicBlock *
16930 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
16931 MachineBasicBlock *BB) const {
16932 const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
16933 DebugLoc DL = MI->getDebugLoc();
16935 // To "insert" a SELECT_CC instruction, we actually have to insert the
16936 // diamond control-flow pattern. The incoming instruction knows the
16937 // destination vreg to set, the condition code register to branch on, the
16938 // true/false values to select between, and a branch opcode to use.
16939 const BasicBlock *LLVM_BB = BB->getBasicBlock();
16940 MachineFunction::iterator It = BB;
16946 // cmpTY ccX, r1, r2
16948 // fallthrough --> copy0MBB
16949 MachineBasicBlock *thisMBB = BB;
16950 MachineFunction *F = BB->getParent();
16951 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
16952 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
16953 F->insert(It, copy0MBB);
16954 F->insert(It, sinkMBB);
16956 // If the EFLAGS register isn't dead in the terminator, then claim that it's
16957 // live into the sink and copy blocks.
16958 const TargetRegisterInfo* TRI = BB->getParent()->getTarget().getRegisterInfo();
16959 if (!MI->killsRegister(X86::EFLAGS) &&
16960 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
16961 copy0MBB->addLiveIn(X86::EFLAGS);
16962 sinkMBB->addLiveIn(X86::EFLAGS);
16965 // Transfer the remainder of BB and its successor edges to sinkMBB.
16966 sinkMBB->splice(sinkMBB->begin(), BB,
16967 std::next(MachineBasicBlock::iterator(MI)), BB->end());
16968 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
16970 // Add the true and fallthrough blocks as its successors.
16971 BB->addSuccessor(copy0MBB);
16972 BB->addSuccessor(sinkMBB);
16974 // Create the conditional branch instruction.
16976 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
16977 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
16980 // %FalseValue = ...
16981 // # fallthrough to sinkMBB
16982 copy0MBB->addSuccessor(sinkMBB);
16985 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
16987 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16988 TII->get(X86::PHI), MI->getOperand(0).getReg())
16989 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
16990 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
16992 MI->eraseFromParent(); // The pseudo instruction is gone now.
16996 MachineBasicBlock *
16997 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
16998 bool Is64Bit) const {
16999 MachineFunction *MF = BB->getParent();
17000 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17001 DebugLoc DL = MI->getDebugLoc();
17002 const BasicBlock *LLVM_BB = BB->getBasicBlock();
17004 assert(MF->shouldSplitStack());
17006 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
17007 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
17010 // ... [Till the alloca]
17011 // If stacklet is not large enough, jump to mallocMBB
17014 // Allocate by subtracting from RSP
17015 // Jump to continueMBB
17018 // Allocate by call to runtime
17022 // [rest of original BB]
17025 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17026 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17027 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17029 MachineRegisterInfo &MRI = MF->getRegInfo();
17030 const TargetRegisterClass *AddrRegClass =
17031 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
17033 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
17034 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
17035 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
17036 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
17037 sizeVReg = MI->getOperand(1).getReg(),
17038 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
17040 MachineFunction::iterator MBBIter = BB;
17043 MF->insert(MBBIter, bumpMBB);
17044 MF->insert(MBBIter, mallocMBB);
17045 MF->insert(MBBIter, continueMBB);
17047 continueMBB->splice(continueMBB->begin(), BB,
17048 std::next(MachineBasicBlock::iterator(MI)), BB->end());
17049 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
17051 // Add code to the main basic block to check if the stack limit has been hit,
17052 // and if so, jump to mallocMBB otherwise to bumpMBB.
17053 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
17054 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
17055 .addReg(tmpSPVReg).addReg(sizeVReg);
17056 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
17057 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
17058 .addReg(SPLimitVReg);
17059 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
17061 // bumpMBB simply decreases the stack pointer, since we know the current
17062 // stacklet has enough space.
17063 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
17064 .addReg(SPLimitVReg);
17065 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
17066 .addReg(SPLimitVReg);
17067 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
17069 // Calls into a routine in libgcc to allocate more space from the heap.
17070 const uint32_t *RegMask =
17071 MF->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
17073 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
17075 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
17076 .addExternalSymbol("__morestack_allocate_stack_space")
17077 .addRegMask(RegMask)
17078 .addReg(X86::RDI, RegState::Implicit)
17079 .addReg(X86::RAX, RegState::ImplicitDefine);
17081 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
17083 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
17084 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
17085 .addExternalSymbol("__morestack_allocate_stack_space")
17086 .addRegMask(RegMask)
17087 .addReg(X86::EAX, RegState::ImplicitDefine);
17091 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
17094 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
17095 .addReg(Is64Bit ? X86::RAX : X86::EAX);
17096 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
17098 // Set up the CFG correctly.
17099 BB->addSuccessor(bumpMBB);
17100 BB->addSuccessor(mallocMBB);
17101 mallocMBB->addSuccessor(continueMBB);
17102 bumpMBB->addSuccessor(continueMBB);
17104 // Take care of the PHI nodes.
17105 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
17106 MI->getOperand(0).getReg())
17107 .addReg(mallocPtrVReg).addMBB(mallocMBB)
17108 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
17110 // Delete the original pseudo instruction.
17111 MI->eraseFromParent();
17114 return continueMBB;
17117 MachineBasicBlock *
17118 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
17119 MachineBasicBlock *BB) const {
17120 const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
17121 DebugLoc DL = MI->getDebugLoc();
17123 assert(!Subtarget->isTargetMacho());
17125 // The lowering is pretty easy: we're just emitting the call to _alloca. The
17126 // non-trivial part is impdef of ESP.
17128 if (Subtarget->isTargetWin64()) {
17129 if (Subtarget->isTargetCygMing()) {
17130 // ___chkstk(Mingw64):
17131 // Clobbers R10, R11, RAX and EFLAGS.
17133 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
17134 .addExternalSymbol("___chkstk")
17135 .addReg(X86::RAX, RegState::Implicit)
17136 .addReg(X86::RSP, RegState::Implicit)
17137 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
17138 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
17139 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17141 // __chkstk(MSVCRT): does not update stack pointer.
17142 // Clobbers R10, R11 and EFLAGS.
17143 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
17144 .addExternalSymbol("__chkstk")
17145 .addReg(X86::RAX, RegState::Implicit)
17146 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17147 // RAX has the offset to be subtracted from RSP.
17148 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
17153 const char *StackProbeSymbol =
17154 Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
17156 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
17157 .addExternalSymbol(StackProbeSymbol)
17158 .addReg(X86::EAX, RegState::Implicit)
17159 .addReg(X86::ESP, RegState::Implicit)
17160 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
17161 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
17162 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17165 MI->eraseFromParent(); // The pseudo instruction is gone now.
17169 MachineBasicBlock *
17170 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
17171 MachineBasicBlock *BB) const {
17172 // This is pretty easy. We're taking the value that we received from
17173 // our load from the relocation, sticking it in either RDI (x86-64)
17174 // or EAX and doing an indirect call. The return value will then
17175 // be in the normal return register.
17176 MachineFunction *F = BB->getParent();
17177 const X86InstrInfo *TII
17178 = static_cast<const X86InstrInfo*>(F->getTarget().getInstrInfo());
17179 DebugLoc DL = MI->getDebugLoc();
17181 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
17182 assert(MI->getOperand(3).isGlobal() && "This should be a global");
17184 // Get a register mask for the lowered call.
17185 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
17186 // proper register mask.
17187 const uint32_t *RegMask =
17188 F->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
17189 if (Subtarget->is64Bit()) {
17190 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17191 TII->get(X86::MOV64rm), X86::RDI)
17193 .addImm(0).addReg(0)
17194 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17195 MI->getOperand(3).getTargetFlags())
17197 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
17198 addDirectMem(MIB, X86::RDI);
17199 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
17200 } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
17201 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17202 TII->get(X86::MOV32rm), X86::EAX)
17204 .addImm(0).addReg(0)
17205 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17206 MI->getOperand(3).getTargetFlags())
17208 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
17209 addDirectMem(MIB, X86::EAX);
17210 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
17212 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17213 TII->get(X86::MOV32rm), X86::EAX)
17214 .addReg(TII->getGlobalBaseReg(F))
17215 .addImm(0).addReg(0)
17216 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17217 MI->getOperand(3).getTargetFlags())
17219 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
17220 addDirectMem(MIB, X86::EAX);
17221 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
17224 MI->eraseFromParent(); // The pseudo instruction is gone now.
17228 MachineBasicBlock *
17229 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
17230 MachineBasicBlock *MBB) const {
17231 DebugLoc DL = MI->getDebugLoc();
17232 MachineFunction *MF = MBB->getParent();
17233 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17234 MachineRegisterInfo &MRI = MF->getRegInfo();
17236 const BasicBlock *BB = MBB->getBasicBlock();
17237 MachineFunction::iterator I = MBB;
17240 // Memory Reference
17241 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17242 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17245 unsigned MemOpndSlot = 0;
17247 unsigned CurOp = 0;
17249 DstReg = MI->getOperand(CurOp++).getReg();
17250 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
17251 assert(RC->hasType(MVT::i32) && "Invalid destination!");
17252 unsigned mainDstReg = MRI.createVirtualRegister(RC);
17253 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
17255 MemOpndSlot = CurOp;
17257 MVT PVT = getPointerTy();
17258 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
17259 "Invalid Pointer Size!");
17261 // For v = setjmp(buf), we generate
17264 // buf[LabelOffset] = restoreMBB
17265 // SjLjSetup restoreMBB
17271 // v = phi(main, restore)
17276 MachineBasicBlock *thisMBB = MBB;
17277 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17278 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17279 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
17280 MF->insert(I, mainMBB);
17281 MF->insert(I, sinkMBB);
17282 MF->push_back(restoreMBB);
17284 MachineInstrBuilder MIB;
17286 // Transfer the remainder of BB and its successor edges to sinkMBB.
17287 sinkMBB->splice(sinkMBB->begin(), MBB,
17288 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17289 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17292 unsigned PtrStoreOpc = 0;
17293 unsigned LabelReg = 0;
17294 const int64_t LabelOffset = 1 * PVT.getStoreSize();
17295 Reloc::Model RM = MF->getTarget().getRelocationModel();
17296 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
17297 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
17299 // Prepare IP either in reg or imm.
17300 if (!UseImmLabel) {
17301 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
17302 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
17303 LabelReg = MRI.createVirtualRegister(PtrRC);
17304 if (Subtarget->is64Bit()) {
17305 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
17309 .addMBB(restoreMBB)
17312 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
17313 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
17314 .addReg(XII->getGlobalBaseReg(MF))
17317 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
17321 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
17323 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
17324 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17325 if (i == X86::AddrDisp)
17326 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
17328 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
17331 MIB.addReg(LabelReg);
17333 MIB.addMBB(restoreMBB);
17334 MIB.setMemRefs(MMOBegin, MMOEnd);
17336 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
17337 .addMBB(restoreMBB);
17339 const X86RegisterInfo *RegInfo =
17340 static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
17341 MIB.addRegMask(RegInfo->getNoPreservedMask());
17342 thisMBB->addSuccessor(mainMBB);
17343 thisMBB->addSuccessor(restoreMBB);
17347 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
17348 mainMBB->addSuccessor(sinkMBB);
17351 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17352 TII->get(X86::PHI), DstReg)
17353 .addReg(mainDstReg).addMBB(mainMBB)
17354 .addReg(restoreDstReg).addMBB(restoreMBB);
17357 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
17358 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
17359 restoreMBB->addSuccessor(sinkMBB);
17361 MI->eraseFromParent();
17365 MachineBasicBlock *
17366 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
17367 MachineBasicBlock *MBB) const {
17368 DebugLoc DL = MI->getDebugLoc();
17369 MachineFunction *MF = MBB->getParent();
17370 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17371 MachineRegisterInfo &MRI = MF->getRegInfo();
17373 // Memory Reference
17374 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17375 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17377 MVT PVT = getPointerTy();
17378 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
17379 "Invalid Pointer Size!");
17381 const TargetRegisterClass *RC =
17382 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
17383 unsigned Tmp = MRI.createVirtualRegister(RC);
17384 // Since FP is only updated here but NOT referenced, it's treated as GPR.
17385 const X86RegisterInfo *RegInfo =
17386 static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
17387 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
17388 unsigned SP = RegInfo->getStackRegister();
17390 MachineInstrBuilder MIB;
17392 const int64_t LabelOffset = 1 * PVT.getStoreSize();
17393 const int64_t SPOffset = 2 * PVT.getStoreSize();
17395 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
17396 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
17399 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
17400 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
17401 MIB.addOperand(MI->getOperand(i));
17402 MIB.setMemRefs(MMOBegin, MMOEnd);
17404 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
17405 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17406 if (i == X86::AddrDisp)
17407 MIB.addDisp(MI->getOperand(i), LabelOffset);
17409 MIB.addOperand(MI->getOperand(i));
17411 MIB.setMemRefs(MMOBegin, MMOEnd);
17413 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
17414 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17415 if (i == X86::AddrDisp)
17416 MIB.addDisp(MI->getOperand(i), SPOffset);
17418 MIB.addOperand(MI->getOperand(i));
17420 MIB.setMemRefs(MMOBegin, MMOEnd);
17422 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
17424 MI->eraseFromParent();
17428 // Replace 213-type (isel default) FMA3 instructions with 231-type for
17429 // accumulator loops. Writing back to the accumulator allows the coalescer
17430 // to remove extra copies in the loop.
17431 MachineBasicBlock *
17432 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
17433 MachineBasicBlock *MBB) const {
17434 MachineOperand &AddendOp = MI->getOperand(3);
17436 // Bail out early if the addend isn't a register - we can't switch these.
17437 if (!AddendOp.isReg())
17440 MachineFunction &MF = *MBB->getParent();
17441 MachineRegisterInfo &MRI = MF.getRegInfo();
17443 // Check whether the addend is defined by a PHI:
17444 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
17445 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
17446 if (!AddendDef.isPHI())
17449 // Look for the following pattern:
17451 // %addend = phi [%entry, 0], [%loop, %result]
17453 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
17457 // %addend = phi [%entry, 0], [%loop, %result]
17459 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
17461 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
17462 assert(AddendDef.getOperand(i).isReg());
17463 MachineOperand PHISrcOp = AddendDef.getOperand(i);
17464 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
17465 if (&PHISrcInst == MI) {
17466 // Found a matching instruction.
17467 unsigned NewFMAOpc = 0;
17468 switch (MI->getOpcode()) {
17469 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
17470 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
17471 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
17472 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
17473 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
17474 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
17475 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
17476 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
17477 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
17478 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
17479 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
17480 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
17481 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
17482 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
17483 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
17484 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
17485 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
17486 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
17487 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
17488 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
17489 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
17490 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
17491 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
17492 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
17493 default: llvm_unreachable("Unrecognized FMA variant.");
17496 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
17497 MachineInstrBuilder MIB =
17498 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
17499 .addOperand(MI->getOperand(0))
17500 .addOperand(MI->getOperand(3))
17501 .addOperand(MI->getOperand(2))
17502 .addOperand(MI->getOperand(1));
17503 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
17504 MI->eraseFromParent();
17511 MachineBasicBlock *
17512 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
17513 MachineBasicBlock *BB) const {
17514 switch (MI->getOpcode()) {
17515 default: llvm_unreachable("Unexpected instr type to insert");
17516 case X86::TAILJMPd64:
17517 case X86::TAILJMPr64:
17518 case X86::TAILJMPm64:
17519 llvm_unreachable("TAILJMP64 would not be touched here.");
17520 case X86::TCRETURNdi64:
17521 case X86::TCRETURNri64:
17522 case X86::TCRETURNmi64:
17524 case X86::WIN_ALLOCA:
17525 return EmitLoweredWinAlloca(MI, BB);
17526 case X86::SEG_ALLOCA_32:
17527 return EmitLoweredSegAlloca(MI, BB, false);
17528 case X86::SEG_ALLOCA_64:
17529 return EmitLoweredSegAlloca(MI, BB, true);
17530 case X86::TLSCall_32:
17531 case X86::TLSCall_64:
17532 return EmitLoweredTLSCall(MI, BB);
17533 case X86::CMOV_GR8:
17534 case X86::CMOV_FR32:
17535 case X86::CMOV_FR64:
17536 case X86::CMOV_V4F32:
17537 case X86::CMOV_V2F64:
17538 case X86::CMOV_V2I64:
17539 case X86::CMOV_V8F32:
17540 case X86::CMOV_V4F64:
17541 case X86::CMOV_V4I64:
17542 case X86::CMOV_V16F32:
17543 case X86::CMOV_V8F64:
17544 case X86::CMOV_V8I64:
17545 case X86::CMOV_GR16:
17546 case X86::CMOV_GR32:
17547 case X86::CMOV_RFP32:
17548 case X86::CMOV_RFP64:
17549 case X86::CMOV_RFP80:
17550 return EmitLoweredSelect(MI, BB);
17552 case X86::FP32_TO_INT16_IN_MEM:
17553 case X86::FP32_TO_INT32_IN_MEM:
17554 case X86::FP32_TO_INT64_IN_MEM:
17555 case X86::FP64_TO_INT16_IN_MEM:
17556 case X86::FP64_TO_INT32_IN_MEM:
17557 case X86::FP64_TO_INT64_IN_MEM:
17558 case X86::FP80_TO_INT16_IN_MEM:
17559 case X86::FP80_TO_INT32_IN_MEM:
17560 case X86::FP80_TO_INT64_IN_MEM: {
17561 MachineFunction *F = BB->getParent();
17562 const TargetInstrInfo *TII = F->getTarget().getInstrInfo();
17563 DebugLoc DL = MI->getDebugLoc();
17565 // Change the floating point control register to use "round towards zero"
17566 // mode when truncating to an integer value.
17567 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
17568 addFrameReference(BuildMI(*BB, MI, DL,
17569 TII->get(X86::FNSTCW16m)), CWFrameIdx);
17571 // Load the old value of the high byte of the control word...
17573 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
17574 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
17577 // Set the high part to be round to zero...
17578 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
17581 // Reload the modified control word now...
17582 addFrameReference(BuildMI(*BB, MI, DL,
17583 TII->get(X86::FLDCW16m)), CWFrameIdx);
17585 // Restore the memory image of control word to original value
17586 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
17589 // Get the X86 opcode to use.
17591 switch (MI->getOpcode()) {
17592 default: llvm_unreachable("illegal opcode!");
17593 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
17594 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
17595 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
17596 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
17597 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
17598 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
17599 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
17600 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
17601 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
17605 MachineOperand &Op = MI->getOperand(0);
17607 AM.BaseType = X86AddressMode::RegBase;
17608 AM.Base.Reg = Op.getReg();
17610 AM.BaseType = X86AddressMode::FrameIndexBase;
17611 AM.Base.FrameIndex = Op.getIndex();
17613 Op = MI->getOperand(1);
17615 AM.Scale = Op.getImm();
17616 Op = MI->getOperand(2);
17618 AM.IndexReg = Op.getImm();
17619 Op = MI->getOperand(3);
17620 if (Op.isGlobal()) {
17621 AM.GV = Op.getGlobal();
17623 AM.Disp = Op.getImm();
17625 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
17626 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
17628 // Reload the original control word now.
17629 addFrameReference(BuildMI(*BB, MI, DL,
17630 TII->get(X86::FLDCW16m)), CWFrameIdx);
17632 MI->eraseFromParent(); // The pseudo instruction is gone now.
17635 // String/text processing lowering.
17636 case X86::PCMPISTRM128REG:
17637 case X86::VPCMPISTRM128REG:
17638 case X86::PCMPISTRM128MEM:
17639 case X86::VPCMPISTRM128MEM:
17640 case X86::PCMPESTRM128REG:
17641 case X86::VPCMPESTRM128REG:
17642 case X86::PCMPESTRM128MEM:
17643 case X86::VPCMPESTRM128MEM:
17644 assert(Subtarget->hasSSE42() &&
17645 "Target must have SSE4.2 or AVX features enabled");
17646 return EmitPCMPSTRM(MI, BB, BB->getParent()->getTarget().getInstrInfo());
17648 // String/text processing lowering.
17649 case X86::PCMPISTRIREG:
17650 case X86::VPCMPISTRIREG:
17651 case X86::PCMPISTRIMEM:
17652 case X86::VPCMPISTRIMEM:
17653 case X86::PCMPESTRIREG:
17654 case X86::VPCMPESTRIREG:
17655 case X86::PCMPESTRIMEM:
17656 case X86::VPCMPESTRIMEM:
17657 assert(Subtarget->hasSSE42() &&
17658 "Target must have SSE4.2 or AVX features enabled");
17659 return EmitPCMPSTRI(MI, BB, BB->getParent()->getTarget().getInstrInfo());
17661 // Thread synchronization.
17663 return EmitMonitor(MI, BB, BB->getParent()->getTarget().getInstrInfo(), Subtarget);
17667 return EmitXBegin(MI, BB, BB->getParent()->getTarget().getInstrInfo());
17669 // Atomic Lowering.
17670 case X86::ATOMAND8:
17671 case X86::ATOMAND16:
17672 case X86::ATOMAND32:
17673 case X86::ATOMAND64:
17676 case X86::ATOMOR16:
17677 case X86::ATOMOR32:
17678 case X86::ATOMOR64:
17680 case X86::ATOMXOR16:
17681 case X86::ATOMXOR8:
17682 case X86::ATOMXOR32:
17683 case X86::ATOMXOR64:
17685 case X86::ATOMNAND8:
17686 case X86::ATOMNAND16:
17687 case X86::ATOMNAND32:
17688 case X86::ATOMNAND64:
17690 case X86::ATOMMAX8:
17691 case X86::ATOMMAX16:
17692 case X86::ATOMMAX32:
17693 case X86::ATOMMAX64:
17695 case X86::ATOMMIN8:
17696 case X86::ATOMMIN16:
17697 case X86::ATOMMIN32:
17698 case X86::ATOMMIN64:
17700 case X86::ATOMUMAX8:
17701 case X86::ATOMUMAX16:
17702 case X86::ATOMUMAX32:
17703 case X86::ATOMUMAX64:
17705 case X86::ATOMUMIN8:
17706 case X86::ATOMUMIN16:
17707 case X86::ATOMUMIN32:
17708 case X86::ATOMUMIN64:
17709 return EmitAtomicLoadArith(MI, BB);
17711 // This group does 64-bit operations on a 32-bit host.
17712 case X86::ATOMAND6432:
17713 case X86::ATOMOR6432:
17714 case X86::ATOMXOR6432:
17715 case X86::ATOMNAND6432:
17716 case X86::ATOMADD6432:
17717 case X86::ATOMSUB6432:
17718 case X86::ATOMMAX6432:
17719 case X86::ATOMMIN6432:
17720 case X86::ATOMUMAX6432:
17721 case X86::ATOMUMIN6432:
17722 case X86::ATOMSWAP6432:
17723 return EmitAtomicLoadArith6432(MI, BB);
17725 case X86::VASTART_SAVE_XMM_REGS:
17726 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
17728 case X86::VAARG_64:
17729 return EmitVAARG64WithCustomInserter(MI, BB);
17731 case X86::EH_SjLj_SetJmp32:
17732 case X86::EH_SjLj_SetJmp64:
17733 return emitEHSjLjSetJmp(MI, BB);
17735 case X86::EH_SjLj_LongJmp32:
17736 case X86::EH_SjLj_LongJmp64:
17737 return emitEHSjLjLongJmp(MI, BB);
17739 case TargetOpcode::STACKMAP:
17740 case TargetOpcode::PATCHPOINT:
17741 return emitPatchPoint(MI, BB);
17743 case X86::VFMADDPDr213r:
17744 case X86::VFMADDPSr213r:
17745 case X86::VFMADDSDr213r:
17746 case X86::VFMADDSSr213r:
17747 case X86::VFMSUBPDr213r:
17748 case X86::VFMSUBPSr213r:
17749 case X86::VFMSUBSDr213r:
17750 case X86::VFMSUBSSr213r:
17751 case X86::VFNMADDPDr213r:
17752 case X86::VFNMADDPSr213r:
17753 case X86::VFNMADDSDr213r:
17754 case X86::VFNMADDSSr213r:
17755 case X86::VFNMSUBPDr213r:
17756 case X86::VFNMSUBPSr213r:
17757 case X86::VFNMSUBSDr213r:
17758 case X86::VFNMSUBSSr213r:
17759 case X86::VFMADDPDr213rY:
17760 case X86::VFMADDPSr213rY:
17761 case X86::VFMSUBPDr213rY:
17762 case X86::VFMSUBPSr213rY:
17763 case X86::VFNMADDPDr213rY:
17764 case X86::VFNMADDPSr213rY:
17765 case X86::VFNMSUBPDr213rY:
17766 case X86::VFNMSUBPSr213rY:
17767 return emitFMA3Instr(MI, BB);
17771 //===----------------------------------------------------------------------===//
17772 // X86 Optimization Hooks
17773 //===----------------------------------------------------------------------===//
17775 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
17778 const SelectionDAG &DAG,
17779 unsigned Depth) const {
17780 unsigned BitWidth = KnownZero.getBitWidth();
17781 unsigned Opc = Op.getOpcode();
17782 assert((Opc >= ISD::BUILTIN_OP_END ||
17783 Opc == ISD::INTRINSIC_WO_CHAIN ||
17784 Opc == ISD::INTRINSIC_W_CHAIN ||
17785 Opc == ISD::INTRINSIC_VOID) &&
17786 "Should use MaskedValueIsZero if you don't know whether Op"
17787 " is a target node!");
17789 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
17803 // These nodes' second result is a boolean.
17804 if (Op.getResNo() == 0)
17807 case X86ISD::SETCC:
17808 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
17810 case ISD::INTRINSIC_WO_CHAIN: {
17811 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17812 unsigned NumLoBits = 0;
17815 case Intrinsic::x86_sse_movmsk_ps:
17816 case Intrinsic::x86_avx_movmsk_ps_256:
17817 case Intrinsic::x86_sse2_movmsk_pd:
17818 case Intrinsic::x86_avx_movmsk_pd_256:
17819 case Intrinsic::x86_mmx_pmovmskb:
17820 case Intrinsic::x86_sse2_pmovmskb_128:
17821 case Intrinsic::x86_avx2_pmovmskb: {
17822 // High bits of movmskp{s|d}, pmovmskb are known zero.
17824 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
17825 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
17826 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
17827 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
17828 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
17829 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
17830 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
17831 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
17833 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
17842 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
17844 const SelectionDAG &,
17845 unsigned Depth) const {
17846 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
17847 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
17848 return Op.getValueType().getScalarType().getSizeInBits();
17854 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
17855 /// node is a GlobalAddress + offset.
17856 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
17857 const GlobalValue* &GA,
17858 int64_t &Offset) const {
17859 if (N->getOpcode() == X86ISD::Wrapper) {
17860 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
17861 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
17862 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
17866 return TargetLowering::isGAPlusOffset(N, GA, Offset);
17869 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
17870 /// same as extracting the high 128-bit part of 256-bit vector and then
17871 /// inserting the result into the low part of a new 256-bit vector
17872 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
17873 EVT VT = SVOp->getValueType(0);
17874 unsigned NumElems = VT.getVectorNumElements();
17876 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17877 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
17878 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17879 SVOp->getMaskElt(j) >= 0)
17885 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
17886 /// same as extracting the low 128-bit part of 256-bit vector and then
17887 /// inserting the result into the high part of a new 256-bit vector
17888 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
17889 EVT VT = SVOp->getValueType(0);
17890 unsigned NumElems = VT.getVectorNumElements();
17892 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17893 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
17894 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17895 SVOp->getMaskElt(j) >= 0)
17901 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
17902 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
17903 TargetLowering::DAGCombinerInfo &DCI,
17904 const X86Subtarget* Subtarget) {
17906 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17907 SDValue V1 = SVOp->getOperand(0);
17908 SDValue V2 = SVOp->getOperand(1);
17909 EVT VT = SVOp->getValueType(0);
17910 unsigned NumElems = VT.getVectorNumElements();
17912 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
17913 V2.getOpcode() == ISD::CONCAT_VECTORS) {
17917 // V UNDEF BUILD_VECTOR UNDEF
17919 // CONCAT_VECTOR CONCAT_VECTOR
17922 // RESULT: V + zero extended
17924 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
17925 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
17926 V1.getOperand(1).getOpcode() != ISD::UNDEF)
17929 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
17932 // To match the shuffle mask, the first half of the mask should
17933 // be exactly the first vector, and all the rest a splat with the
17934 // first element of the second one.
17935 for (unsigned i = 0; i != NumElems/2; ++i)
17936 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
17937 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
17940 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
17941 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
17942 if (Ld->hasNUsesOfValue(1, 0)) {
17943 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
17944 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
17946 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
17948 Ld->getPointerInfo(),
17949 Ld->getAlignment(),
17950 false/*isVolatile*/, true/*ReadMem*/,
17951 false/*WriteMem*/);
17953 // Make sure the newly-created LOAD is in the same position as Ld in
17954 // terms of dependency. We create a TokenFactor for Ld and ResNode,
17955 // and update uses of Ld's output chain to use the TokenFactor.
17956 if (Ld->hasAnyUseOfValue(1)) {
17957 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17958 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
17959 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
17960 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
17961 SDValue(ResNode.getNode(), 1));
17964 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
17968 // Emit a zeroed vector and insert the desired subvector on its
17970 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17971 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
17972 return DCI.CombineTo(N, InsV);
17975 //===--------------------------------------------------------------------===//
17976 // Combine some shuffles into subvector extracts and inserts:
17979 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17980 if (isShuffleHigh128VectorInsertLow(SVOp)) {
17981 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
17982 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
17983 return DCI.CombineTo(N, InsV);
17986 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17987 if (isShuffleLow128VectorInsertHigh(SVOp)) {
17988 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
17989 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
17990 return DCI.CombineTo(N, InsV);
17996 /// PerformShuffleCombine - Performs several different shuffle combines.
17997 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
17998 TargetLowering::DAGCombinerInfo &DCI,
17999 const X86Subtarget *Subtarget) {
18001 SDValue N0 = N->getOperand(0);
18002 SDValue N1 = N->getOperand(1);
18003 EVT VT = N->getValueType(0);
18005 // Don't create instructions with illegal types after legalize types has run.
18006 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18007 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
18010 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
18011 if (Subtarget->hasFp256() && VT.is256BitVector() &&
18012 N->getOpcode() == ISD::VECTOR_SHUFFLE)
18013 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
18015 // During Type Legalization, when promoting illegal vector types,
18016 // the backend might introduce new shuffle dag nodes and bitcasts.
18018 // This code performs the following transformation:
18019 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
18020 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
18022 // We do this only if both the bitcast and the BINOP dag nodes have
18023 // one use. Also, perform this transformation only if the new binary
18024 // operation is legal. This is to avoid introducing dag nodes that
18025 // potentially need to be further expanded (or custom lowered) into a
18026 // less optimal sequence of dag nodes.
18027 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
18028 N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
18029 N0.getOpcode() == ISD::BITCAST) {
18030 SDValue BC0 = N0.getOperand(0);
18031 EVT SVT = BC0.getValueType();
18032 unsigned Opcode = BC0.getOpcode();
18033 unsigned NumElts = VT.getVectorNumElements();
18035 if (BC0.hasOneUse() && SVT.isVector() &&
18036 SVT.getVectorNumElements() * 2 == NumElts &&
18037 TLI.isOperationLegal(Opcode, VT)) {
18038 bool CanFold = false;
18050 unsigned SVTNumElts = SVT.getVectorNumElements();
18051 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
18052 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
18053 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
18054 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
18055 CanFold = SVOp->getMaskElt(i) < 0;
18058 SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
18059 SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
18060 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
18061 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
18066 // Only handle 128 wide vector from here on.
18067 if (!VT.is128BitVector())
18070 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
18071 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
18072 // consecutive, non-overlapping, and in the right order.
18073 SmallVector<SDValue, 16> Elts;
18074 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
18075 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
18077 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
18080 /// PerformTruncateCombine - Converts truncate operation to
18081 /// a sequence of vector shuffle operations.
18082 /// It is possible when we truncate 256-bit vector to 128-bit vector
18083 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
18084 TargetLowering::DAGCombinerInfo &DCI,
18085 const X86Subtarget *Subtarget) {
18089 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
18090 /// specific shuffle of a load can be folded into a single element load.
18091 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
18092 /// shuffles have been customed lowered so we need to handle those here.
18093 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
18094 TargetLowering::DAGCombinerInfo &DCI) {
18095 if (DCI.isBeforeLegalizeOps())
18098 SDValue InVec = N->getOperand(0);
18099 SDValue EltNo = N->getOperand(1);
18101 if (!isa<ConstantSDNode>(EltNo))
18104 EVT VT = InVec.getValueType();
18106 bool HasShuffleIntoBitcast = false;
18107 if (InVec.getOpcode() == ISD::BITCAST) {
18108 // Don't duplicate a load with other uses.
18109 if (!InVec.hasOneUse())
18111 EVT BCVT = InVec.getOperand(0).getValueType();
18112 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
18114 InVec = InVec.getOperand(0);
18115 HasShuffleIntoBitcast = true;
18118 if (!isTargetShuffle(InVec.getOpcode()))
18121 // Don't duplicate a load with other uses.
18122 if (!InVec.hasOneUse())
18125 SmallVector<int, 16> ShuffleMask;
18127 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
18131 // Select the input vector, guarding against out of range extract vector.
18132 unsigned NumElems = VT.getVectorNumElements();
18133 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
18134 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
18135 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
18136 : InVec.getOperand(1);
18138 // If inputs to shuffle are the same for both ops, then allow 2 uses
18139 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
18141 if (LdNode.getOpcode() == ISD::BITCAST) {
18142 // Don't duplicate a load with other uses.
18143 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
18146 AllowedUses = 1; // only allow 1 load use if we have a bitcast
18147 LdNode = LdNode.getOperand(0);
18150 if (!ISD::isNormalLoad(LdNode.getNode()))
18153 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
18155 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
18158 if (HasShuffleIntoBitcast) {
18159 // If there's a bitcast before the shuffle, check if the load type and
18160 // alignment is valid.
18161 unsigned Align = LN0->getAlignment();
18162 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18163 unsigned NewAlign = TLI.getDataLayout()->
18164 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
18166 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
18170 // All checks match so transform back to vector_shuffle so that DAG combiner
18171 // can finish the job
18174 // Create shuffle node taking into account the case that its a unary shuffle
18175 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
18176 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
18177 InVec.getOperand(0), Shuffle,
18179 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
18180 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
18184 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
18185 /// generation and convert it from being a bunch of shuffles and extracts
18186 /// to a simple store and scalar loads to extract the elements.
18187 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
18188 TargetLowering::DAGCombinerInfo &DCI) {
18189 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
18190 if (NewOp.getNode())
18193 SDValue InputVector = N->getOperand(0);
18195 // Detect whether we are trying to convert from mmx to i32 and the bitcast
18196 // from mmx to v2i32 has a single usage.
18197 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
18198 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
18199 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
18200 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
18201 N->getValueType(0),
18202 InputVector.getNode()->getOperand(0));
18204 // Only operate on vectors of 4 elements, where the alternative shuffling
18205 // gets to be more expensive.
18206 if (InputVector.getValueType() != MVT::v4i32)
18209 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
18210 // single use which is a sign-extend or zero-extend, and all elements are
18212 SmallVector<SDNode *, 4> Uses;
18213 unsigned ExtractedElements = 0;
18214 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
18215 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
18216 if (UI.getUse().getResNo() != InputVector.getResNo())
18219 SDNode *Extract = *UI;
18220 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
18223 if (Extract->getValueType(0) != MVT::i32)
18225 if (!Extract->hasOneUse())
18227 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
18228 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
18230 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
18233 // Record which element was extracted.
18234 ExtractedElements |=
18235 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
18237 Uses.push_back(Extract);
18240 // If not all the elements were used, this may not be worthwhile.
18241 if (ExtractedElements != 15)
18244 // Ok, we've now decided to do the transformation.
18245 SDLoc dl(InputVector);
18247 // Store the value to a temporary stack slot.
18248 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
18249 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
18250 MachinePointerInfo(), false, false, 0);
18252 // Replace each use (extract) with a load of the appropriate element.
18253 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
18254 UE = Uses.end(); UI != UE; ++UI) {
18255 SDNode *Extract = *UI;
18257 // cOMpute the element's address.
18258 SDValue Idx = Extract->getOperand(1);
18260 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
18261 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
18262 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18263 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
18265 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
18266 StackPtr, OffsetVal);
18268 // Load the scalar.
18269 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
18270 ScalarAddr, MachinePointerInfo(),
18271 false, false, false, 0);
18273 // Replace the exact with the load.
18274 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
18277 // The replacement was made in place; don't return anything.
18281 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
18282 static std::pair<unsigned, bool>
18283 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
18284 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
18285 if (!VT.isVector())
18286 return std::make_pair(0, false);
18288 bool NeedSplit = false;
18289 switch (VT.getSimpleVT().SimpleTy) {
18290 default: return std::make_pair(0, false);
18294 if (!Subtarget->hasAVX2())
18296 if (!Subtarget->hasAVX())
18297 return std::make_pair(0, false);
18302 if (!Subtarget->hasSSE2())
18303 return std::make_pair(0, false);
18306 // SSE2 has only a small subset of the operations.
18307 bool hasUnsigned = Subtarget->hasSSE41() ||
18308 (Subtarget->hasSSE2() && VT == MVT::v16i8);
18309 bool hasSigned = Subtarget->hasSSE41() ||
18310 (Subtarget->hasSSE2() && VT == MVT::v8i16);
18312 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18315 // Check for x CC y ? x : y.
18316 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
18317 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
18322 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
18325 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
18328 Opc = hasSigned ? X86ISD::SMIN : 0; break;
18331 Opc = hasSigned ? X86ISD::SMAX : 0; break;
18333 // Check for x CC y ? y : x -- a min/max with reversed arms.
18334 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
18335 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
18340 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
18343 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
18346 Opc = hasSigned ? X86ISD::SMAX : 0; break;
18349 Opc = hasSigned ? X86ISD::SMIN : 0; break;
18353 return std::make_pair(Opc, NeedSplit);
18357 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
18358 const X86Subtarget *Subtarget) {
18360 SDValue Cond = N->getOperand(0);
18361 SDValue LHS = N->getOperand(1);
18362 SDValue RHS = N->getOperand(2);
18364 if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
18365 SDValue CondSrc = Cond->getOperand(0);
18366 if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
18367 Cond = CondSrc->getOperand(0);
18370 MVT VT = N->getSimpleValueType(0);
18371 MVT EltVT = VT.getVectorElementType();
18372 unsigned NumElems = VT.getVectorNumElements();
18373 // There is no blend with immediate in AVX-512.
18374 if (VT.is512BitVector())
18377 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
18379 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
18382 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
18385 unsigned MaskValue = 0;
18386 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
18389 SmallVector<int, 8> ShuffleMask(NumElems, -1);
18390 for (unsigned i = 0; i < NumElems; ++i) {
18391 // Be sure we emit undef where we can.
18392 if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
18393 ShuffleMask[i] = -1;
18395 ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
18398 return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
18401 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
18403 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
18404 TargetLowering::DAGCombinerInfo &DCI,
18405 const X86Subtarget *Subtarget) {
18407 SDValue Cond = N->getOperand(0);
18408 // Get the LHS/RHS of the select.
18409 SDValue LHS = N->getOperand(1);
18410 SDValue RHS = N->getOperand(2);
18411 EVT VT = LHS.getValueType();
18412 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18414 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
18415 // instructions match the semantics of the common C idiom x<y?x:y but not
18416 // x<=y?x:y, because of how they handle negative zero (which can be
18417 // ignored in unsafe-math mode).
18418 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
18419 VT != MVT::f80 && TLI.isTypeLegal(VT) &&
18420 (Subtarget->hasSSE2() ||
18421 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
18422 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18424 unsigned Opcode = 0;
18425 // Check for x CC y ? x : y.
18426 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
18427 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
18431 // Converting this to a min would handle NaNs incorrectly, and swapping
18432 // the operands would cause it to handle comparisons between positive
18433 // and negative zero incorrectly.
18434 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
18435 if (!DAG.getTarget().Options.UnsafeFPMath &&
18436 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
18438 std::swap(LHS, RHS);
18440 Opcode = X86ISD::FMIN;
18443 // Converting this to a min would handle comparisons between positive
18444 // and negative zero incorrectly.
18445 if (!DAG.getTarget().Options.UnsafeFPMath &&
18446 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
18448 Opcode = X86ISD::FMIN;
18451 // Converting this to a min would handle both negative zeros and NaNs
18452 // incorrectly, but we can swap the operands to fix both.
18453 std::swap(LHS, RHS);
18457 Opcode = X86ISD::FMIN;
18461 // Converting this to a max would handle comparisons between positive
18462 // and negative zero incorrectly.
18463 if (!DAG.getTarget().Options.UnsafeFPMath &&
18464 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
18466 Opcode = X86ISD::FMAX;
18469 // Converting this to a max would handle NaNs incorrectly, and swapping
18470 // the operands would cause it to handle comparisons between positive
18471 // and negative zero incorrectly.
18472 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
18473 if (!DAG.getTarget().Options.UnsafeFPMath &&
18474 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
18476 std::swap(LHS, RHS);
18478 Opcode = X86ISD::FMAX;
18481 // Converting this to a max would handle both negative zeros and NaNs
18482 // incorrectly, but we can swap the operands to fix both.
18483 std::swap(LHS, RHS);
18487 Opcode = X86ISD::FMAX;
18490 // Check for x CC y ? y : x -- a min/max with reversed arms.
18491 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
18492 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
18496 // Converting this to a min would handle comparisons between positive
18497 // and negative zero incorrectly, and swapping the operands would
18498 // cause it to handle NaNs incorrectly.
18499 if (!DAG.getTarget().Options.UnsafeFPMath &&
18500 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
18501 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
18503 std::swap(LHS, RHS);
18505 Opcode = X86ISD::FMIN;
18508 // Converting this to a min would handle NaNs incorrectly.
18509 if (!DAG.getTarget().Options.UnsafeFPMath &&
18510 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
18512 Opcode = X86ISD::FMIN;
18515 // Converting this to a min would handle both negative zeros and NaNs
18516 // incorrectly, but we can swap the operands to fix both.
18517 std::swap(LHS, RHS);
18521 Opcode = X86ISD::FMIN;
18525 // Converting this to a max would handle NaNs incorrectly.
18526 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
18528 Opcode = X86ISD::FMAX;
18531 // Converting this to a max would handle comparisons between positive
18532 // and negative zero incorrectly, and swapping the operands would
18533 // cause it to handle NaNs incorrectly.
18534 if (!DAG.getTarget().Options.UnsafeFPMath &&
18535 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
18536 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
18538 std::swap(LHS, RHS);
18540 Opcode = X86ISD::FMAX;
18543 // Converting this to a max would handle both negative zeros and NaNs
18544 // incorrectly, but we can swap the operands to fix both.
18545 std::swap(LHS, RHS);
18549 Opcode = X86ISD::FMAX;
18555 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
18558 EVT CondVT = Cond.getValueType();
18559 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
18560 CondVT.getVectorElementType() == MVT::i1) {
18561 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
18562 // lowering on AVX-512. In this case we convert it to
18563 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
18564 // The same situation for all 128 and 256-bit vectors of i8 and i16
18565 EVT OpVT = LHS.getValueType();
18566 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
18567 (OpVT.getVectorElementType() == MVT::i8 ||
18568 OpVT.getVectorElementType() == MVT::i16)) {
18569 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
18570 DCI.AddToWorklist(Cond.getNode());
18571 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
18574 // If this is a select between two integer constants, try to do some
18576 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
18577 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
18578 // Don't do this for crazy integer types.
18579 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
18580 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
18581 // so that TrueC (the true value) is larger than FalseC.
18582 bool NeedsCondInvert = false;
18584 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
18585 // Efficiently invertible.
18586 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
18587 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
18588 isa<ConstantSDNode>(Cond.getOperand(1))))) {
18589 NeedsCondInvert = true;
18590 std::swap(TrueC, FalseC);
18593 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
18594 if (FalseC->getAPIntValue() == 0 &&
18595 TrueC->getAPIntValue().isPowerOf2()) {
18596 if (NeedsCondInvert) // Invert the condition if needed.
18597 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18598 DAG.getConstant(1, Cond.getValueType()));
18600 // Zero extend the condition if needed.
18601 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
18603 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18604 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
18605 DAG.getConstant(ShAmt, MVT::i8));
18608 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
18609 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18610 if (NeedsCondInvert) // Invert the condition if needed.
18611 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18612 DAG.getConstant(1, Cond.getValueType()));
18614 // Zero extend the condition if needed.
18615 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18616 FalseC->getValueType(0), Cond);
18617 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18618 SDValue(FalseC, 0));
18621 // Optimize cases that will turn into an LEA instruction. This requires
18622 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18623 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18624 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18625 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18627 bool isFastMultiplier = false;
18629 switch ((unsigned char)Diff) {
18631 case 1: // result = add base, cond
18632 case 2: // result = lea base( , cond*2)
18633 case 3: // result = lea base(cond, cond*2)
18634 case 4: // result = lea base( , cond*4)
18635 case 5: // result = lea base(cond, cond*4)
18636 case 8: // result = lea base( , cond*8)
18637 case 9: // result = lea base(cond, cond*8)
18638 isFastMultiplier = true;
18643 if (isFastMultiplier) {
18644 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18645 if (NeedsCondInvert) // Invert the condition if needed.
18646 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18647 DAG.getConstant(1, Cond.getValueType()));
18649 // Zero extend the condition if needed.
18650 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18652 // Scale the condition by the difference.
18654 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18655 DAG.getConstant(Diff, Cond.getValueType()));
18657 // Add the base if non-zero.
18658 if (FalseC->getAPIntValue() != 0)
18659 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18660 SDValue(FalseC, 0));
18667 // Canonicalize max and min:
18668 // (x > y) ? x : y -> (x >= y) ? x : y
18669 // (x < y) ? x : y -> (x <= y) ? x : y
18670 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
18671 // the need for an extra compare
18672 // against zero. e.g.
18673 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
18675 // testl %edi, %edi
18677 // cmovgl %edi, %eax
18681 // cmovsl %eax, %edi
18682 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
18683 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
18684 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
18685 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18690 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
18691 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
18692 Cond.getOperand(0), Cond.getOperand(1), NewCC);
18693 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
18698 // Early exit check
18699 if (!TLI.isTypeLegal(VT))
18702 // Match VSELECTs into subs with unsigned saturation.
18703 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
18704 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
18705 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
18706 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
18707 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18709 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
18710 // left side invert the predicate to simplify logic below.
18712 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
18714 CC = ISD::getSetCCInverse(CC, true);
18715 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
18719 if (Other.getNode() && Other->getNumOperands() == 2 &&
18720 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
18721 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
18722 SDValue CondRHS = Cond->getOperand(1);
18724 // Look for a general sub with unsigned saturation first.
18725 // x >= y ? x-y : 0 --> subus x, y
18726 // x > y ? x-y : 0 --> subus x, y
18727 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
18728 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
18729 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
18731 // If the RHS is a constant we have to reverse the const canonicalization.
18732 // x > C-1 ? x+-C : 0 --> subus x, C
18733 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
18734 isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
18735 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
18736 if (CondRHS.getConstantOperandVal(0) == -A-1)
18737 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
18738 DAG.getConstant(-A, VT));
18741 // Another special case: If C was a sign bit, the sub has been
18742 // canonicalized into a xor.
18743 // FIXME: Would it be better to use computeKnownBits to determine whether
18744 // it's safe to decanonicalize the xor?
18745 // x s< 0 ? x^C : 0 --> subus x, C
18746 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
18747 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
18748 isSplatVector(OpRHS.getNode())) {
18749 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
18751 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
18756 // Try to match a min/max vector operation.
18757 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
18758 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
18759 unsigned Opc = ret.first;
18760 bool NeedSplit = ret.second;
18762 if (Opc && NeedSplit) {
18763 unsigned NumElems = VT.getVectorNumElements();
18764 // Extract the LHS vectors
18765 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
18766 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
18768 // Extract the RHS vectors
18769 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
18770 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
18772 // Create min/max for each subvector
18773 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
18774 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
18776 // Merge the result
18777 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
18779 return DAG.getNode(Opc, DL, VT, LHS, RHS);
18782 // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
18783 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
18784 // Check if SETCC has already been promoted
18785 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
18786 // Check that condition value type matches vselect operand type
18789 assert(Cond.getValueType().isVector() &&
18790 "vector select expects a vector selector!");
18792 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
18793 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
18795 if (!TValIsAllOnes && !FValIsAllZeros) {
18796 // Try invert the condition if true value is not all 1s and false value
18798 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
18799 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
18801 if (TValIsAllZeros || FValIsAllOnes) {
18802 SDValue CC = Cond.getOperand(2);
18803 ISD::CondCode NewCC =
18804 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
18805 Cond.getOperand(0).getValueType().isInteger());
18806 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
18807 std::swap(LHS, RHS);
18808 TValIsAllOnes = FValIsAllOnes;
18809 FValIsAllZeros = TValIsAllZeros;
18813 if (TValIsAllOnes || FValIsAllZeros) {
18816 if (TValIsAllOnes && FValIsAllZeros)
18818 else if (TValIsAllOnes)
18819 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
18820 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
18821 else if (FValIsAllZeros)
18822 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
18823 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
18825 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
18829 // Try to fold this VSELECT into a MOVSS/MOVSD
18830 if (N->getOpcode() == ISD::VSELECT &&
18831 Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
18832 if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
18833 (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
18834 bool CanFold = false;
18835 unsigned NumElems = Cond.getNumOperands();
18839 if (isZero(Cond.getOperand(0))) {
18842 // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
18843 // fold (vselect <0,-1> -> (movsd A, B)
18844 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
18845 CanFold = isAllOnes(Cond.getOperand(i));
18846 } else if (isAllOnes(Cond.getOperand(0))) {
18850 // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
18851 // fold (vselect <-1,0> -> (movsd B, A)
18852 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
18853 CanFold = isZero(Cond.getOperand(i));
18857 if (VT == MVT::v4i32 || VT == MVT::v4f32)
18858 return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
18859 return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
18862 if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
18863 // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
18864 // (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
18865 // (v2i64 (bitcast B)))))
18867 // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
18868 // (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
18869 // (v2f64 (bitcast B)))))
18871 // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
18872 // (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
18873 // (v2i64 (bitcast A)))))
18875 // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
18876 // (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
18877 // (v2f64 (bitcast A)))))
18879 CanFold = (isZero(Cond.getOperand(0)) &&
18880 isZero(Cond.getOperand(1)) &&
18881 isAllOnes(Cond.getOperand(2)) &&
18882 isAllOnes(Cond.getOperand(3)));
18884 if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
18885 isAllOnes(Cond.getOperand(1)) &&
18886 isZero(Cond.getOperand(2)) &&
18887 isZero(Cond.getOperand(3))) {
18889 std::swap(LHS, RHS);
18893 EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
18894 SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
18895 SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
18896 SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
18898 return DAG.getNode(ISD::BITCAST, DL, VT, Select);
18904 // If we know that this node is legal then we know that it is going to be
18905 // matched by one of the SSE/AVX BLEND instructions. These instructions only
18906 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
18907 // to simplify previous instructions.
18908 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
18909 !DCI.isBeforeLegalize() &&
18910 // We explicitly check against v8i16 and v16i16 because, although
18911 // they're marked as Custom, they might only be legal when Cond is a
18912 // build_vector of constants. This will be taken care in a later
18914 (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
18915 VT != MVT::v8i16)) {
18916 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
18918 // Don't optimize vector selects that map to mask-registers.
18922 // Check all uses of that condition operand to check whether it will be
18923 // consumed by non-BLEND instructions, which may depend on all bits are set
18925 for (SDNode::use_iterator I = Cond->use_begin(),
18926 E = Cond->use_end(); I != E; ++I)
18927 if (I->getOpcode() != ISD::VSELECT)
18928 // TODO: Add other opcodes eventually lowered into BLEND.
18931 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
18932 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
18934 APInt KnownZero, KnownOne;
18935 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
18936 DCI.isBeforeLegalizeOps());
18937 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
18938 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
18939 DCI.CommitTargetLoweringOpt(TLO);
18942 // We should generate an X86ISD::BLENDI from a vselect if its argument
18943 // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
18944 // constants. This specific pattern gets generated when we split a
18945 // selector for a 512 bit vector in a machine without AVX512 (but with
18946 // 256-bit vectors), during legalization:
18948 // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
18950 // Iff we find this pattern and the build_vectors are built from
18951 // constants, we translate the vselect into a shuffle_vector that we
18952 // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
18953 if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
18954 SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
18955 if (Shuffle.getNode())
18962 // Check whether a boolean test is testing a boolean value generated by
18963 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
18966 // Simplify the following patterns:
18967 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
18968 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
18969 // to (Op EFLAGS Cond)
18971 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
18972 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
18973 // to (Op EFLAGS !Cond)
18975 // where Op could be BRCOND or CMOV.
18977 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
18978 // Quit if not CMP and SUB with its value result used.
18979 if (Cmp.getOpcode() != X86ISD::CMP &&
18980 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
18983 // Quit if not used as a boolean value.
18984 if (CC != X86::COND_E && CC != X86::COND_NE)
18987 // Check CMP operands. One of them should be 0 or 1 and the other should be
18988 // an SetCC or extended from it.
18989 SDValue Op1 = Cmp.getOperand(0);
18990 SDValue Op2 = Cmp.getOperand(1);
18993 const ConstantSDNode* C = nullptr;
18994 bool needOppositeCond = (CC == X86::COND_E);
18995 bool checkAgainstTrue = false; // Is it a comparison against 1?
18997 if ((C = dyn_cast<ConstantSDNode>(Op1)))
18999 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
19001 else // Quit if all operands are not constants.
19004 if (C->getZExtValue() == 1) {
19005 needOppositeCond = !needOppositeCond;
19006 checkAgainstTrue = true;
19007 } else if (C->getZExtValue() != 0)
19008 // Quit if the constant is neither 0 or 1.
19011 bool truncatedToBoolWithAnd = false;
19012 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
19013 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
19014 SetCC.getOpcode() == ISD::TRUNCATE ||
19015 SetCC.getOpcode() == ISD::AND) {
19016 if (SetCC.getOpcode() == ISD::AND) {
19018 ConstantSDNode *CS;
19019 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
19020 CS->getZExtValue() == 1)
19022 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
19023 CS->getZExtValue() == 1)
19027 SetCC = SetCC.getOperand(OpIdx);
19028 truncatedToBoolWithAnd = true;
19030 SetCC = SetCC.getOperand(0);
19033 switch (SetCC.getOpcode()) {
19034 case X86ISD::SETCC_CARRY:
19035 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
19036 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
19037 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
19038 // truncated to i1 using 'and'.
19039 if (checkAgainstTrue && !truncatedToBoolWithAnd)
19041 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
19042 "Invalid use of SETCC_CARRY!");
19044 case X86ISD::SETCC:
19045 // Set the condition code or opposite one if necessary.
19046 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
19047 if (needOppositeCond)
19048 CC = X86::GetOppositeBranchCondition(CC);
19049 return SetCC.getOperand(1);
19050 case X86ISD::CMOV: {
19051 // Check whether false/true value has canonical one, i.e. 0 or 1.
19052 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
19053 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
19054 // Quit if true value is not a constant.
19057 // Quit if false value is not a constant.
19059 SDValue Op = SetCC.getOperand(0);
19060 // Skip 'zext' or 'trunc' node.
19061 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
19062 Op.getOpcode() == ISD::TRUNCATE)
19063 Op = Op.getOperand(0);
19064 // A special case for rdrand/rdseed, where 0 is set if false cond is
19066 if ((Op.getOpcode() != X86ISD::RDRAND &&
19067 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
19070 // Quit if false value is not the constant 0 or 1.
19071 bool FValIsFalse = true;
19072 if (FVal && FVal->getZExtValue() != 0) {
19073 if (FVal->getZExtValue() != 1)
19075 // If FVal is 1, opposite cond is needed.
19076 needOppositeCond = !needOppositeCond;
19077 FValIsFalse = false;
19079 // Quit if TVal is not the constant opposite of FVal.
19080 if (FValIsFalse && TVal->getZExtValue() != 1)
19082 if (!FValIsFalse && TVal->getZExtValue() != 0)
19084 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
19085 if (needOppositeCond)
19086 CC = X86::GetOppositeBranchCondition(CC);
19087 return SetCC.getOperand(3);
19094 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
19095 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
19096 TargetLowering::DAGCombinerInfo &DCI,
19097 const X86Subtarget *Subtarget) {
19100 // If the flag operand isn't dead, don't touch this CMOV.
19101 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
19104 SDValue FalseOp = N->getOperand(0);
19105 SDValue TrueOp = N->getOperand(1);
19106 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
19107 SDValue Cond = N->getOperand(3);
19109 if (CC == X86::COND_E || CC == X86::COND_NE) {
19110 switch (Cond.getOpcode()) {
19114 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
19115 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
19116 return (CC == X86::COND_E) ? FalseOp : TrueOp;
19122 Flags = checkBoolTestSetCCCombine(Cond, CC);
19123 if (Flags.getNode() &&
19124 // Extra check as FCMOV only supports a subset of X86 cond.
19125 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
19126 SDValue Ops[] = { FalseOp, TrueOp,
19127 DAG.getConstant(CC, MVT::i8), Flags };
19128 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
19131 // If this is a select between two integer constants, try to do some
19132 // optimizations. Note that the operands are ordered the opposite of SELECT
19134 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
19135 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
19136 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
19137 // larger than FalseC (the false value).
19138 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
19139 CC = X86::GetOppositeBranchCondition(CC);
19140 std::swap(TrueC, FalseC);
19141 std::swap(TrueOp, FalseOp);
19144 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
19145 // This is efficient for any integer data type (including i8/i16) and
19147 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
19148 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
19149 DAG.getConstant(CC, MVT::i8), Cond);
19151 // Zero extend the condition if needed.
19152 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
19154 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
19155 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
19156 DAG.getConstant(ShAmt, MVT::i8));
19157 if (N->getNumValues() == 2) // Dead flag value?
19158 return DCI.CombineTo(N, Cond, SDValue());
19162 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
19163 // for any integer data type, including i8/i16.
19164 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
19165 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
19166 DAG.getConstant(CC, MVT::i8), Cond);
19168 // Zero extend the condition if needed.
19169 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
19170 FalseC->getValueType(0), Cond);
19171 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19172 SDValue(FalseC, 0));
19174 if (N->getNumValues() == 2) // Dead flag value?
19175 return DCI.CombineTo(N, Cond, SDValue());
19179 // Optimize cases that will turn into an LEA instruction. This requires
19180 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
19181 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
19182 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
19183 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
19185 bool isFastMultiplier = false;
19187 switch ((unsigned char)Diff) {
19189 case 1: // result = add base, cond
19190 case 2: // result = lea base( , cond*2)
19191 case 3: // result = lea base(cond, cond*2)
19192 case 4: // result = lea base( , cond*4)
19193 case 5: // result = lea base(cond, cond*4)
19194 case 8: // result = lea base( , cond*8)
19195 case 9: // result = lea base(cond, cond*8)
19196 isFastMultiplier = true;
19201 if (isFastMultiplier) {
19202 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
19203 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
19204 DAG.getConstant(CC, MVT::i8), Cond);
19205 // Zero extend the condition if needed.
19206 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
19208 // Scale the condition by the difference.
19210 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
19211 DAG.getConstant(Diff, Cond.getValueType()));
19213 // Add the base if non-zero.
19214 if (FalseC->getAPIntValue() != 0)
19215 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19216 SDValue(FalseC, 0));
19217 if (N->getNumValues() == 2) // Dead flag value?
19218 return DCI.CombineTo(N, Cond, SDValue());
19225 // Handle these cases:
19226 // (select (x != c), e, c) -> select (x != c), e, x),
19227 // (select (x == c), c, e) -> select (x == c), x, e)
19228 // where the c is an integer constant, and the "select" is the combination
19229 // of CMOV and CMP.
19231 // The rationale for this change is that the conditional-move from a constant
19232 // needs two instructions, however, conditional-move from a register needs
19233 // only one instruction.
19235 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
19236 // some instruction-combining opportunities. This opt needs to be
19237 // postponed as late as possible.
19239 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
19240 // the DCI.xxxx conditions are provided to postpone the optimization as
19241 // late as possible.
19243 ConstantSDNode *CmpAgainst = nullptr;
19244 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
19245 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
19246 !isa<ConstantSDNode>(Cond.getOperand(0))) {
19248 if (CC == X86::COND_NE &&
19249 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
19250 CC = X86::GetOppositeBranchCondition(CC);
19251 std::swap(TrueOp, FalseOp);
19254 if (CC == X86::COND_E &&
19255 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
19256 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
19257 DAG.getConstant(CC, MVT::i8), Cond };
19258 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
19266 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
19267 const X86Subtarget *Subtarget) {
19268 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
19270 default: return SDValue();
19271 // SSE/AVX/AVX2 blend intrinsics.
19272 case Intrinsic::x86_avx2_pblendvb:
19273 case Intrinsic::x86_avx2_pblendw:
19274 case Intrinsic::x86_avx2_pblendd_128:
19275 case Intrinsic::x86_avx2_pblendd_256:
19276 // Don't try to simplify this intrinsic if we don't have AVX2.
19277 if (!Subtarget->hasAVX2())
19280 case Intrinsic::x86_avx_blend_pd_256:
19281 case Intrinsic::x86_avx_blend_ps_256:
19282 case Intrinsic::x86_avx_blendv_pd_256:
19283 case Intrinsic::x86_avx_blendv_ps_256:
19284 // Don't try to simplify this intrinsic if we don't have AVX.
19285 if (!Subtarget->hasAVX())
19288 case Intrinsic::x86_sse41_pblendw:
19289 case Intrinsic::x86_sse41_blendpd:
19290 case Intrinsic::x86_sse41_blendps:
19291 case Intrinsic::x86_sse41_blendvps:
19292 case Intrinsic::x86_sse41_blendvpd:
19293 case Intrinsic::x86_sse41_pblendvb: {
19294 SDValue Op0 = N->getOperand(1);
19295 SDValue Op1 = N->getOperand(2);
19296 SDValue Mask = N->getOperand(3);
19298 // Don't try to simplify this intrinsic if we don't have SSE4.1.
19299 if (!Subtarget->hasSSE41())
19302 // fold (blend A, A, Mask) -> A
19305 // fold (blend A, B, allZeros) -> A
19306 if (ISD::isBuildVectorAllZeros(Mask.getNode()))
19308 // fold (blend A, B, allOnes) -> B
19309 if (ISD::isBuildVectorAllOnes(Mask.getNode()))
19312 // Simplify the case where the mask is a constant i32 value.
19313 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
19314 if (C->isNullValue())
19316 if (C->isAllOnesValue())
19323 // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
19324 case Intrinsic::x86_sse2_psrai_w:
19325 case Intrinsic::x86_sse2_psrai_d:
19326 case Intrinsic::x86_avx2_psrai_w:
19327 case Intrinsic::x86_avx2_psrai_d:
19328 case Intrinsic::x86_sse2_psra_w:
19329 case Intrinsic::x86_sse2_psra_d:
19330 case Intrinsic::x86_avx2_psra_w:
19331 case Intrinsic::x86_avx2_psra_d: {
19332 SDValue Op0 = N->getOperand(1);
19333 SDValue Op1 = N->getOperand(2);
19334 EVT VT = Op0.getValueType();
19335 assert(VT.isVector() && "Expected a vector type!");
19337 if (isa<BuildVectorSDNode>(Op1))
19338 Op1 = Op1.getOperand(0);
19340 if (!isa<ConstantSDNode>(Op1))
19343 EVT SVT = VT.getVectorElementType();
19344 unsigned SVTBits = SVT.getSizeInBits();
19346 ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
19347 const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
19348 uint64_t ShAmt = C.getZExtValue();
19350 // Don't try to convert this shift into a ISD::SRA if the shift
19351 // count is bigger than or equal to the element size.
19352 if (ShAmt >= SVTBits)
19355 // Trivial case: if the shift count is zero, then fold this
19356 // into the first operand.
19360 // Replace this packed shift intrinsic with a target independent
19362 SDValue Splat = DAG.getConstant(C, VT);
19363 return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
19368 /// PerformMulCombine - Optimize a single multiply with constant into two
19369 /// in order to implement it with two cheaper instructions, e.g.
19370 /// LEA + SHL, LEA + LEA.
19371 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
19372 TargetLowering::DAGCombinerInfo &DCI) {
19373 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
19376 EVT VT = N->getValueType(0);
19377 if (VT != MVT::i64)
19380 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
19383 uint64_t MulAmt = C->getZExtValue();
19384 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
19387 uint64_t MulAmt1 = 0;
19388 uint64_t MulAmt2 = 0;
19389 if ((MulAmt % 9) == 0) {
19391 MulAmt2 = MulAmt / 9;
19392 } else if ((MulAmt % 5) == 0) {
19394 MulAmt2 = MulAmt / 5;
19395 } else if ((MulAmt % 3) == 0) {
19397 MulAmt2 = MulAmt / 3;
19400 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
19403 if (isPowerOf2_64(MulAmt2) &&
19404 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
19405 // If second multiplifer is pow2, issue it first. We want the multiply by
19406 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
19408 std::swap(MulAmt1, MulAmt2);
19411 if (isPowerOf2_64(MulAmt1))
19412 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
19413 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
19415 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
19416 DAG.getConstant(MulAmt1, VT));
19418 if (isPowerOf2_64(MulAmt2))
19419 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
19420 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
19422 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
19423 DAG.getConstant(MulAmt2, VT));
19425 // Do not add new nodes to DAG combiner worklist.
19426 DCI.CombineTo(N, NewMul, false);
19431 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
19432 SDValue N0 = N->getOperand(0);
19433 SDValue N1 = N->getOperand(1);
19434 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
19435 EVT VT = N0.getValueType();
19437 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
19438 // since the result of setcc_c is all zero's or all ones.
19439 if (VT.isInteger() && !VT.isVector() &&
19440 N1C && N0.getOpcode() == ISD::AND &&
19441 N0.getOperand(1).getOpcode() == ISD::Constant) {
19442 SDValue N00 = N0.getOperand(0);
19443 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
19444 ((N00.getOpcode() == ISD::ANY_EXTEND ||
19445 N00.getOpcode() == ISD::ZERO_EXTEND) &&
19446 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
19447 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
19448 APInt ShAmt = N1C->getAPIntValue();
19449 Mask = Mask.shl(ShAmt);
19451 return DAG.getNode(ISD::AND, SDLoc(N), VT,
19452 N00, DAG.getConstant(Mask, VT));
19456 // Hardware support for vector shifts is sparse which makes us scalarize the
19457 // vector operations in many cases. Also, on sandybridge ADD is faster than
19459 // (shl V, 1) -> add V,V
19460 if (isSplatVector(N1.getNode())) {
19461 assert(N0.getValueType().isVector() && "Invalid vector shift type");
19462 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
19463 // We shift all of the values by one. In many cases we do not have
19464 // hardware support for this operation. This is better expressed as an ADD
19466 if (N1C && (1 == N1C->getZExtValue())) {
19467 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
19474 /// \brief Returns a vector of 0s if the node in input is a vector logical
19475 /// shift by a constant amount which is known to be bigger than or equal
19476 /// to the vector element size in bits.
19477 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
19478 const X86Subtarget *Subtarget) {
19479 EVT VT = N->getValueType(0);
19481 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
19482 (!Subtarget->hasInt256() ||
19483 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
19486 SDValue Amt = N->getOperand(1);
19488 if (isSplatVector(Amt.getNode())) {
19489 SDValue SclrAmt = Amt->getOperand(0);
19490 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
19491 APInt ShiftAmt = C->getAPIntValue();
19492 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
19494 // SSE2/AVX2 logical shifts always return a vector of 0s
19495 // if the shift amount is bigger than or equal to
19496 // the element size. The constant shift amount will be
19497 // encoded as a 8-bit immediate.
19498 if (ShiftAmt.trunc(8).uge(MaxAmount))
19499 return getZeroVector(VT, Subtarget, DAG, DL);
19506 /// PerformShiftCombine - Combine shifts.
19507 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
19508 TargetLowering::DAGCombinerInfo &DCI,
19509 const X86Subtarget *Subtarget) {
19510 if (N->getOpcode() == ISD::SHL) {
19511 SDValue V = PerformSHLCombine(N, DAG);
19512 if (V.getNode()) return V;
19515 if (N->getOpcode() != ISD::SRA) {
19516 // Try to fold this logical shift into a zero vector.
19517 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
19518 if (V.getNode()) return V;
19524 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
19525 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
19526 // and friends. Likewise for OR -> CMPNEQSS.
19527 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
19528 TargetLowering::DAGCombinerInfo &DCI,
19529 const X86Subtarget *Subtarget) {
19532 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
19533 // we're requiring SSE2 for both.
19534 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
19535 SDValue N0 = N->getOperand(0);
19536 SDValue N1 = N->getOperand(1);
19537 SDValue CMP0 = N0->getOperand(1);
19538 SDValue CMP1 = N1->getOperand(1);
19541 // The SETCCs should both refer to the same CMP.
19542 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
19545 SDValue CMP00 = CMP0->getOperand(0);
19546 SDValue CMP01 = CMP0->getOperand(1);
19547 EVT VT = CMP00.getValueType();
19549 if (VT == MVT::f32 || VT == MVT::f64) {
19550 bool ExpectingFlags = false;
19551 // Check for any users that want flags:
19552 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
19553 !ExpectingFlags && UI != UE; ++UI)
19554 switch (UI->getOpcode()) {
19559 ExpectingFlags = true;
19561 case ISD::CopyToReg:
19562 case ISD::SIGN_EXTEND:
19563 case ISD::ZERO_EXTEND:
19564 case ISD::ANY_EXTEND:
19568 if (!ExpectingFlags) {
19569 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
19570 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
19572 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
19573 X86::CondCode tmp = cc0;
19578 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
19579 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
19580 // FIXME: need symbolic constants for these magic numbers.
19581 // See X86ATTInstPrinter.cpp:printSSECC().
19582 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
19583 if (Subtarget->hasAVX512()) {
19584 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
19585 CMP01, DAG.getConstant(x86cc, MVT::i8));
19586 if (N->getValueType(0) != MVT::i1)
19587 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
19591 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
19592 CMP00.getValueType(), CMP00, CMP01,
19593 DAG.getConstant(x86cc, MVT::i8));
19595 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
19596 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
19598 if (is64BitFP && !Subtarget->is64Bit()) {
19599 // On a 32-bit target, we cannot bitcast the 64-bit float to a
19600 // 64-bit integer, since that's not a legal type. Since
19601 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
19602 // bits, but can do this little dance to extract the lowest 32 bits
19603 // and work with those going forward.
19604 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
19606 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
19608 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
19609 Vector32, DAG.getIntPtrConstant(0));
19613 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
19614 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
19615 DAG.getConstant(1, IntVT));
19616 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
19617 return OneBitOfTruth;
19625 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
19626 /// so it can be folded inside ANDNP.
19627 static bool CanFoldXORWithAllOnes(const SDNode *N) {
19628 EVT VT = N->getValueType(0);
19630 // Match direct AllOnes for 128 and 256-bit vectors
19631 if (ISD::isBuildVectorAllOnes(N))
19634 // Look through a bit convert.
19635 if (N->getOpcode() == ISD::BITCAST)
19636 N = N->getOperand(0).getNode();
19638 // Sometimes the operand may come from a insert_subvector building a 256-bit
19640 if (VT.is256BitVector() &&
19641 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
19642 SDValue V1 = N->getOperand(0);
19643 SDValue V2 = N->getOperand(1);
19645 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
19646 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
19647 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
19648 ISD::isBuildVectorAllOnes(V2.getNode()))
19655 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
19656 // register. In most cases we actually compare or select YMM-sized registers
19657 // and mixing the two types creates horrible code. This method optimizes
19658 // some of the transition sequences.
19659 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
19660 TargetLowering::DAGCombinerInfo &DCI,
19661 const X86Subtarget *Subtarget) {
19662 EVT VT = N->getValueType(0);
19663 if (!VT.is256BitVector())
19666 assert((N->getOpcode() == ISD::ANY_EXTEND ||
19667 N->getOpcode() == ISD::ZERO_EXTEND ||
19668 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
19670 SDValue Narrow = N->getOperand(0);
19671 EVT NarrowVT = Narrow->getValueType(0);
19672 if (!NarrowVT.is128BitVector())
19675 if (Narrow->getOpcode() != ISD::XOR &&
19676 Narrow->getOpcode() != ISD::AND &&
19677 Narrow->getOpcode() != ISD::OR)
19680 SDValue N0 = Narrow->getOperand(0);
19681 SDValue N1 = Narrow->getOperand(1);
19684 // The Left side has to be a trunc.
19685 if (N0.getOpcode() != ISD::TRUNCATE)
19688 // The type of the truncated inputs.
19689 EVT WideVT = N0->getOperand(0)->getValueType(0);
19693 // The right side has to be a 'trunc' or a constant vector.
19694 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
19695 bool RHSConst = (isSplatVector(N1.getNode()) &&
19696 isa<ConstantSDNode>(N1->getOperand(0)));
19697 if (!RHSTrunc && !RHSConst)
19700 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19702 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
19705 // Set N0 and N1 to hold the inputs to the new wide operation.
19706 N0 = N0->getOperand(0);
19708 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
19709 N1->getOperand(0));
19710 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
19711 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
19712 } else if (RHSTrunc) {
19713 N1 = N1->getOperand(0);
19716 // Generate the wide operation.
19717 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
19718 unsigned Opcode = N->getOpcode();
19720 case ISD::ANY_EXTEND:
19722 case ISD::ZERO_EXTEND: {
19723 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
19724 APInt Mask = APInt::getAllOnesValue(InBits);
19725 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
19726 return DAG.getNode(ISD::AND, DL, VT,
19727 Op, DAG.getConstant(Mask, VT));
19729 case ISD::SIGN_EXTEND:
19730 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
19731 Op, DAG.getValueType(NarrowVT));
19733 llvm_unreachable("Unexpected opcode");
19737 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
19738 TargetLowering::DAGCombinerInfo &DCI,
19739 const X86Subtarget *Subtarget) {
19740 EVT VT = N->getValueType(0);
19741 if (DCI.isBeforeLegalizeOps())
19744 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
19748 // Create BEXTR instructions
19749 // BEXTR is ((X >> imm) & (2**size-1))
19750 if (VT == MVT::i32 || VT == MVT::i64) {
19751 SDValue N0 = N->getOperand(0);
19752 SDValue N1 = N->getOperand(1);
19755 // Check for BEXTR.
19756 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
19757 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
19758 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
19759 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19760 if (MaskNode && ShiftNode) {
19761 uint64_t Mask = MaskNode->getZExtValue();
19762 uint64_t Shift = ShiftNode->getZExtValue();
19763 if (isMask_64(Mask)) {
19764 uint64_t MaskSize = CountPopulation_64(Mask);
19765 if (Shift + MaskSize <= VT.getSizeInBits())
19766 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
19767 DAG.getConstant(Shift | (MaskSize << 8), VT));
19775 // Want to form ANDNP nodes:
19776 // 1) In the hopes of then easily combining them with OR and AND nodes
19777 // to form PBLEND/PSIGN.
19778 // 2) To match ANDN packed intrinsics
19779 if (VT != MVT::v2i64 && VT != MVT::v4i64)
19782 SDValue N0 = N->getOperand(0);
19783 SDValue N1 = N->getOperand(1);
19786 // Check LHS for vnot
19787 if (N0.getOpcode() == ISD::XOR &&
19788 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
19789 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
19790 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
19792 // Check RHS for vnot
19793 if (N1.getOpcode() == ISD::XOR &&
19794 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
19795 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
19796 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
19801 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
19802 TargetLowering::DAGCombinerInfo &DCI,
19803 const X86Subtarget *Subtarget) {
19804 if (DCI.isBeforeLegalizeOps())
19807 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
19811 SDValue N0 = N->getOperand(0);
19812 SDValue N1 = N->getOperand(1);
19813 EVT VT = N->getValueType(0);
19815 // look for psign/blend
19816 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
19817 if (!Subtarget->hasSSSE3() ||
19818 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
19821 // Canonicalize pandn to RHS
19822 if (N0.getOpcode() == X86ISD::ANDNP)
19824 // or (and (m, y), (pandn m, x))
19825 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
19826 SDValue Mask = N1.getOperand(0);
19827 SDValue X = N1.getOperand(1);
19829 if (N0.getOperand(0) == Mask)
19830 Y = N0.getOperand(1);
19831 if (N0.getOperand(1) == Mask)
19832 Y = N0.getOperand(0);
19834 // Check to see if the mask appeared in both the AND and ANDNP and
19838 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
19839 // Look through mask bitcast.
19840 if (Mask.getOpcode() == ISD::BITCAST)
19841 Mask = Mask.getOperand(0);
19842 if (X.getOpcode() == ISD::BITCAST)
19843 X = X.getOperand(0);
19844 if (Y.getOpcode() == ISD::BITCAST)
19845 Y = Y.getOperand(0);
19847 EVT MaskVT = Mask.getValueType();
19849 // Validate that the Mask operand is a vector sra node.
19850 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
19851 // there is no psrai.b
19852 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
19853 unsigned SraAmt = ~0;
19854 if (Mask.getOpcode() == ISD::SRA) {
19855 SDValue Amt = Mask.getOperand(1);
19856 if (isSplatVector(Amt.getNode())) {
19857 SDValue SclrAmt = Amt->getOperand(0);
19858 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
19859 SraAmt = C->getZExtValue();
19861 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
19862 SDValue SraC = Mask.getOperand(1);
19863 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
19865 if ((SraAmt + 1) != EltBits)
19870 // Now we know we at least have a plendvb with the mask val. See if
19871 // we can form a psignb/w/d.
19872 // psign = x.type == y.type == mask.type && y = sub(0, x);
19873 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
19874 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
19875 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
19876 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
19877 "Unsupported VT for PSIGN");
19878 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
19879 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
19881 // PBLENDVB only available on SSE 4.1
19882 if (!Subtarget->hasSSE41())
19885 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
19887 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
19888 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
19889 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
19890 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
19891 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
19895 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
19898 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
19899 MachineFunction &MF = DAG.getMachineFunction();
19900 bool OptForSize = MF.getFunction()->getAttributes().
19901 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
19903 // SHLD/SHRD instructions have lower register pressure, but on some
19904 // platforms they have higher latency than the equivalent
19905 // series of shifts/or that would otherwise be generated.
19906 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
19907 // have higher latencies and we are not optimizing for size.
19908 if (!OptForSize && Subtarget->isSHLDSlow())
19911 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
19913 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
19915 if (!N0.hasOneUse() || !N1.hasOneUse())
19918 SDValue ShAmt0 = N0.getOperand(1);
19919 if (ShAmt0.getValueType() != MVT::i8)
19921 SDValue ShAmt1 = N1.getOperand(1);
19922 if (ShAmt1.getValueType() != MVT::i8)
19924 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
19925 ShAmt0 = ShAmt0.getOperand(0);
19926 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
19927 ShAmt1 = ShAmt1.getOperand(0);
19930 unsigned Opc = X86ISD::SHLD;
19931 SDValue Op0 = N0.getOperand(0);
19932 SDValue Op1 = N1.getOperand(0);
19933 if (ShAmt0.getOpcode() == ISD::SUB) {
19934 Opc = X86ISD::SHRD;
19935 std::swap(Op0, Op1);
19936 std::swap(ShAmt0, ShAmt1);
19939 unsigned Bits = VT.getSizeInBits();
19940 if (ShAmt1.getOpcode() == ISD::SUB) {
19941 SDValue Sum = ShAmt1.getOperand(0);
19942 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
19943 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
19944 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
19945 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
19946 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
19947 return DAG.getNode(Opc, DL, VT,
19949 DAG.getNode(ISD::TRUNCATE, DL,
19952 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
19953 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
19955 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
19956 return DAG.getNode(Opc, DL, VT,
19957 N0.getOperand(0), N1.getOperand(0),
19958 DAG.getNode(ISD::TRUNCATE, DL,
19965 // Generate NEG and CMOV for integer abs.
19966 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
19967 EVT VT = N->getValueType(0);
19969 // Since X86 does not have CMOV for 8-bit integer, we don't convert
19970 // 8-bit integer abs to NEG and CMOV.
19971 if (VT.isInteger() && VT.getSizeInBits() == 8)
19974 SDValue N0 = N->getOperand(0);
19975 SDValue N1 = N->getOperand(1);
19978 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
19979 // and change it to SUB and CMOV.
19980 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
19981 N0.getOpcode() == ISD::ADD &&
19982 N0.getOperand(1) == N1 &&
19983 N1.getOpcode() == ISD::SRA &&
19984 N1.getOperand(0) == N0.getOperand(0))
19985 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
19986 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
19987 // Generate SUB & CMOV.
19988 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
19989 DAG.getConstant(0, VT), N0.getOperand(0));
19991 SDValue Ops[] = { N0.getOperand(0), Neg,
19992 DAG.getConstant(X86::COND_GE, MVT::i8),
19993 SDValue(Neg.getNode(), 1) };
19994 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
19999 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
20000 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
20001 TargetLowering::DAGCombinerInfo &DCI,
20002 const X86Subtarget *Subtarget) {
20003 if (DCI.isBeforeLegalizeOps())
20006 if (Subtarget->hasCMov()) {
20007 SDValue RV = performIntegerAbsCombine(N, DAG);
20015 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
20016 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
20017 TargetLowering::DAGCombinerInfo &DCI,
20018 const X86Subtarget *Subtarget) {
20019 LoadSDNode *Ld = cast<LoadSDNode>(N);
20020 EVT RegVT = Ld->getValueType(0);
20021 EVT MemVT = Ld->getMemoryVT();
20023 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20024 unsigned RegSz = RegVT.getSizeInBits();
20026 // On Sandybridge unaligned 256bit loads are inefficient.
20027 ISD::LoadExtType Ext = Ld->getExtensionType();
20028 unsigned Alignment = Ld->getAlignment();
20029 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
20030 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
20031 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
20032 unsigned NumElems = RegVT.getVectorNumElements();
20036 SDValue Ptr = Ld->getBasePtr();
20037 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
20039 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
20041 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
20042 Ld->getPointerInfo(), Ld->isVolatile(),
20043 Ld->isNonTemporal(), Ld->isInvariant(),
20045 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
20046 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
20047 Ld->getPointerInfo(), Ld->isVolatile(),
20048 Ld->isNonTemporal(), Ld->isInvariant(),
20049 std::min(16U, Alignment));
20050 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
20052 Load2.getValue(1));
20054 SDValue NewVec = DAG.getUNDEF(RegVT);
20055 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
20056 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
20057 return DCI.CombineTo(N, NewVec, TF, true);
20060 // If this is a vector EXT Load then attempt to optimize it using a
20061 // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
20062 // expansion is still better than scalar code.
20063 // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
20064 // emit a shuffle and a arithmetic shift.
20065 // TODO: It is possible to support ZExt by zeroing the undef values
20066 // during the shuffle phase or after the shuffle.
20067 if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
20068 (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
20069 assert(MemVT != RegVT && "Cannot extend to the same type");
20070 assert(MemVT.isVector() && "Must load a vector from memory");
20072 unsigned NumElems = RegVT.getVectorNumElements();
20073 unsigned MemSz = MemVT.getSizeInBits();
20074 assert(RegSz > MemSz && "Register size must be greater than the mem size");
20076 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
20079 // All sizes must be a power of two.
20080 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
20083 // Attempt to load the original value using scalar loads.
20084 // Find the largest scalar type that divides the total loaded size.
20085 MVT SclrLoadTy = MVT::i8;
20086 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
20087 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
20088 MVT Tp = (MVT::SimpleValueType)tp;
20089 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
20094 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
20095 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
20097 SclrLoadTy = MVT::f64;
20099 // Calculate the number of scalar loads that we need to perform
20100 // in order to load our vector from memory.
20101 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
20102 if (Ext == ISD::SEXTLOAD && NumLoads > 1)
20105 unsigned loadRegZize = RegSz;
20106 if (Ext == ISD::SEXTLOAD && RegSz == 256)
20109 // Represent our vector as a sequence of elements which are the
20110 // largest scalar that we can load.
20111 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
20112 loadRegZize/SclrLoadTy.getSizeInBits());
20114 // Represent the data using the same element type that is stored in
20115 // memory. In practice, we ''widen'' MemVT.
20117 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
20118 loadRegZize/MemVT.getScalarType().getSizeInBits());
20120 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
20121 "Invalid vector type");
20123 // We can't shuffle using an illegal type.
20124 if (!TLI.isTypeLegal(WideVecVT))
20127 SmallVector<SDValue, 8> Chains;
20128 SDValue Ptr = Ld->getBasePtr();
20129 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
20130 TLI.getPointerTy());
20131 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
20133 for (unsigned i = 0; i < NumLoads; ++i) {
20134 // Perform a single load.
20135 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
20136 Ptr, Ld->getPointerInfo(),
20137 Ld->isVolatile(), Ld->isNonTemporal(),
20138 Ld->isInvariant(), Ld->getAlignment());
20139 Chains.push_back(ScalarLoad.getValue(1));
20140 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
20141 // another round of DAGCombining.
20143 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
20145 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
20146 ScalarLoad, DAG.getIntPtrConstant(i));
20148 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
20151 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
20153 // Bitcast the loaded value to a vector of the original element type, in
20154 // the size of the target vector type.
20155 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
20156 unsigned SizeRatio = RegSz/MemSz;
20158 if (Ext == ISD::SEXTLOAD) {
20159 // If we have SSE4.1 we can directly emit a VSEXT node.
20160 if (Subtarget->hasSSE41()) {
20161 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
20162 return DCI.CombineTo(N, Sext, TF, true);
20165 // Otherwise we'll shuffle the small elements in the high bits of the
20166 // larger type and perform an arithmetic shift. If the shift is not legal
20167 // it's better to scalarize.
20168 if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
20171 // Redistribute the loaded elements into the different locations.
20172 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
20173 for (unsigned i = 0; i != NumElems; ++i)
20174 ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
20176 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
20177 DAG.getUNDEF(WideVecVT),
20180 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
20182 // Build the arithmetic shift.
20183 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
20184 MemVT.getVectorElementType().getSizeInBits();
20185 Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
20186 DAG.getConstant(Amt, RegVT));
20188 return DCI.CombineTo(N, Shuff, TF, true);
20191 // Redistribute the loaded elements into the different locations.
20192 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
20193 for (unsigned i = 0; i != NumElems; ++i)
20194 ShuffleVec[i*SizeRatio] = i;
20196 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
20197 DAG.getUNDEF(WideVecVT),
20200 // Bitcast to the requested type.
20201 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
20202 // Replace the original load with the new sequence
20203 // and return the new chain.
20204 return DCI.CombineTo(N, Shuff, TF, true);
20210 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
20211 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
20212 const X86Subtarget *Subtarget) {
20213 StoreSDNode *St = cast<StoreSDNode>(N);
20214 EVT VT = St->getValue().getValueType();
20215 EVT StVT = St->getMemoryVT();
20217 SDValue StoredVal = St->getOperand(1);
20218 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20220 // If we are saving a concatenation of two XMM registers, perform two stores.
20221 // On Sandy Bridge, 256-bit memory operations are executed by two
20222 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
20223 // memory operation.
20224 unsigned Alignment = St->getAlignment();
20225 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
20226 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
20227 StVT == VT && !IsAligned) {
20228 unsigned NumElems = VT.getVectorNumElements();
20232 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
20233 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
20235 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
20236 SDValue Ptr0 = St->getBasePtr();
20237 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
20239 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
20240 St->getPointerInfo(), St->isVolatile(),
20241 St->isNonTemporal(), Alignment);
20242 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
20243 St->getPointerInfo(), St->isVolatile(),
20244 St->isNonTemporal(),
20245 std::min(16U, Alignment));
20246 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
20249 // Optimize trunc store (of multiple scalars) to shuffle and store.
20250 // First, pack all of the elements in one place. Next, store to memory
20251 // in fewer chunks.
20252 if (St->isTruncatingStore() && VT.isVector()) {
20253 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20254 unsigned NumElems = VT.getVectorNumElements();
20255 assert(StVT != VT && "Cannot truncate to the same type");
20256 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
20257 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
20259 // From, To sizes and ElemCount must be pow of two
20260 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
20261 // We are going to use the original vector elt for storing.
20262 // Accumulated smaller vector elements must be a multiple of the store size.
20263 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
20265 unsigned SizeRatio = FromSz / ToSz;
20267 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
20269 // Create a type on which we perform the shuffle
20270 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
20271 StVT.getScalarType(), NumElems*SizeRatio);
20273 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
20275 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
20276 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
20277 for (unsigned i = 0; i != NumElems; ++i)
20278 ShuffleVec[i] = i * SizeRatio;
20280 // Can't shuffle using an illegal type.
20281 if (!TLI.isTypeLegal(WideVecVT))
20284 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
20285 DAG.getUNDEF(WideVecVT),
20287 // At this point all of the data is stored at the bottom of the
20288 // register. We now need to save it to mem.
20290 // Find the largest store unit
20291 MVT StoreType = MVT::i8;
20292 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
20293 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
20294 MVT Tp = (MVT::SimpleValueType)tp;
20295 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
20299 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
20300 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
20301 (64 <= NumElems * ToSz))
20302 StoreType = MVT::f64;
20304 // Bitcast the original vector into a vector of store-size units
20305 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
20306 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
20307 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
20308 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
20309 SmallVector<SDValue, 8> Chains;
20310 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
20311 TLI.getPointerTy());
20312 SDValue Ptr = St->getBasePtr();
20314 // Perform one or more big stores into memory.
20315 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
20316 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
20317 StoreType, ShuffWide,
20318 DAG.getIntPtrConstant(i));
20319 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
20320 St->getPointerInfo(), St->isVolatile(),
20321 St->isNonTemporal(), St->getAlignment());
20322 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
20323 Chains.push_back(Ch);
20326 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
20329 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
20330 // the FP state in cases where an emms may be missing.
20331 // A preferable solution to the general problem is to figure out the right
20332 // places to insert EMMS. This qualifies as a quick hack.
20334 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
20335 if (VT.getSizeInBits() != 64)
20338 const Function *F = DAG.getMachineFunction().getFunction();
20339 bool NoImplicitFloatOps = F->getAttributes().
20340 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
20341 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
20342 && Subtarget->hasSSE2();
20343 if ((VT.isVector() ||
20344 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
20345 isa<LoadSDNode>(St->getValue()) &&
20346 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
20347 St->getChain().hasOneUse() && !St->isVolatile()) {
20348 SDNode* LdVal = St->getValue().getNode();
20349 LoadSDNode *Ld = nullptr;
20350 int TokenFactorIndex = -1;
20351 SmallVector<SDValue, 8> Ops;
20352 SDNode* ChainVal = St->getChain().getNode();
20353 // Must be a store of a load. We currently handle two cases: the load
20354 // is a direct child, and it's under an intervening TokenFactor. It is
20355 // possible to dig deeper under nested TokenFactors.
20356 if (ChainVal == LdVal)
20357 Ld = cast<LoadSDNode>(St->getChain());
20358 else if (St->getValue().hasOneUse() &&
20359 ChainVal->getOpcode() == ISD::TokenFactor) {
20360 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
20361 if (ChainVal->getOperand(i).getNode() == LdVal) {
20362 TokenFactorIndex = i;
20363 Ld = cast<LoadSDNode>(St->getValue());
20365 Ops.push_back(ChainVal->getOperand(i));
20369 if (!Ld || !ISD::isNormalLoad(Ld))
20372 // If this is not the MMX case, i.e. we are just turning i64 load/store
20373 // into f64 load/store, avoid the transformation if there are multiple
20374 // uses of the loaded value.
20375 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
20380 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
20381 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
20383 if (Subtarget->is64Bit() || F64IsLegal) {
20384 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
20385 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
20386 Ld->getPointerInfo(), Ld->isVolatile(),
20387 Ld->isNonTemporal(), Ld->isInvariant(),
20388 Ld->getAlignment());
20389 SDValue NewChain = NewLd.getValue(1);
20390 if (TokenFactorIndex != -1) {
20391 Ops.push_back(NewChain);
20392 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
20394 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
20395 St->getPointerInfo(),
20396 St->isVolatile(), St->isNonTemporal(),
20397 St->getAlignment());
20400 // Otherwise, lower to two pairs of 32-bit loads / stores.
20401 SDValue LoAddr = Ld->getBasePtr();
20402 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
20403 DAG.getConstant(4, MVT::i32));
20405 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
20406 Ld->getPointerInfo(),
20407 Ld->isVolatile(), Ld->isNonTemporal(),
20408 Ld->isInvariant(), Ld->getAlignment());
20409 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
20410 Ld->getPointerInfo().getWithOffset(4),
20411 Ld->isVolatile(), Ld->isNonTemporal(),
20413 MinAlign(Ld->getAlignment(), 4));
20415 SDValue NewChain = LoLd.getValue(1);
20416 if (TokenFactorIndex != -1) {
20417 Ops.push_back(LoLd);
20418 Ops.push_back(HiLd);
20419 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
20422 LoAddr = St->getBasePtr();
20423 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
20424 DAG.getConstant(4, MVT::i32));
20426 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
20427 St->getPointerInfo(),
20428 St->isVolatile(), St->isNonTemporal(),
20429 St->getAlignment());
20430 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
20431 St->getPointerInfo().getWithOffset(4),
20433 St->isNonTemporal(),
20434 MinAlign(St->getAlignment(), 4));
20435 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
20440 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
20441 /// and return the operands for the horizontal operation in LHS and RHS. A
20442 /// horizontal operation performs the binary operation on successive elements
20443 /// of its first operand, then on successive elements of its second operand,
20444 /// returning the resulting values in a vector. For example, if
20445 /// A = < float a0, float a1, float a2, float a3 >
20447 /// B = < float b0, float b1, float b2, float b3 >
20448 /// then the result of doing a horizontal operation on A and B is
20449 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
20450 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
20451 /// A horizontal-op B, for some already available A and B, and if so then LHS is
20452 /// set to A, RHS to B, and the routine returns 'true'.
20453 /// Note that the binary operation should have the property that if one of the
20454 /// operands is UNDEF then the result is UNDEF.
20455 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
20456 // Look for the following pattern: if
20457 // A = < float a0, float a1, float a2, float a3 >
20458 // B = < float b0, float b1, float b2, float b3 >
20460 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
20461 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
20462 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
20463 // which is A horizontal-op B.
20465 // At least one of the operands should be a vector shuffle.
20466 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
20467 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
20470 MVT VT = LHS.getSimpleValueType();
20472 assert((VT.is128BitVector() || VT.is256BitVector()) &&
20473 "Unsupported vector type for horizontal add/sub");
20475 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
20476 // operate independently on 128-bit lanes.
20477 unsigned NumElts = VT.getVectorNumElements();
20478 unsigned NumLanes = VT.getSizeInBits()/128;
20479 unsigned NumLaneElts = NumElts / NumLanes;
20480 assert((NumLaneElts % 2 == 0) &&
20481 "Vector type should have an even number of elements in each lane");
20482 unsigned HalfLaneElts = NumLaneElts/2;
20484 // View LHS in the form
20485 // LHS = VECTOR_SHUFFLE A, B, LMask
20486 // If LHS is not a shuffle then pretend it is the shuffle
20487 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
20488 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
20491 SmallVector<int, 16> LMask(NumElts);
20492 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
20493 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
20494 A = LHS.getOperand(0);
20495 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
20496 B = LHS.getOperand(1);
20497 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
20498 std::copy(Mask.begin(), Mask.end(), LMask.begin());
20500 if (LHS.getOpcode() != ISD::UNDEF)
20502 for (unsigned i = 0; i != NumElts; ++i)
20506 // Likewise, view RHS in the form
20507 // RHS = VECTOR_SHUFFLE C, D, RMask
20509 SmallVector<int, 16> RMask(NumElts);
20510 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
20511 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
20512 C = RHS.getOperand(0);
20513 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
20514 D = RHS.getOperand(1);
20515 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
20516 std::copy(Mask.begin(), Mask.end(), RMask.begin());
20518 if (RHS.getOpcode() != ISD::UNDEF)
20520 for (unsigned i = 0; i != NumElts; ++i)
20524 // Check that the shuffles are both shuffling the same vectors.
20525 if (!(A == C && B == D) && !(A == D && B == C))
20528 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
20529 if (!A.getNode() && !B.getNode())
20532 // If A and B occur in reverse order in RHS, then "swap" them (which means
20533 // rewriting the mask).
20535 CommuteVectorShuffleMask(RMask, NumElts);
20537 // At this point LHS and RHS are equivalent to
20538 // LHS = VECTOR_SHUFFLE A, B, LMask
20539 // RHS = VECTOR_SHUFFLE A, B, RMask
20540 // Check that the masks correspond to performing a horizontal operation.
20541 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
20542 for (unsigned i = 0; i != NumLaneElts; ++i) {
20543 int LIdx = LMask[i+l], RIdx = RMask[i+l];
20545 // Ignore any UNDEF components.
20546 if (LIdx < 0 || RIdx < 0 ||
20547 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
20548 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
20551 // Check that successive elements are being operated on. If not, this is
20552 // not a horizontal operation.
20553 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
20554 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
20555 if (!(LIdx == Index && RIdx == Index + 1) &&
20556 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
20561 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
20562 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
20566 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
20567 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
20568 const X86Subtarget *Subtarget) {
20569 EVT VT = N->getValueType(0);
20570 SDValue LHS = N->getOperand(0);
20571 SDValue RHS = N->getOperand(1);
20573 // Try to synthesize horizontal adds from adds of shuffles.
20574 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
20575 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
20576 isHorizontalBinOp(LHS, RHS, true))
20577 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
20581 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
20582 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
20583 const X86Subtarget *Subtarget) {
20584 EVT VT = N->getValueType(0);
20585 SDValue LHS = N->getOperand(0);
20586 SDValue RHS = N->getOperand(1);
20588 // Try to synthesize horizontal subs from subs of shuffles.
20589 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
20590 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
20591 isHorizontalBinOp(LHS, RHS, false))
20592 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
20596 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
20597 /// X86ISD::FXOR nodes.
20598 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
20599 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
20600 // F[X]OR(0.0, x) -> x
20601 // F[X]OR(x, 0.0) -> x
20602 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20603 if (C->getValueAPF().isPosZero())
20604 return N->getOperand(1);
20605 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20606 if (C->getValueAPF().isPosZero())
20607 return N->getOperand(0);
20611 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
20612 /// X86ISD::FMAX nodes.
20613 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
20614 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
20616 // Only perform optimizations if UnsafeMath is used.
20617 if (!DAG.getTarget().Options.UnsafeFPMath)
20620 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
20621 // into FMINC and FMAXC, which are Commutative operations.
20622 unsigned NewOp = 0;
20623 switch (N->getOpcode()) {
20624 default: llvm_unreachable("unknown opcode");
20625 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
20626 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
20629 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
20630 N->getOperand(0), N->getOperand(1));
20633 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
20634 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
20635 // FAND(0.0, x) -> 0.0
20636 // FAND(x, 0.0) -> 0.0
20637 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20638 if (C->getValueAPF().isPosZero())
20639 return N->getOperand(0);
20640 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20641 if (C->getValueAPF().isPosZero())
20642 return N->getOperand(1);
20646 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
20647 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
20648 // FANDN(x, 0.0) -> 0.0
20649 // FANDN(0.0, x) -> x
20650 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20651 if (C->getValueAPF().isPosZero())
20652 return N->getOperand(1);
20653 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20654 if (C->getValueAPF().isPosZero())
20655 return N->getOperand(1);
20659 static SDValue PerformBTCombine(SDNode *N,
20661 TargetLowering::DAGCombinerInfo &DCI) {
20662 // BT ignores high bits in the bit index operand.
20663 SDValue Op1 = N->getOperand(1);
20664 if (Op1.hasOneUse()) {
20665 unsigned BitWidth = Op1.getValueSizeInBits();
20666 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
20667 APInt KnownZero, KnownOne;
20668 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
20669 !DCI.isBeforeLegalizeOps());
20670 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20671 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
20672 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
20673 DCI.CommitTargetLoweringOpt(TLO);
20678 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
20679 SDValue Op = N->getOperand(0);
20680 if (Op.getOpcode() == ISD::BITCAST)
20681 Op = Op.getOperand(0);
20682 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
20683 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
20684 VT.getVectorElementType().getSizeInBits() ==
20685 OpVT.getVectorElementType().getSizeInBits()) {
20686 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
20691 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
20692 const X86Subtarget *Subtarget) {
20693 EVT VT = N->getValueType(0);
20694 if (!VT.isVector())
20697 SDValue N0 = N->getOperand(0);
20698 SDValue N1 = N->getOperand(1);
20699 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
20702 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
20703 // both SSE and AVX2 since there is no sign-extended shift right
20704 // operation on a vector with 64-bit elements.
20705 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
20706 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
20707 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
20708 N0.getOpcode() == ISD::SIGN_EXTEND)) {
20709 SDValue N00 = N0.getOperand(0);
20711 // EXTLOAD has a better solution on AVX2,
20712 // it may be replaced with X86ISD::VSEXT node.
20713 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
20714 if (!ISD::isNormalLoad(N00.getNode()))
20717 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
20718 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
20720 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
20726 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
20727 TargetLowering::DAGCombinerInfo &DCI,
20728 const X86Subtarget *Subtarget) {
20729 if (!DCI.isBeforeLegalizeOps())
20732 if (!Subtarget->hasFp256())
20735 EVT VT = N->getValueType(0);
20736 if (VT.isVector() && VT.getSizeInBits() == 256) {
20737 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
20745 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
20746 const X86Subtarget* Subtarget) {
20748 EVT VT = N->getValueType(0);
20750 // Let legalize expand this if it isn't a legal type yet.
20751 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
20754 EVT ScalarVT = VT.getScalarType();
20755 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
20756 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
20759 SDValue A = N->getOperand(0);
20760 SDValue B = N->getOperand(1);
20761 SDValue C = N->getOperand(2);
20763 bool NegA = (A.getOpcode() == ISD::FNEG);
20764 bool NegB = (B.getOpcode() == ISD::FNEG);
20765 bool NegC = (C.getOpcode() == ISD::FNEG);
20767 // Negative multiplication when NegA xor NegB
20768 bool NegMul = (NegA != NegB);
20770 A = A.getOperand(0);
20772 B = B.getOperand(0);
20774 C = C.getOperand(0);
20778 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
20780 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
20782 return DAG.getNode(Opcode, dl, VT, A, B, C);
20785 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
20786 TargetLowering::DAGCombinerInfo &DCI,
20787 const X86Subtarget *Subtarget) {
20788 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
20789 // (and (i32 x86isd::setcc_carry), 1)
20790 // This eliminates the zext. This transformation is necessary because
20791 // ISD::SETCC is always legalized to i8.
20793 SDValue N0 = N->getOperand(0);
20794 EVT VT = N->getValueType(0);
20796 if (N0.getOpcode() == ISD::AND &&
20798 N0.getOperand(0).hasOneUse()) {
20799 SDValue N00 = N0.getOperand(0);
20800 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
20801 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
20802 if (!C || C->getZExtValue() != 1)
20804 return DAG.getNode(ISD::AND, dl, VT,
20805 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
20806 N00.getOperand(0), N00.getOperand(1)),
20807 DAG.getConstant(1, VT));
20811 if (N0.getOpcode() == ISD::TRUNCATE &&
20813 N0.getOperand(0).hasOneUse()) {
20814 SDValue N00 = N0.getOperand(0);
20815 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
20816 return DAG.getNode(ISD::AND, dl, VT,
20817 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
20818 N00.getOperand(0), N00.getOperand(1)),
20819 DAG.getConstant(1, VT));
20822 if (VT.is256BitVector()) {
20823 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
20831 // Optimize x == -y --> x+y == 0
20832 // x != -y --> x+y != 0
20833 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
20834 const X86Subtarget* Subtarget) {
20835 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
20836 SDValue LHS = N->getOperand(0);
20837 SDValue RHS = N->getOperand(1);
20838 EVT VT = N->getValueType(0);
20841 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
20842 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
20843 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
20844 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
20845 LHS.getValueType(), RHS, LHS.getOperand(1));
20846 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
20847 addV, DAG.getConstant(0, addV.getValueType()), CC);
20849 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
20850 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
20851 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
20852 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
20853 RHS.getValueType(), LHS, RHS.getOperand(1));
20854 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
20855 addV, DAG.getConstant(0, addV.getValueType()), CC);
20858 if (VT.getScalarType() == MVT::i1) {
20859 bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
20860 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
20861 bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
20862 if (!IsSEXT0 && !IsVZero0)
20864 bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
20865 (RHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
20866 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
20868 if (!IsSEXT1 && !IsVZero1)
20871 if (IsSEXT0 && IsVZero1) {
20872 assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
20873 if (CC == ISD::SETEQ)
20874 return DAG.getNOT(DL, LHS.getOperand(0), VT);
20875 return LHS.getOperand(0);
20877 if (IsSEXT1 && IsVZero0) {
20878 assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
20879 if (CC == ISD::SETEQ)
20880 return DAG.getNOT(DL, RHS.getOperand(0), VT);
20881 return RHS.getOperand(0);
20888 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
20889 const X86Subtarget *Subtarget) {
20891 MVT VT = N->getOperand(1)->getSimpleValueType(0);
20892 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
20893 "X86insertps is only defined for v4x32");
20895 SDValue Ld = N->getOperand(1);
20896 if (MayFoldLoad(Ld)) {
20897 // Extract the countS bits from the immediate so we can get the proper
20898 // address when narrowing the vector load to a specific element.
20899 // When the second source op is a memory address, interps doesn't use
20900 // countS and just gets an f32 from that address.
20901 unsigned DestIndex =
20902 cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
20903 Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
20907 // Create this as a scalar to vector to match the instruction pattern.
20908 SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
20909 // countS bits are ignored when loading from memory on insertps, which
20910 // means we don't need to explicitly set them to 0.
20911 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
20912 LoadScalarToVector, N->getOperand(2));
20915 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
20916 // as "sbb reg,reg", since it can be extended without zext and produces
20917 // an all-ones bit which is more useful than 0/1 in some cases.
20918 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
20921 return DAG.getNode(ISD::AND, DL, VT,
20922 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
20923 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
20924 DAG.getConstant(1, VT));
20925 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
20926 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
20927 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
20928 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
20931 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
20932 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
20933 TargetLowering::DAGCombinerInfo &DCI,
20934 const X86Subtarget *Subtarget) {
20936 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
20937 SDValue EFLAGS = N->getOperand(1);
20939 if (CC == X86::COND_A) {
20940 // Try to convert COND_A into COND_B in an attempt to facilitate
20941 // materializing "setb reg".
20943 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
20944 // cannot take an immediate as its first operand.
20946 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
20947 EFLAGS.getValueType().isInteger() &&
20948 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
20949 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
20950 EFLAGS.getNode()->getVTList(),
20951 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
20952 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
20953 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
20957 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
20958 // a zext and produces an all-ones bit which is more useful than 0/1 in some
20960 if (CC == X86::COND_B)
20961 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
20965 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
20966 if (Flags.getNode()) {
20967 SDValue Cond = DAG.getConstant(CC, MVT::i8);
20968 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
20974 // Optimize branch condition evaluation.
20976 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
20977 TargetLowering::DAGCombinerInfo &DCI,
20978 const X86Subtarget *Subtarget) {
20980 SDValue Chain = N->getOperand(0);
20981 SDValue Dest = N->getOperand(1);
20982 SDValue EFLAGS = N->getOperand(3);
20983 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
20987 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
20988 if (Flags.getNode()) {
20989 SDValue Cond = DAG.getConstant(CC, MVT::i8);
20990 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
20997 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
20998 const X86TargetLowering *XTLI) {
20999 SDValue Op0 = N->getOperand(0);
21000 EVT InVT = Op0->getValueType(0);
21002 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
21003 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
21005 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
21006 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
21007 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
21010 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
21011 // a 32-bit target where SSE doesn't support i64->FP operations.
21012 if (Op0.getOpcode() == ISD::LOAD) {
21013 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
21014 EVT VT = Ld->getValueType(0);
21015 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
21016 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
21017 !XTLI->getSubtarget()->is64Bit() &&
21019 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
21020 Ld->getChain(), Op0, DAG);
21021 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
21028 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
21029 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
21030 X86TargetLowering::DAGCombinerInfo &DCI) {
21031 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
21032 // the result is either zero or one (depending on the input carry bit).
21033 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
21034 if (X86::isZeroNode(N->getOperand(0)) &&
21035 X86::isZeroNode(N->getOperand(1)) &&
21036 // We don't have a good way to replace an EFLAGS use, so only do this when
21038 SDValue(N, 1).use_empty()) {
21040 EVT VT = N->getValueType(0);
21041 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
21042 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
21043 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
21044 DAG.getConstant(X86::COND_B,MVT::i8),
21046 DAG.getConstant(1, VT));
21047 return DCI.CombineTo(N, Res1, CarryOut);
21053 // fold (add Y, (sete X, 0)) -> adc 0, Y
21054 // (add Y, (setne X, 0)) -> sbb -1, Y
21055 // (sub (sete X, 0), Y) -> sbb 0, Y
21056 // (sub (setne X, 0), Y) -> adc -1, Y
21057 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
21060 // Look through ZExts.
21061 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
21062 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
21065 SDValue SetCC = Ext.getOperand(0);
21066 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
21069 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
21070 if (CC != X86::COND_E && CC != X86::COND_NE)
21073 SDValue Cmp = SetCC.getOperand(1);
21074 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
21075 !X86::isZeroNode(Cmp.getOperand(1)) ||
21076 !Cmp.getOperand(0).getValueType().isInteger())
21079 SDValue CmpOp0 = Cmp.getOperand(0);
21080 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
21081 DAG.getConstant(1, CmpOp0.getValueType()));
21083 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
21084 if (CC == X86::COND_NE)
21085 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
21086 DL, OtherVal.getValueType(), OtherVal,
21087 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
21088 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
21089 DL, OtherVal.getValueType(), OtherVal,
21090 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
21093 /// PerformADDCombine - Do target-specific dag combines on integer adds.
21094 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
21095 const X86Subtarget *Subtarget) {
21096 EVT VT = N->getValueType(0);
21097 SDValue Op0 = N->getOperand(0);
21098 SDValue Op1 = N->getOperand(1);
21100 // Try to synthesize horizontal adds from adds of shuffles.
21101 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
21102 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
21103 isHorizontalBinOp(Op0, Op1, true))
21104 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
21106 return OptimizeConditionalInDecrement(N, DAG);
21109 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
21110 const X86Subtarget *Subtarget) {
21111 SDValue Op0 = N->getOperand(0);
21112 SDValue Op1 = N->getOperand(1);
21114 // X86 can't encode an immediate LHS of a sub. See if we can push the
21115 // negation into a preceding instruction.
21116 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
21117 // If the RHS of the sub is a XOR with one use and a constant, invert the
21118 // immediate. Then add one to the LHS of the sub so we can turn
21119 // X-Y -> X+~Y+1, saving one register.
21120 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
21121 isa<ConstantSDNode>(Op1.getOperand(1))) {
21122 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
21123 EVT VT = Op0.getValueType();
21124 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
21126 DAG.getConstant(~XorC, VT));
21127 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
21128 DAG.getConstant(C->getAPIntValue()+1, VT));
21132 // Try to synthesize horizontal adds from adds of shuffles.
21133 EVT VT = N->getValueType(0);
21134 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
21135 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
21136 isHorizontalBinOp(Op0, Op1, true))
21137 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
21139 return OptimizeConditionalInDecrement(N, DAG);
21142 /// performVZEXTCombine - Performs build vector combines
21143 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
21144 TargetLowering::DAGCombinerInfo &DCI,
21145 const X86Subtarget *Subtarget) {
21146 // (vzext (bitcast (vzext (x)) -> (vzext x)
21147 SDValue In = N->getOperand(0);
21148 while (In.getOpcode() == ISD::BITCAST)
21149 In = In.getOperand(0);
21151 if (In.getOpcode() != X86ISD::VZEXT)
21154 return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
21158 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
21159 DAGCombinerInfo &DCI) const {
21160 SelectionDAG &DAG = DCI.DAG;
21161 switch (N->getOpcode()) {
21163 case ISD::EXTRACT_VECTOR_ELT:
21164 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
21166 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
21167 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
21168 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
21169 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
21170 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
21171 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
21174 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
21175 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
21176 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
21177 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
21178 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
21179 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
21180 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
21181 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
21182 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
21184 case X86ISD::FOR: return PerformFORCombine(N, DAG);
21186 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
21187 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
21188 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
21189 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
21190 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
21191 case ISD::ANY_EXTEND:
21192 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
21193 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
21194 case ISD::SIGN_EXTEND_INREG:
21195 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
21196 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
21197 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
21198 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
21199 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
21200 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
21201 case X86ISD::SHUFP: // Handle all target specific shuffles
21202 case X86ISD::PALIGNR:
21203 case X86ISD::UNPCKH:
21204 case X86ISD::UNPCKL:
21205 case X86ISD::MOVHLPS:
21206 case X86ISD::MOVLHPS:
21207 case X86ISD::PSHUFD:
21208 case X86ISD::PSHUFHW:
21209 case X86ISD::PSHUFLW:
21210 case X86ISD::MOVSS:
21211 case X86ISD::MOVSD:
21212 case X86ISD::VPERMILP:
21213 case X86ISD::VPERM2X128:
21214 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
21215 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
21216 case ISD::INTRINSIC_WO_CHAIN:
21217 return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
21218 case X86ISD::INSERTPS:
21219 return PerformINSERTPSCombine(N, DAG, Subtarget);
21220 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
21226 /// isTypeDesirableForOp - Return true if the target has native support for
21227 /// the specified value type and it is 'desirable' to use the type for the
21228 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
21229 /// instruction encodings are longer and some i16 instructions are slow.
21230 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
21231 if (!isTypeLegal(VT))
21233 if (VT != MVT::i16)
21240 case ISD::SIGN_EXTEND:
21241 case ISD::ZERO_EXTEND:
21242 case ISD::ANY_EXTEND:
21255 /// IsDesirableToPromoteOp - This method query the target whether it is
21256 /// beneficial for dag combiner to promote the specified node. If true, it
21257 /// should return the desired promotion type by reference.
21258 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
21259 EVT VT = Op.getValueType();
21260 if (VT != MVT::i16)
21263 bool Promote = false;
21264 bool Commute = false;
21265 switch (Op.getOpcode()) {
21268 LoadSDNode *LD = cast<LoadSDNode>(Op);
21269 // If the non-extending load has a single use and it's not live out, then it
21270 // might be folded.
21271 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
21272 Op.hasOneUse()*/) {
21273 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
21274 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
21275 // The only case where we'd want to promote LOAD (rather then it being
21276 // promoted as an operand is when it's only use is liveout.
21277 if (UI->getOpcode() != ISD::CopyToReg)
21284 case ISD::SIGN_EXTEND:
21285 case ISD::ZERO_EXTEND:
21286 case ISD::ANY_EXTEND:
21291 SDValue N0 = Op.getOperand(0);
21292 // Look out for (store (shl (load), x)).
21293 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
21306 SDValue N0 = Op.getOperand(0);
21307 SDValue N1 = Op.getOperand(1);
21308 if (!Commute && MayFoldLoad(N1))
21310 // Avoid disabling potential load folding opportunities.
21311 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
21313 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
21323 //===----------------------------------------------------------------------===//
21324 // X86 Inline Assembly Support
21325 //===----------------------------------------------------------------------===//
21328 // Helper to match a string separated by whitespace.
21329 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
21330 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
21332 for (unsigned i = 0, e = args.size(); i != e; ++i) {
21333 StringRef piece(*args[i]);
21334 if (!s.startswith(piece)) // Check if the piece matches.
21337 s = s.substr(piece.size());
21338 StringRef::size_type pos = s.find_first_not_of(" \t");
21339 if (pos == 0) // We matched a prefix.
21347 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
21350 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
21352 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
21353 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
21354 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
21355 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
21357 if (AsmPieces.size() == 3)
21359 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
21366 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
21367 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
21369 std::string AsmStr = IA->getAsmString();
21371 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
21372 if (!Ty || Ty->getBitWidth() % 16 != 0)
21375 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
21376 SmallVector<StringRef, 4> AsmPieces;
21377 SplitString(AsmStr, AsmPieces, ";\n");
21379 switch (AsmPieces.size()) {
21380 default: return false;
21382 // FIXME: this should verify that we are targeting a 486 or better. If not,
21383 // we will turn this bswap into something that will be lowered to logical
21384 // ops instead of emitting the bswap asm. For now, we don't support 486 or
21385 // lower so don't worry about this.
21387 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
21388 matchAsm(AsmPieces[0], "bswapl", "$0") ||
21389 matchAsm(AsmPieces[0], "bswapq", "$0") ||
21390 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
21391 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
21392 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
21393 // No need to check constraints, nothing other than the equivalent of
21394 // "=r,0" would be valid here.
21395 return IntrinsicLowering::LowerToByteSwap(CI);
21398 // rorw $$8, ${0:w} --> llvm.bswap.i16
21399 if (CI->getType()->isIntegerTy(16) &&
21400 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
21401 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
21402 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
21404 const std::string &ConstraintsStr = IA->getConstraintString();
21405 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
21406 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
21407 if (clobbersFlagRegisters(AsmPieces))
21408 return IntrinsicLowering::LowerToByteSwap(CI);
21412 if (CI->getType()->isIntegerTy(32) &&
21413 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
21414 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
21415 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
21416 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
21418 const std::string &ConstraintsStr = IA->getConstraintString();
21419 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
21420 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
21421 if (clobbersFlagRegisters(AsmPieces))
21422 return IntrinsicLowering::LowerToByteSwap(CI);
21425 if (CI->getType()->isIntegerTy(64)) {
21426 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
21427 if (Constraints.size() >= 2 &&
21428 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
21429 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
21430 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
21431 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
21432 matchAsm(AsmPieces[1], "bswap", "%edx") &&
21433 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
21434 return IntrinsicLowering::LowerToByteSwap(CI);
21442 /// getConstraintType - Given a constraint letter, return the type of
21443 /// constraint it is for this target.
21444 X86TargetLowering::ConstraintType
21445 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
21446 if (Constraint.size() == 1) {
21447 switch (Constraint[0]) {
21458 return C_RegisterClass;
21482 return TargetLowering::getConstraintType(Constraint);
21485 /// Examine constraint type and operand type and determine a weight value.
21486 /// This object must already have been set up with the operand type
21487 /// and the current alternative constraint selected.
21488 TargetLowering::ConstraintWeight
21489 X86TargetLowering::getSingleConstraintMatchWeight(
21490 AsmOperandInfo &info, const char *constraint) const {
21491 ConstraintWeight weight = CW_Invalid;
21492 Value *CallOperandVal = info.CallOperandVal;
21493 // If we don't have a value, we can't do a match,
21494 // but allow it at the lowest weight.
21495 if (!CallOperandVal)
21497 Type *type = CallOperandVal->getType();
21498 // Look at the constraint type.
21499 switch (*constraint) {
21501 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
21512 if (CallOperandVal->getType()->isIntegerTy())
21513 weight = CW_SpecificReg;
21518 if (type->isFloatingPointTy())
21519 weight = CW_SpecificReg;
21522 if (type->isX86_MMXTy() && Subtarget->hasMMX())
21523 weight = CW_SpecificReg;
21527 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
21528 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
21529 weight = CW_Register;
21532 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
21533 if (C->getZExtValue() <= 31)
21534 weight = CW_Constant;
21538 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21539 if (C->getZExtValue() <= 63)
21540 weight = CW_Constant;
21544 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21545 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
21546 weight = CW_Constant;
21550 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21551 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
21552 weight = CW_Constant;
21556 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21557 if (C->getZExtValue() <= 3)
21558 weight = CW_Constant;
21562 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21563 if (C->getZExtValue() <= 0xff)
21564 weight = CW_Constant;
21569 if (dyn_cast<ConstantFP>(CallOperandVal)) {
21570 weight = CW_Constant;
21574 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21575 if ((C->getSExtValue() >= -0x80000000LL) &&
21576 (C->getSExtValue() <= 0x7fffffffLL))
21577 weight = CW_Constant;
21581 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21582 if (C->getZExtValue() <= 0xffffffff)
21583 weight = CW_Constant;
21590 /// LowerXConstraint - try to replace an X constraint, which matches anything,
21591 /// with another that has more specific requirements based on the type of the
21592 /// corresponding operand.
21593 const char *X86TargetLowering::
21594 LowerXConstraint(EVT ConstraintVT) const {
21595 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
21596 // 'f' like normal targets.
21597 if (ConstraintVT.isFloatingPoint()) {
21598 if (Subtarget->hasSSE2())
21600 if (Subtarget->hasSSE1())
21604 return TargetLowering::LowerXConstraint(ConstraintVT);
21607 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
21608 /// vector. If it is invalid, don't add anything to Ops.
21609 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
21610 std::string &Constraint,
21611 std::vector<SDValue>&Ops,
21612 SelectionDAG &DAG) const {
21615 // Only support length 1 constraints for now.
21616 if (Constraint.length() > 1) return;
21618 char ConstraintLetter = Constraint[0];
21619 switch (ConstraintLetter) {
21622 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21623 if (C->getZExtValue() <= 31) {
21624 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21630 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21631 if (C->getZExtValue() <= 63) {
21632 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21638 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21639 if (isInt<8>(C->getSExtValue())) {
21640 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21646 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21647 if (C->getZExtValue() <= 255) {
21648 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21654 // 32-bit signed value
21655 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21656 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
21657 C->getSExtValue())) {
21658 // Widen to 64 bits here to get it sign extended.
21659 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
21662 // FIXME gcc accepts some relocatable values here too, but only in certain
21663 // memory models; it's complicated.
21668 // 32-bit unsigned value
21669 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21670 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
21671 C->getZExtValue())) {
21672 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21676 // FIXME gcc accepts some relocatable values here too, but only in certain
21677 // memory models; it's complicated.
21681 // Literal immediates are always ok.
21682 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
21683 // Widen to 64 bits here to get it sign extended.
21684 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
21688 // In any sort of PIC mode addresses need to be computed at runtime by
21689 // adding in a register or some sort of table lookup. These can't
21690 // be used as immediates.
21691 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
21694 // If we are in non-pic codegen mode, we allow the address of a global (with
21695 // an optional displacement) to be used with 'i'.
21696 GlobalAddressSDNode *GA = nullptr;
21697 int64_t Offset = 0;
21699 // Match either (GA), (GA+C), (GA+C1+C2), etc.
21701 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
21702 Offset += GA->getOffset();
21704 } else if (Op.getOpcode() == ISD::ADD) {
21705 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
21706 Offset += C->getZExtValue();
21707 Op = Op.getOperand(0);
21710 } else if (Op.getOpcode() == ISD::SUB) {
21711 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
21712 Offset += -C->getZExtValue();
21713 Op = Op.getOperand(0);
21718 // Otherwise, this isn't something we can handle, reject it.
21722 const GlobalValue *GV = GA->getGlobal();
21723 // If we require an extra load to get this address, as in PIC mode, we
21724 // can't accept it.
21725 if (isGlobalStubReference(
21726 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
21729 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
21730 GA->getValueType(0), Offset);
21735 if (Result.getNode()) {
21736 Ops.push_back(Result);
21739 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
21742 std::pair<unsigned, const TargetRegisterClass*>
21743 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
21745 // First, see if this is a constraint that directly corresponds to an LLVM
21747 if (Constraint.size() == 1) {
21748 // GCC Constraint Letters
21749 switch (Constraint[0]) {
21751 // TODO: Slight differences here in allocation order and leaving
21752 // RIP in the class. Do they matter any more here than they do
21753 // in the normal allocation?
21754 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
21755 if (Subtarget->is64Bit()) {
21756 if (VT == MVT::i32 || VT == MVT::f32)
21757 return std::make_pair(0U, &X86::GR32RegClass);
21758 if (VT == MVT::i16)
21759 return std::make_pair(0U, &X86::GR16RegClass);
21760 if (VT == MVT::i8 || VT == MVT::i1)
21761 return std::make_pair(0U, &X86::GR8RegClass);
21762 if (VT == MVT::i64 || VT == MVT::f64)
21763 return std::make_pair(0U, &X86::GR64RegClass);
21766 // 32-bit fallthrough
21767 case 'Q': // Q_REGS
21768 if (VT == MVT::i32 || VT == MVT::f32)
21769 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
21770 if (VT == MVT::i16)
21771 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
21772 if (VT == MVT::i8 || VT == MVT::i1)
21773 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
21774 if (VT == MVT::i64)
21775 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
21777 case 'r': // GENERAL_REGS
21778 case 'l': // INDEX_REGS
21779 if (VT == MVT::i8 || VT == MVT::i1)
21780 return std::make_pair(0U, &X86::GR8RegClass);
21781 if (VT == MVT::i16)
21782 return std::make_pair(0U, &X86::GR16RegClass);
21783 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
21784 return std::make_pair(0U, &X86::GR32RegClass);
21785 return std::make_pair(0U, &X86::GR64RegClass);
21786 case 'R': // LEGACY_REGS
21787 if (VT == MVT::i8 || VT == MVT::i1)
21788 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
21789 if (VT == MVT::i16)
21790 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
21791 if (VT == MVT::i32 || !Subtarget->is64Bit())
21792 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
21793 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
21794 case 'f': // FP Stack registers.
21795 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
21796 // value to the correct fpstack register class.
21797 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
21798 return std::make_pair(0U, &X86::RFP32RegClass);
21799 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
21800 return std::make_pair(0U, &X86::RFP64RegClass);
21801 return std::make_pair(0U, &X86::RFP80RegClass);
21802 case 'y': // MMX_REGS if MMX allowed.
21803 if (!Subtarget->hasMMX()) break;
21804 return std::make_pair(0U, &X86::VR64RegClass);
21805 case 'Y': // SSE_REGS if SSE2 allowed
21806 if (!Subtarget->hasSSE2()) break;
21808 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
21809 if (!Subtarget->hasSSE1()) break;
21811 switch (VT.SimpleTy) {
21813 // Scalar SSE types.
21816 return std::make_pair(0U, &X86::FR32RegClass);
21819 return std::make_pair(0U, &X86::FR64RegClass);
21827 return std::make_pair(0U, &X86::VR128RegClass);
21835 return std::make_pair(0U, &X86::VR256RegClass);
21840 return std::make_pair(0U, &X86::VR512RegClass);
21846 // Use the default implementation in TargetLowering to convert the register
21847 // constraint into a member of a register class.
21848 std::pair<unsigned, const TargetRegisterClass*> Res;
21849 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
21851 // Not found as a standard register?
21853 // Map st(0) -> st(7) -> ST0
21854 if (Constraint.size() == 7 && Constraint[0] == '{' &&
21855 tolower(Constraint[1]) == 's' &&
21856 tolower(Constraint[2]) == 't' &&
21857 Constraint[3] == '(' &&
21858 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
21859 Constraint[5] == ')' &&
21860 Constraint[6] == '}') {
21862 Res.first = X86::ST0+Constraint[4]-'0';
21863 Res.second = &X86::RFP80RegClass;
21867 // GCC allows "st(0)" to be called just plain "st".
21868 if (StringRef("{st}").equals_lower(Constraint)) {
21869 Res.first = X86::ST0;
21870 Res.second = &X86::RFP80RegClass;
21875 if (StringRef("{flags}").equals_lower(Constraint)) {
21876 Res.first = X86::EFLAGS;
21877 Res.second = &X86::CCRRegClass;
21881 // 'A' means EAX + EDX.
21882 if (Constraint == "A") {
21883 Res.first = X86::EAX;
21884 Res.second = &X86::GR32_ADRegClass;
21890 // Otherwise, check to see if this is a register class of the wrong value
21891 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
21892 // turn into {ax},{dx}.
21893 if (Res.second->hasType(VT))
21894 return Res; // Correct type already, nothing to do.
21896 // All of the single-register GCC register classes map their values onto
21897 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
21898 // really want an 8-bit or 32-bit register, map to the appropriate register
21899 // class and return the appropriate register.
21900 if (Res.second == &X86::GR16RegClass) {
21901 if (VT == MVT::i8 || VT == MVT::i1) {
21902 unsigned DestReg = 0;
21903 switch (Res.first) {
21905 case X86::AX: DestReg = X86::AL; break;
21906 case X86::DX: DestReg = X86::DL; break;
21907 case X86::CX: DestReg = X86::CL; break;
21908 case X86::BX: DestReg = X86::BL; break;
21911 Res.first = DestReg;
21912 Res.second = &X86::GR8RegClass;
21914 } else if (VT == MVT::i32 || VT == MVT::f32) {
21915 unsigned DestReg = 0;
21916 switch (Res.first) {
21918 case X86::AX: DestReg = X86::EAX; break;
21919 case X86::DX: DestReg = X86::EDX; break;
21920 case X86::CX: DestReg = X86::ECX; break;
21921 case X86::BX: DestReg = X86::EBX; break;
21922 case X86::SI: DestReg = X86::ESI; break;
21923 case X86::DI: DestReg = X86::EDI; break;
21924 case X86::BP: DestReg = X86::EBP; break;
21925 case X86::SP: DestReg = X86::ESP; break;
21928 Res.first = DestReg;
21929 Res.second = &X86::GR32RegClass;
21931 } else if (VT == MVT::i64 || VT == MVT::f64) {
21932 unsigned DestReg = 0;
21933 switch (Res.first) {
21935 case X86::AX: DestReg = X86::RAX; break;
21936 case X86::DX: DestReg = X86::RDX; break;
21937 case X86::CX: DestReg = X86::RCX; break;
21938 case X86::BX: DestReg = X86::RBX; break;
21939 case X86::SI: DestReg = X86::RSI; break;
21940 case X86::DI: DestReg = X86::RDI; break;
21941 case X86::BP: DestReg = X86::RBP; break;
21942 case X86::SP: DestReg = X86::RSP; break;
21945 Res.first = DestReg;
21946 Res.second = &X86::GR64RegClass;
21949 } else if (Res.second == &X86::FR32RegClass ||
21950 Res.second == &X86::FR64RegClass ||
21951 Res.second == &X86::VR128RegClass ||
21952 Res.second == &X86::VR256RegClass ||
21953 Res.second == &X86::FR32XRegClass ||
21954 Res.second == &X86::FR64XRegClass ||
21955 Res.second == &X86::VR128XRegClass ||
21956 Res.second == &X86::VR256XRegClass ||
21957 Res.second == &X86::VR512RegClass) {
21958 // Handle references to XMM physical registers that got mapped into the
21959 // wrong class. This can happen with constraints like {xmm0} where the
21960 // target independent register mapper will just pick the first match it can
21961 // find, ignoring the required type.
21963 if (VT == MVT::f32 || VT == MVT::i32)
21964 Res.second = &X86::FR32RegClass;
21965 else if (VT == MVT::f64 || VT == MVT::i64)
21966 Res.second = &X86::FR64RegClass;
21967 else if (X86::VR128RegClass.hasType(VT))
21968 Res.second = &X86::VR128RegClass;
21969 else if (X86::VR256RegClass.hasType(VT))
21970 Res.second = &X86::VR256RegClass;
21971 else if (X86::VR512RegClass.hasType(VT))
21972 Res.second = &X86::VR512RegClass;
21978 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
21980 // Scaling factors are not free at all.
21981 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
21982 // will take 2 allocations in the out of order engine instead of 1
21983 // for plain addressing mode, i.e. inst (reg1).
21985 // vaddps (%rsi,%drx), %ymm0, %ymm1
21986 // Requires two allocations (one for the load, one for the computation)
21988 // vaddps (%rsi), %ymm0, %ymm1
21989 // Requires just 1 allocation, i.e., freeing allocations for other operations
21990 // and having less micro operations to execute.
21992 // For some X86 architectures, this is even worse because for instance for
21993 // stores, the complex addressing mode forces the instruction to use the
21994 // "load" ports instead of the dedicated "store" port.
21995 // E.g., on Haswell:
21996 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
21997 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
21998 if (isLegalAddressingMode(AM, Ty))
21999 // Scale represents reg2 * scale, thus account for 1
22000 // as soon as we use a second register.
22001 return AM.Scale != 0;
22005 bool X86TargetLowering::isTargetFTOL() const {
22006 return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();