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 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6225 const X86Subtarget *Subtarget) {
6227 EVT VT = N->getValueType(0);
6228 unsigned NumElts = VT.getVectorNumElements();
6229 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
6230 SDValue InVec0, InVec1;
6232 // Try to match horizontal ADD/SUB.
6233 unsigned NumUndefsLO = 0;
6234 unsigned NumUndefsHI = 0;
6235 unsigned Half = NumElts/2;
6237 // Count the number of UNDEF operands in the build_vector in input.
6238 for (unsigned i = 0, e = Half; i != e; ++i)
6239 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6242 for (unsigned i = Half, e = NumElts; i != e; ++i)
6243 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6246 // Early exit if this is either a build_vector of all UNDEFs or all the
6247 // operands but one are UNDEF.
6248 if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6251 if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6252 // Try to match an SSE3 float HADD/HSUB.
6253 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6254 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6256 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6257 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6258 } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6259 // Try to match an SSSE3 integer HADD/HSUB.
6260 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6261 return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6263 if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6264 return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6267 if (!Subtarget->hasAVX())
6270 if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6271 // Try to match an AVX horizontal add/sub of packed single/double
6272 // precision floating point values from 256-bit vectors.
6273 SDValue InVec2, InVec3;
6274 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6275 isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6276 ((InVec0.getOpcode() == ISD::UNDEF ||
6277 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6278 ((InVec1.getOpcode() == ISD::UNDEF ||
6279 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6280 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6282 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6283 isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6284 ((InVec0.getOpcode() == ISD::UNDEF ||
6285 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6286 ((InVec1.getOpcode() == ISD::UNDEF ||
6287 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6288 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6289 } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6290 // Try to match an AVX2 horizontal add/sub of signed integers.
6291 SDValue InVec2, InVec3;
6293 bool CanFold = true;
6295 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6296 isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6297 ((InVec0.getOpcode() == ISD::UNDEF ||
6298 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6299 ((InVec1.getOpcode() == ISD::UNDEF ||
6300 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6301 X86Opcode = X86ISD::HADD;
6302 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6303 isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6304 ((InVec0.getOpcode() == ISD::UNDEF ||
6305 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6306 ((InVec1.getOpcode() == ISD::UNDEF ||
6307 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6308 X86Opcode = X86ISD::HSUB;
6313 // Fold this build_vector into a single horizontal add/sub.
6314 // Do this only if the target has AVX2.
6315 if (Subtarget->hasAVX2())
6316 return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6318 // Do not try to expand this build_vector into a pair of horizontal
6319 // add/sub if we can emit a pair of scalar add/sub.
6320 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6323 // Convert this build_vector into a pair of horizontal binop followed by
6325 bool isUndefLO = NumUndefsLO == Half;
6326 bool isUndefHI = NumUndefsHI == Half;
6327 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6328 isUndefLO, isUndefHI);
6332 if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6333 VT == MVT::v16i16) && Subtarget->hasAVX()) {
6335 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6336 X86Opcode = X86ISD::HADD;
6337 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6338 X86Opcode = X86ISD::HSUB;
6339 else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6340 X86Opcode = X86ISD::FHADD;
6341 else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6342 X86Opcode = X86ISD::FHSUB;
6346 // Don't try to expand this build_vector into a pair of horizontal add/sub
6347 // if we can simply emit a pair of scalar add/sub.
6348 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6351 // Convert this build_vector into two horizontal add/sub followed by
6353 bool isUndefLO = NumUndefsLO == Half;
6354 bool isUndefHI = NumUndefsHI == Half;
6355 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6356 isUndefLO, isUndefHI);
6363 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6366 MVT VT = Op.getSimpleValueType();
6367 MVT ExtVT = VT.getVectorElementType();
6368 unsigned NumElems = Op.getNumOperands();
6370 // Generate vectors for predicate vectors.
6371 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6372 return LowerBUILD_VECTORvXi1(Op, DAG);
6374 // Vectors containing all zeros can be matched by pxor and xorps later
6375 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6376 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6377 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6378 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6381 return getZeroVector(VT, Subtarget, DAG, dl);
6384 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6385 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6386 // vpcmpeqd on 256-bit vectors.
6387 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6388 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6391 if (!VT.is512BitVector())
6392 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6395 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6396 if (Broadcast.getNode())
6399 unsigned EVTBits = ExtVT.getSizeInBits();
6401 unsigned NumZero = 0;
6402 unsigned NumNonZero = 0;
6403 unsigned NonZeros = 0;
6404 bool IsAllConstants = true;
6405 SmallSet<SDValue, 8> Values;
6406 for (unsigned i = 0; i < NumElems; ++i) {
6407 SDValue Elt = Op.getOperand(i);
6408 if (Elt.getOpcode() == ISD::UNDEF)
6411 if (Elt.getOpcode() != ISD::Constant &&
6412 Elt.getOpcode() != ISD::ConstantFP)
6413 IsAllConstants = false;
6414 if (X86::isZeroNode(Elt))
6417 NonZeros |= (1 << i);
6422 // All undef vector. Return an UNDEF. All zero vectors were handled above.
6423 if (NumNonZero == 0)
6424 return DAG.getUNDEF(VT);
6426 // Special case for single non-zero, non-undef, element.
6427 if (NumNonZero == 1) {
6428 unsigned Idx = countTrailingZeros(NonZeros);
6429 SDValue Item = Op.getOperand(Idx);
6431 // If this is an insertion of an i64 value on x86-32, and if the top bits of
6432 // the value are obviously zero, truncate the value to i32 and do the
6433 // insertion that way. Only do this if the value is non-constant or if the
6434 // value is a constant being inserted into element 0. It is cheaper to do
6435 // a constant pool load than it is to do a movd + shuffle.
6436 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6437 (!IsAllConstants || Idx == 0)) {
6438 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6440 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6441 EVT VecVT = MVT::v4i32;
6442 unsigned VecElts = 4;
6444 // Truncate the value (which may itself be a constant) to i32, and
6445 // convert it to a vector with movd (S2V+shuffle to zero extend).
6446 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6447 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6448 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6450 // Now we have our 32-bit value zero extended in the low element of
6451 // a vector. If Idx != 0, swizzle it into place.
6453 SmallVector<int, 4> Mask;
6454 Mask.push_back(Idx);
6455 for (unsigned i = 1; i != VecElts; ++i)
6457 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6460 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6464 // If we have a constant or non-constant insertion into the low element of
6465 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6466 // the rest of the elements. This will be matched as movd/movq/movss/movsd
6467 // depending on what the source datatype is.
6470 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6472 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6473 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6474 if (VT.is256BitVector() || VT.is512BitVector()) {
6475 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6476 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6477 Item, DAG.getIntPtrConstant(0));
6479 assert(VT.is128BitVector() && "Expected an SSE value type!");
6480 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6481 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6482 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6485 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6486 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6487 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6488 if (VT.is256BitVector()) {
6489 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6490 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6492 assert(VT.is128BitVector() && "Expected an SSE value type!");
6493 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6495 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6499 // Is it a vector logical left shift?
6500 if (NumElems == 2 && Idx == 1 &&
6501 X86::isZeroNode(Op.getOperand(0)) &&
6502 !X86::isZeroNode(Op.getOperand(1))) {
6503 unsigned NumBits = VT.getSizeInBits();
6504 return getVShift(true, VT,
6505 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6506 VT, Op.getOperand(1)),
6507 NumBits/2, DAG, *this, dl);
6510 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6513 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6514 // is a non-constant being inserted into an element other than the low one,
6515 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6516 // movd/movss) to move this into the low element, then shuffle it into
6518 if (EVTBits == 32) {
6519 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6521 // Turn it into a shuffle of zero and zero-extended scalar to vector.
6522 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6523 SmallVector<int, 8> MaskVec;
6524 for (unsigned i = 0; i != NumElems; ++i)
6525 MaskVec.push_back(i == Idx ? 0 : 1);
6526 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6530 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6531 if (Values.size() == 1) {
6532 if (EVTBits == 32) {
6533 // Instead of a shuffle like this:
6534 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6535 // Check if it's possible to issue this instead.
6536 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6537 unsigned Idx = countTrailingZeros(NonZeros);
6538 SDValue Item = Op.getOperand(Idx);
6539 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6540 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6545 // A vector full of immediates; various special cases are already
6546 // handled, so this is best done with a single constant-pool load.
6550 // For AVX-length vectors, build the individual 128-bit pieces and use
6551 // shuffles to put them in place.
6552 if (VT.is256BitVector() || VT.is512BitVector()) {
6553 SmallVector<SDValue, 64> V;
6554 for (unsigned i = 0; i != NumElems; ++i)
6555 V.push_back(Op.getOperand(i));
6557 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6559 // Build both the lower and upper subvector.
6560 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6561 makeArrayRef(&V[0], NumElems/2));
6562 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6563 makeArrayRef(&V[NumElems / 2], NumElems/2));
6565 // Recreate the wider vector with the lower and upper part.
6566 if (VT.is256BitVector())
6567 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6568 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6571 // Let legalizer expand 2-wide build_vectors.
6572 if (EVTBits == 64) {
6573 if (NumNonZero == 1) {
6574 // One half is zero or undef.
6575 unsigned Idx = countTrailingZeros(NonZeros);
6576 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6577 Op.getOperand(Idx));
6578 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6583 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6584 if (EVTBits == 8 && NumElems == 16) {
6585 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6587 if (V.getNode()) return V;
6590 if (EVTBits == 16 && NumElems == 8) {
6591 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6593 if (V.getNode()) return V;
6596 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6597 if (EVTBits == 32 && NumElems == 4) {
6598 SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6599 NumZero, DAG, Subtarget, *this);
6604 // If element VT is == 32 bits, turn it into a number of shuffles.
6605 SmallVector<SDValue, 8> V(NumElems);
6606 if (NumElems == 4 && NumZero > 0) {
6607 for (unsigned i = 0; i < 4; ++i) {
6608 bool isZero = !(NonZeros & (1 << i));
6610 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6612 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6615 for (unsigned i = 0; i < 2; ++i) {
6616 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6619 V[i] = V[i*2]; // Must be a zero vector.
6622 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6625 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6628 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6633 bool Reverse1 = (NonZeros & 0x3) == 2;
6634 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6638 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6639 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6641 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6644 if (Values.size() > 1 && VT.is128BitVector()) {
6645 // Check for a build vector of consecutive loads.
6646 for (unsigned i = 0; i < NumElems; ++i)
6647 V[i] = Op.getOperand(i);
6649 // Check for elements which are consecutive loads.
6650 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6654 // Check for a build vector from mostly shuffle plus few inserting.
6655 SDValue Sh = buildFromShuffleMostly(Op, DAG);
6659 // For SSE 4.1, use insertps to put the high elements into the low element.
6660 if (getSubtarget()->hasSSE41()) {
6662 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6663 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6665 Result = DAG.getUNDEF(VT);
6667 for (unsigned i = 1; i < NumElems; ++i) {
6668 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6669 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6670 Op.getOperand(i), DAG.getIntPtrConstant(i));
6675 // Otherwise, expand into a number of unpckl*, start by extending each of
6676 // our (non-undef) elements to the full vector width with the element in the
6677 // bottom slot of the vector (which generates no code for SSE).
6678 for (unsigned i = 0; i < NumElems; ++i) {
6679 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6680 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6682 V[i] = DAG.getUNDEF(VT);
6685 // Next, we iteratively mix elements, e.g. for v4f32:
6686 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6687 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6688 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6689 unsigned EltStride = NumElems >> 1;
6690 while (EltStride != 0) {
6691 for (unsigned i = 0; i < EltStride; ++i) {
6692 // If V[i+EltStride] is undef and this is the first round of mixing,
6693 // then it is safe to just drop this shuffle: V[i] is already in the
6694 // right place, the one element (since it's the first round) being
6695 // inserted as undef can be dropped. This isn't safe for successive
6696 // rounds because they will permute elements within both vectors.
6697 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6698 EltStride == NumElems/2)
6701 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6710 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6711 // to create 256-bit vectors from two other 128-bit ones.
6712 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6714 MVT ResVT = Op.getSimpleValueType();
6716 assert((ResVT.is256BitVector() ||
6717 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6719 SDValue V1 = Op.getOperand(0);
6720 SDValue V2 = Op.getOperand(1);
6721 unsigned NumElems = ResVT.getVectorNumElements();
6722 if(ResVT.is256BitVector())
6723 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6725 if (Op.getNumOperands() == 4) {
6726 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6727 ResVT.getVectorNumElements()/2);
6728 SDValue V3 = Op.getOperand(2);
6729 SDValue V4 = Op.getOperand(3);
6730 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6731 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6733 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6736 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6737 MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6738 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6739 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6740 Op.getNumOperands() == 4)));
6742 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6743 // from two other 128-bit ones.
6745 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6746 return LowerAVXCONCAT_VECTORS(Op, DAG);
6749 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
6750 bool hasInt256, unsigned *MaskOut = nullptr) {
6751 MVT EltVT = VT.getVectorElementType();
6753 // There is no blend with immediate in AVX-512.
6754 if (VT.is512BitVector())
6757 if (!hasSSE41 || EltVT == MVT::i8)
6759 if (!hasInt256 && VT == MVT::v16i16)
6762 unsigned MaskValue = 0;
6763 unsigned NumElems = VT.getVectorNumElements();
6764 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6765 unsigned NumLanes = (NumElems - 1) / 8 + 1;
6766 unsigned NumElemsInLane = NumElems / NumLanes;
6768 // Blend for v16i16 should be symetric for the both lanes.
6769 for (unsigned i = 0; i < NumElemsInLane; ++i) {
6771 int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
6772 int EltIdx = MaskVals[i];
6774 if ((EltIdx < 0 || EltIdx == (int)i) &&
6775 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6778 if (((unsigned)EltIdx == (i + NumElems)) &&
6779 (SndLaneEltIdx < 0 ||
6780 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6781 MaskValue |= (1 << i);
6787 *MaskOut = MaskValue;
6791 // Try to lower a shuffle node into a simple blend instruction.
6792 // This function assumes isBlendMask returns true for this
6793 // SuffleVectorSDNode
6794 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6796 const X86Subtarget *Subtarget,
6797 SelectionDAG &DAG) {
6798 MVT VT = SVOp->getSimpleValueType(0);
6799 MVT EltVT = VT.getVectorElementType();
6800 assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
6801 Subtarget->hasInt256() && "Trying to lower a "
6802 "VECTOR_SHUFFLE to a Blend but "
6803 "with the wrong mask"));
6804 SDValue V1 = SVOp->getOperand(0);
6805 SDValue V2 = SVOp->getOperand(1);
6807 unsigned NumElems = VT.getVectorNumElements();
6809 // Convert i32 vectors to floating point if it is not AVX2.
6810 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6812 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6813 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6815 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6816 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6819 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6820 DAG.getConstant(MaskValue, MVT::i32));
6821 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6824 /// In vector type \p VT, return true if the element at index \p InputIdx
6825 /// falls on a different 128-bit lane than \p OutputIdx.
6826 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
6827 unsigned OutputIdx) {
6828 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6829 return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
6832 /// Generate a PSHUFB if possible. Selects elements from \p V1 according to
6833 /// \p MaskVals. MaskVals[OutputIdx] = InputIdx specifies that we want to
6834 /// shuffle the element at InputIdx in V1 to OutputIdx in the result. If \p
6835 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
6837 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
6838 SelectionDAG &DAG) {
6839 MVT VT = V1.getSimpleValueType();
6840 assert(VT.is128BitVector() || VT.is256BitVector());
6842 MVT EltVT = VT.getVectorElementType();
6843 unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
6844 unsigned NumElts = VT.getVectorNumElements();
6846 SmallVector<SDValue, 32> PshufbMask;
6847 for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
6848 int InputIdx = MaskVals[OutputIdx];
6849 unsigned InputByteIdx;
6851 if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
6852 InputByteIdx = 0x80;
6854 // Cross lane is not allowed.
6855 if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
6857 InputByteIdx = InputIdx * EltSizeInBytes;
6858 // Index is an byte offset within the 128-bit lane.
6859 InputByteIdx &= 0xf;
6862 for (unsigned j = 0; j < EltSizeInBytes; ++j) {
6863 PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
6864 if (InputByteIdx != 0x80)
6869 MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
6871 V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
6872 return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
6873 DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
6876 // v8i16 shuffles - Prefer shuffles in the following order:
6877 // 1. [all] pshuflw, pshufhw, optional move
6878 // 2. [ssse3] 1 x pshufb
6879 // 3. [ssse3] 2 x pshufb + 1 x por
6880 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6882 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6883 SelectionDAG &DAG) {
6884 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6885 SDValue V1 = SVOp->getOperand(0);
6886 SDValue V2 = SVOp->getOperand(1);
6888 SmallVector<int, 8> MaskVals;
6890 // Determine if more than 1 of the words in each of the low and high quadwords
6891 // of the result come from the same quadword of one of the two inputs. Undef
6892 // mask values count as coming from any quadword, for better codegen.
6894 // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
6895 // feeds this quad. For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
6896 unsigned LoQuad[] = { 0, 0, 0, 0 };
6897 unsigned HiQuad[] = { 0, 0, 0, 0 };
6898 // Indices of quads used.
6899 std::bitset<4> InputQuads;
6900 for (unsigned i = 0; i < 8; ++i) {
6901 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6902 int EltIdx = SVOp->getMaskElt(i);
6903 MaskVals.push_back(EltIdx);
6912 InputQuads.set(EltIdx / 4);
6915 int BestLoQuad = -1;
6916 unsigned MaxQuad = 1;
6917 for (unsigned i = 0; i < 4; ++i) {
6918 if (LoQuad[i] > MaxQuad) {
6920 MaxQuad = LoQuad[i];
6924 int BestHiQuad = -1;
6926 for (unsigned i = 0; i < 4; ++i) {
6927 if (HiQuad[i] > MaxQuad) {
6929 MaxQuad = HiQuad[i];
6933 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6934 // of the two input vectors, shuffle them into one input vector so only a
6935 // single pshufb instruction is necessary. If there are more than 2 input
6936 // quads, disable the next transformation since it does not help SSSE3.
6937 bool V1Used = InputQuads[0] || InputQuads[1];
6938 bool V2Used = InputQuads[2] || InputQuads[3];
6939 if (Subtarget->hasSSSE3()) {
6940 if (InputQuads.count() == 2 && V1Used && V2Used) {
6941 BestLoQuad = InputQuads[0] ? 0 : 1;
6942 BestHiQuad = InputQuads[2] ? 2 : 3;
6944 if (InputQuads.count() > 2) {
6950 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6951 // the shuffle mask. If a quad is scored as -1, that means that it contains
6952 // words from all 4 input quadwords.
6954 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6956 BestLoQuad < 0 ? 0 : BestLoQuad,
6957 BestHiQuad < 0 ? 1 : BestHiQuad
6959 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6960 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6961 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6962 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6964 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6965 // source words for the shuffle, to aid later transformations.
6966 bool AllWordsInNewV = true;
6967 bool InOrder[2] = { true, true };
6968 for (unsigned i = 0; i != 8; ++i) {
6969 int idx = MaskVals[i];
6971 InOrder[i/4] = false;
6972 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6974 AllWordsInNewV = false;
6978 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6979 if (AllWordsInNewV) {
6980 for (int i = 0; i != 8; ++i) {
6981 int idx = MaskVals[i];
6984 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6985 if ((idx != i) && idx < 4)
6987 if ((idx != i) && idx > 3)
6996 // If we've eliminated the use of V2, and the new mask is a pshuflw or
6997 // pshufhw, that's as cheap as it gets. Return the new shuffle.
6998 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6999 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
7000 unsigned TargetMask = 0;
7001 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
7002 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
7003 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
7004 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
7005 getShufflePSHUFLWImmediate(SVOp);
7006 V1 = NewV.getOperand(0);
7007 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
7011 // Promote splats to a larger type which usually leads to more efficient code.
7012 // FIXME: Is this true if pshufb is available?
7013 if (SVOp->isSplat())
7014 return PromoteSplat(SVOp, DAG);
7016 // If we have SSSE3, and all words of the result are from 1 input vector,
7017 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
7018 // is present, fall back to case 4.
7019 if (Subtarget->hasSSSE3()) {
7020 SmallVector<SDValue,16> pshufbMask;
7022 // If we have elements from both input vectors, set the high bit of the
7023 // shuffle mask element to zero out elements that come from V2 in the V1
7024 // mask, and elements that come from V1 in the V2 mask, so that the two
7025 // results can be OR'd together.
7026 bool TwoInputs = V1Used && V2Used;
7027 V1 = getPSHUFB(MaskVals, V1, dl, DAG);
7029 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
7031 // Calculate the shuffle mask for the second input, shuffle it, and
7032 // OR it with the first shuffled input.
7033 CommuteVectorShuffleMask(MaskVals, 8);
7034 V2 = getPSHUFB(MaskVals, V2, dl, DAG);
7035 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
7036 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
7039 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
7040 // and update MaskVals with new element order.
7041 std::bitset<8> InOrder;
7042 if (BestLoQuad >= 0) {
7043 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
7044 for (int i = 0; i != 4; ++i) {
7045 int idx = MaskVals[i];
7048 } else if ((idx / 4) == BestLoQuad) {
7053 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
7056 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
7057 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
7058 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
7060 getShufflePSHUFLWImmediate(SVOp), DAG);
7064 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
7065 // and update MaskVals with the new element order.
7066 if (BestHiQuad >= 0) {
7067 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
7068 for (unsigned i = 4; i != 8; ++i) {
7069 int idx = MaskVals[i];
7072 } else if ((idx / 4) == BestHiQuad) {
7073 MaskV[i] = (idx & 3) + 4;
7077 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
7080 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
7081 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
7082 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
7084 getShufflePSHUFHWImmediate(SVOp), DAG);
7088 // In case BestHi & BestLo were both -1, which means each quadword has a word
7089 // from each of the four input quadwords, calculate the InOrder bitvector now
7090 // before falling through to the insert/extract cleanup.
7091 if (BestLoQuad == -1 && BestHiQuad == -1) {
7093 for (int i = 0; i != 8; ++i)
7094 if (MaskVals[i] < 0 || MaskVals[i] == i)
7098 // The other elements are put in the right place using pextrw and pinsrw.
7099 for (unsigned i = 0; i != 8; ++i) {
7102 int EltIdx = MaskVals[i];
7105 SDValue ExtOp = (EltIdx < 8) ?
7106 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
7107 DAG.getIntPtrConstant(EltIdx)) :
7108 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
7109 DAG.getIntPtrConstant(EltIdx - 8));
7110 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
7111 DAG.getIntPtrConstant(i));
7116 /// \brief v16i16 shuffles
7118 /// FIXME: We only support generation of a single pshufb currently. We can
7119 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
7120 /// well (e.g 2 x pshufb + 1 x por).
7122 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
7123 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7124 SDValue V1 = SVOp->getOperand(0);
7125 SDValue V2 = SVOp->getOperand(1);
7128 if (V2.getOpcode() != ISD::UNDEF)
7131 SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
7132 return getPSHUFB(MaskVals, V1, dl, DAG);
7135 // v16i8 shuffles - Prefer shuffles in the following order:
7136 // 1. [ssse3] 1 x pshufb
7137 // 2. [ssse3] 2 x pshufb + 1 x por
7138 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
7139 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
7140 const X86Subtarget* Subtarget,
7141 SelectionDAG &DAG) {
7142 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7143 SDValue V1 = SVOp->getOperand(0);
7144 SDValue V2 = SVOp->getOperand(1);
7146 ArrayRef<int> MaskVals = SVOp->getMask();
7148 // Promote splats to a larger type which usually leads to more efficient code.
7149 // FIXME: Is this true if pshufb is available?
7150 if (SVOp->isSplat())
7151 return PromoteSplat(SVOp, DAG);
7153 // If we have SSSE3, case 1 is generated when all result bytes come from
7154 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
7155 // present, fall back to case 3.
7157 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
7158 if (Subtarget->hasSSSE3()) {
7159 SmallVector<SDValue,16> pshufbMask;
7161 // If all result elements are from one input vector, then only translate
7162 // undef mask values to 0x80 (zero out result) in the pshufb mask.
7164 // Otherwise, we have elements from both input vectors, and must zero out
7165 // elements that come from V2 in the first mask, and V1 in the second mask
7166 // so that we can OR them together.
7167 for (unsigned i = 0; i != 16; ++i) {
7168 int EltIdx = MaskVals[i];
7169 if (EltIdx < 0 || EltIdx >= 16)
7171 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
7173 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
7174 DAG.getNode(ISD::BUILD_VECTOR, dl,
7175 MVT::v16i8, pshufbMask));
7177 // As PSHUFB will zero elements with negative indices, it's safe to ignore
7178 // the 2nd operand if it's undefined or zero.
7179 if (V2.getOpcode() == ISD::UNDEF ||
7180 ISD::isBuildVectorAllZeros(V2.getNode()))
7183 // Calculate the shuffle mask for the second input, shuffle it, and
7184 // OR it with the first shuffled input.
7186 for (unsigned i = 0; i != 16; ++i) {
7187 int EltIdx = MaskVals[i];
7188 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
7189 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
7191 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
7192 DAG.getNode(ISD::BUILD_VECTOR, dl,
7193 MVT::v16i8, pshufbMask));
7194 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
7197 // No SSSE3 - Calculate in place words and then fix all out of place words
7198 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
7199 // the 16 different words that comprise the two doublequadword input vectors.
7200 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
7201 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
7203 for (int i = 0; i != 8; ++i) {
7204 int Elt0 = MaskVals[i*2];
7205 int Elt1 = MaskVals[i*2+1];
7207 // This word of the result is all undef, skip it.
7208 if (Elt0 < 0 && Elt1 < 0)
7211 // This word of the result is already in the correct place, skip it.
7212 if ((Elt0 == i*2) && (Elt1 == i*2+1))
7215 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
7216 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
7219 // If Elt0 and Elt1 are defined, are consecutive, and can be load
7220 // using a single extract together, load it and store it.
7221 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
7222 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
7223 DAG.getIntPtrConstant(Elt1 / 2));
7224 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
7225 DAG.getIntPtrConstant(i));
7229 // If Elt1 is defined, extract it from the appropriate source. If the
7230 // source byte is not also odd, shift the extracted word left 8 bits
7231 // otherwise clear the bottom 8 bits if we need to do an or.
7233 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
7234 DAG.getIntPtrConstant(Elt1 / 2));
7235 if ((Elt1 & 1) == 0)
7236 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
7238 TLI.getShiftAmountTy(InsElt.getValueType())));
7240 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
7241 DAG.getConstant(0xFF00, MVT::i16));
7243 // If Elt0 is defined, extract it from the appropriate source. If the
7244 // source byte is not also even, shift the extracted word right 8 bits. If
7245 // Elt1 was also defined, OR the extracted values together before
7246 // inserting them in the result.
7248 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
7249 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
7250 if ((Elt0 & 1) != 0)
7251 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
7253 TLI.getShiftAmountTy(InsElt0.getValueType())));
7255 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
7256 DAG.getConstant(0x00FF, MVT::i16));
7257 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
7260 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
7261 DAG.getIntPtrConstant(i));
7263 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
7266 // v32i8 shuffles - Translate to VPSHUFB if possible.
7268 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
7269 const X86Subtarget *Subtarget,
7270 SelectionDAG &DAG) {
7271 MVT VT = SVOp->getSimpleValueType(0);
7272 SDValue V1 = SVOp->getOperand(0);
7273 SDValue V2 = SVOp->getOperand(1);
7275 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
7277 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7278 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
7279 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
7281 // VPSHUFB may be generated if
7282 // (1) one of input vector is undefined or zeroinitializer.
7283 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
7284 // And (2) the mask indexes don't cross the 128-bit lane.
7285 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
7286 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
7289 if (V1IsAllZero && !V2IsAllZero) {
7290 CommuteVectorShuffleMask(MaskVals, 32);
7293 return getPSHUFB(MaskVals, V1, dl, DAG);
7296 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
7297 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
7298 /// done when every pair / quad of shuffle mask elements point to elements in
7299 /// the right sequence. e.g.
7300 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
7302 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
7303 SelectionDAG &DAG) {
7304 MVT VT = SVOp->getSimpleValueType(0);
7306 unsigned NumElems = VT.getVectorNumElements();
7309 switch (VT.SimpleTy) {
7310 default: llvm_unreachable("Unexpected!");
7313 return SDValue(SVOp, 0);
7314 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
7315 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
7316 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
7317 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
7318 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
7319 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
7322 SmallVector<int, 8> MaskVec;
7323 for (unsigned i = 0; i != NumElems; i += Scale) {
7325 for (unsigned j = 0; j != Scale; ++j) {
7326 int EltIdx = SVOp->getMaskElt(i+j);
7330 StartIdx = (EltIdx / Scale);
7331 if (EltIdx != (int)(StartIdx*Scale + j))
7334 MaskVec.push_back(StartIdx);
7337 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
7338 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
7339 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
7342 /// getVZextMovL - Return a zero-extending vector move low node.
7344 static SDValue getVZextMovL(MVT VT, MVT OpVT,
7345 SDValue SrcOp, SelectionDAG &DAG,
7346 const X86Subtarget *Subtarget, SDLoc dl) {
7347 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
7348 LoadSDNode *LD = nullptr;
7349 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
7350 LD = dyn_cast<LoadSDNode>(SrcOp);
7352 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
7354 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
7355 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
7356 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
7357 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
7358 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
7360 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
7361 return DAG.getNode(ISD::BITCAST, dl, VT,
7362 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
7363 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7371 return DAG.getNode(ISD::BITCAST, dl, VT,
7372 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
7373 DAG.getNode(ISD::BITCAST, dl,
7377 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
7378 /// which could not be matched by any known target speficic shuffle
7380 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7382 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
7383 if (NewOp.getNode())
7386 MVT VT = SVOp->getSimpleValueType(0);
7388 unsigned NumElems = VT.getVectorNumElements();
7389 unsigned NumLaneElems = NumElems / 2;
7392 MVT EltVT = VT.getVectorElementType();
7393 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
7396 SmallVector<int, 16> Mask;
7397 for (unsigned l = 0; l < 2; ++l) {
7398 // Build a shuffle mask for the output, discovering on the fly which
7399 // input vectors to use as shuffle operands (recorded in InputUsed).
7400 // If building a suitable shuffle vector proves too hard, then bail
7401 // out with UseBuildVector set.
7402 bool UseBuildVector = false;
7403 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
7404 unsigned LaneStart = l * NumLaneElems;
7405 for (unsigned i = 0; i != NumLaneElems; ++i) {
7406 // The mask element. This indexes into the input.
7407 int Idx = SVOp->getMaskElt(i+LaneStart);
7409 // the mask element does not index into any input vector.
7414 // The input vector this mask element indexes into.
7415 int Input = Idx / NumLaneElems;
7417 // Turn the index into an offset from the start of the input vector.
7418 Idx -= Input * NumLaneElems;
7420 // Find or create a shuffle vector operand to hold this input.
7422 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
7423 if (InputUsed[OpNo] == Input)
7424 // This input vector is already an operand.
7426 if (InputUsed[OpNo] < 0) {
7427 // Create a new operand for this input vector.
7428 InputUsed[OpNo] = Input;
7433 if (OpNo >= array_lengthof(InputUsed)) {
7434 // More than two input vectors used! Give up on trying to create a
7435 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
7436 UseBuildVector = true;
7440 // Add the mask index for the new shuffle vector.
7441 Mask.push_back(Idx + OpNo * NumLaneElems);
7444 if (UseBuildVector) {
7445 SmallVector<SDValue, 16> SVOps;
7446 for (unsigned i = 0; i != NumLaneElems; ++i) {
7447 // The mask element. This indexes into the input.
7448 int Idx = SVOp->getMaskElt(i+LaneStart);
7450 SVOps.push_back(DAG.getUNDEF(EltVT));
7454 // The input vector this mask element indexes into.
7455 int Input = Idx / NumElems;
7457 // Turn the index into an offset from the start of the input vector.
7458 Idx -= Input * NumElems;
7460 // Extract the vector element by hand.
7461 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
7462 SVOp->getOperand(Input),
7463 DAG.getIntPtrConstant(Idx)));
7466 // Construct the output using a BUILD_VECTOR.
7467 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
7468 } else if (InputUsed[0] < 0) {
7469 // No input vectors were used! The result is undefined.
7470 Output[l] = DAG.getUNDEF(NVT);
7472 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
7473 (InputUsed[0] % 2) * NumLaneElems,
7475 // If only one input was used, use an undefined vector for the other.
7476 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
7477 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
7478 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
7479 // At least one input vector was used. Create a new shuffle vector.
7480 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
7486 // Concatenate the result back
7487 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
7490 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
7491 /// 4 elements, and match them with several different shuffle types.
7493 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7494 SDValue V1 = SVOp->getOperand(0);
7495 SDValue V2 = SVOp->getOperand(1);
7497 MVT VT = SVOp->getSimpleValueType(0);
7499 assert(VT.is128BitVector() && "Unsupported vector size");
7501 std::pair<int, int> Locs[4];
7502 int Mask1[] = { -1, -1, -1, -1 };
7503 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
7507 for (unsigned i = 0; i != 4; ++i) {
7508 int Idx = PermMask[i];
7510 Locs[i] = std::make_pair(-1, -1);
7512 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
7514 Locs[i] = std::make_pair(0, NumLo);
7518 Locs[i] = std::make_pair(1, NumHi);
7520 Mask1[2+NumHi] = Idx;
7526 if (NumLo <= 2 && NumHi <= 2) {
7527 // If no more than two elements come from either vector. This can be
7528 // implemented with two shuffles. First shuffle gather the elements.
7529 // The second shuffle, which takes the first shuffle as both of its
7530 // vector operands, put the elements into the right order.
7531 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7533 int Mask2[] = { -1, -1, -1, -1 };
7535 for (unsigned i = 0; i != 4; ++i)
7536 if (Locs[i].first != -1) {
7537 unsigned Idx = (i < 2) ? 0 : 4;
7538 Idx += Locs[i].first * 2 + Locs[i].second;
7542 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
7545 if (NumLo == 3 || NumHi == 3) {
7546 // Otherwise, we must have three elements from one vector, call it X, and
7547 // one element from the other, call it Y. First, use a shufps to build an
7548 // intermediate vector with the one element from Y and the element from X
7549 // that will be in the same half in the final destination (the indexes don't
7550 // matter). Then, use a shufps to build the final vector, taking the half
7551 // containing the element from Y from the intermediate, and the other half
7554 // Normalize it so the 3 elements come from V1.
7555 CommuteVectorShuffleMask(PermMask, 4);
7559 // Find the element from V2.
7561 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
7562 int Val = PermMask[HiIndex];
7569 Mask1[0] = PermMask[HiIndex];
7571 Mask1[2] = PermMask[HiIndex^1];
7573 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7576 Mask1[0] = PermMask[0];
7577 Mask1[1] = PermMask[1];
7578 Mask1[2] = HiIndex & 1 ? 6 : 4;
7579 Mask1[3] = HiIndex & 1 ? 4 : 6;
7580 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7583 Mask1[0] = HiIndex & 1 ? 2 : 0;
7584 Mask1[1] = HiIndex & 1 ? 0 : 2;
7585 Mask1[2] = PermMask[2];
7586 Mask1[3] = PermMask[3];
7591 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7594 // Break it into (shuffle shuffle_hi, shuffle_lo).
7595 int LoMask[] = { -1, -1, -1, -1 };
7596 int HiMask[] = { -1, -1, -1, -1 };
7598 int *MaskPtr = LoMask;
7599 unsigned MaskIdx = 0;
7602 for (unsigned i = 0; i != 4; ++i) {
7609 int Idx = PermMask[i];
7611 Locs[i] = std::make_pair(-1, -1);
7612 } else if (Idx < 4) {
7613 Locs[i] = std::make_pair(MaskIdx, LoIdx);
7614 MaskPtr[LoIdx] = Idx;
7617 Locs[i] = std::make_pair(MaskIdx, HiIdx);
7618 MaskPtr[HiIdx] = Idx;
7623 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7624 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7625 int MaskOps[] = { -1, -1, -1, -1 };
7626 for (unsigned i = 0; i != 4; ++i)
7627 if (Locs[i].first != -1)
7628 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7629 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7632 static bool MayFoldVectorLoad(SDValue V) {
7633 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7634 V = V.getOperand(0);
7636 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7637 V = V.getOperand(0);
7638 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7639 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7640 // BUILD_VECTOR (load), undef
7641 V = V.getOperand(0);
7643 return MayFoldLoad(V);
7647 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7648 MVT VT = Op.getSimpleValueType();
7650 // Canonizalize to v2f64.
7651 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7652 return DAG.getNode(ISD::BITCAST, dl, VT,
7653 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7658 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7660 SDValue V1 = Op.getOperand(0);
7661 SDValue V2 = Op.getOperand(1);
7662 MVT VT = Op.getSimpleValueType();
7664 assert(VT != MVT::v2i64 && "unsupported shuffle type");
7666 if (HasSSE2 && VT == MVT::v2f64)
7667 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7669 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7670 return DAG.getNode(ISD::BITCAST, dl, VT,
7671 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7672 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7673 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7677 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7678 SDValue V1 = Op.getOperand(0);
7679 SDValue V2 = Op.getOperand(1);
7680 MVT VT = Op.getSimpleValueType();
7682 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7683 "unsupported shuffle type");
7685 if (V2.getOpcode() == ISD::UNDEF)
7689 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7693 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7694 SDValue V1 = Op.getOperand(0);
7695 SDValue V2 = Op.getOperand(1);
7696 MVT VT = Op.getSimpleValueType();
7697 unsigned NumElems = VT.getVectorNumElements();
7699 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7700 // operand of these instructions is only memory, so check if there's a
7701 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7703 bool CanFoldLoad = false;
7705 // Trivial case, when V2 comes from a load.
7706 if (MayFoldVectorLoad(V2))
7709 // When V1 is a load, it can be folded later into a store in isel, example:
7710 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7712 // (MOVLPSmr addr:$src1, VR128:$src2)
7713 // So, recognize this potential and also use MOVLPS or MOVLPD
7714 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7717 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7719 if (HasSSE2 && NumElems == 2)
7720 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7723 // If we don't care about the second element, proceed to use movss.
7724 if (SVOp->getMaskElt(1) != -1)
7725 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7728 // movl and movlp will both match v2i64, but v2i64 is never matched by
7729 // movl earlier because we make it strict to avoid messing with the movlp load
7730 // folding logic (see the code above getMOVLP call). Match it here then,
7731 // this is horrible, but will stay like this until we move all shuffle
7732 // matching to x86 specific nodes. Note that for the 1st condition all
7733 // types are matched with movsd.
7735 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7736 // as to remove this logic from here, as much as possible
7737 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7738 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7739 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7742 assert(VT != MVT::v4i32 && "unsupported shuffle type");
7744 // Invert the operand order and use SHUFPS to match it.
7745 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7746 getShuffleSHUFImmediate(SVOp), DAG);
7749 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
7750 SelectionDAG &DAG) {
7752 MVT VT = Load->getSimpleValueType(0);
7753 MVT EVT = VT.getVectorElementType();
7754 SDValue Addr = Load->getOperand(1);
7755 SDValue NewAddr = DAG.getNode(
7756 ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
7757 DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
7760 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
7761 DAG.getMachineFunction().getMachineMemOperand(
7762 Load->getMemOperand(), 0, EVT.getStoreSize()));
7766 // It is only safe to call this function if isINSERTPSMask is true for
7767 // this shufflevector mask.
7768 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
7769 SelectionDAG &DAG) {
7770 // Generate an insertps instruction when inserting an f32 from memory onto a
7771 // v4f32 or when copying a member from one v4f32 to another.
7772 // We also use it for transferring i32 from one register to another,
7773 // since it simply copies the same bits.
7774 // If we're transferring an i32 from memory to a specific element in a
7775 // register, we output a generic DAG that will match the PINSRD
7777 MVT VT = SVOp->getSimpleValueType(0);
7778 MVT EVT = VT.getVectorElementType();
7779 SDValue V1 = SVOp->getOperand(0);
7780 SDValue V2 = SVOp->getOperand(1);
7781 auto Mask = SVOp->getMask();
7782 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
7783 "unsupported vector type for insertps/pinsrd");
7785 auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
7786 auto FromV2Predicate = [](const int &i) { return i >= 4; };
7787 int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
7795 DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
7798 assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
7799 "More than one element from V1 and from V2, or no elements from one "
7800 "of the vectors. This case should not have returned true from "
7805 std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
7808 unsigned SrcIndex = Mask[DestIndex] % 4;
7809 if (MayFoldLoad(From)) {
7810 // Trivial case, when From comes from a load and is only used by the
7811 // shuffle. Make it use insertps from the vector that we need from that
7814 NarrowVectorLoadToElement(cast<LoadSDNode>(From), SrcIndex, DAG);
7815 if (!NewLoad.getNode())
7818 if (EVT == MVT::f32) {
7819 // Create this as a scalar to vector to match the instruction pattern.
7820 SDValue LoadScalarToVector =
7821 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
7822 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
7823 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
7825 } else { // EVT == MVT::i32
7826 // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
7827 // instruction, to match the PINSRD instruction, which loads an i32 to a
7828 // certain vector element.
7829 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
7830 DAG.getConstant(DestIndex, MVT::i32));
7834 // Vector-element-to-vector
7835 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
7836 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
7839 // Reduce a vector shuffle to zext.
7840 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7841 SelectionDAG &DAG) {
7842 // PMOVZX is only available from SSE41.
7843 if (!Subtarget->hasSSE41())
7846 MVT VT = Op.getSimpleValueType();
7848 // Only AVX2 support 256-bit vector integer extending.
7849 if (!Subtarget->hasInt256() && VT.is256BitVector())
7852 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7854 SDValue V1 = Op.getOperand(0);
7855 SDValue V2 = Op.getOperand(1);
7856 unsigned NumElems = VT.getVectorNumElements();
7858 // Extending is an unary operation and the element type of the source vector
7859 // won't be equal to or larger than i64.
7860 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7861 VT.getVectorElementType() == MVT::i64)
7864 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7865 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7866 while ((1U << Shift) < NumElems) {
7867 if (SVOp->getMaskElt(1U << Shift) == 1)
7870 // The maximal ratio is 8, i.e. from i8 to i64.
7875 // Check the shuffle mask.
7876 unsigned Mask = (1U << Shift) - 1;
7877 for (unsigned i = 0; i != NumElems; ++i) {
7878 int EltIdx = SVOp->getMaskElt(i);
7879 if ((i & Mask) != 0 && EltIdx != -1)
7881 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7885 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7886 MVT NeVT = MVT::getIntegerVT(NBits);
7887 MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7889 if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7892 // Simplify the operand as it's prepared to be fed into shuffle.
7893 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7894 if (V1.getOpcode() == ISD::BITCAST &&
7895 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7896 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7897 V1.getOperand(0).getOperand(0)
7898 .getSimpleValueType().getSizeInBits() == SignificantBits) {
7899 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7900 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7901 ConstantSDNode *CIdx =
7902 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7903 // If it's foldable, i.e. normal load with single use, we will let code
7904 // selection to fold it. Otherwise, we will short the conversion sequence.
7905 if (CIdx && CIdx->getZExtValue() == 0 &&
7906 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7907 MVT FullVT = V.getSimpleValueType();
7908 MVT V1VT = V1.getSimpleValueType();
7909 if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7910 // The "ext_vec_elt" node is wider than the result node.
7911 // In this case we should extract subvector from V.
7912 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7913 unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7914 MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7915 FullVT.getVectorNumElements()/Ratio);
7916 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7917 DAG.getIntPtrConstant(0));
7919 V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7923 return DAG.getNode(ISD::BITCAST, DL, VT,
7924 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7927 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7928 SelectionDAG &DAG) {
7929 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7930 MVT VT = Op.getSimpleValueType();
7932 SDValue V1 = Op.getOperand(0);
7933 SDValue V2 = Op.getOperand(1);
7935 if (isZeroShuffle(SVOp))
7936 return getZeroVector(VT, Subtarget, DAG, dl);
7938 // Handle splat operations
7939 if (SVOp->isSplat()) {
7940 // Use vbroadcast whenever the splat comes from a foldable load
7941 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7942 if (Broadcast.getNode())
7946 // Check integer expanding shuffles.
7947 SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7948 if (NewOp.getNode())
7951 // If the shuffle can be profitably rewritten as a narrower shuffle, then
7953 if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
7955 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7956 if (NewOp.getNode())
7957 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7958 } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
7959 // FIXME: Figure out a cleaner way to do this.
7960 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7961 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7962 if (NewOp.getNode()) {
7963 MVT NewVT = NewOp.getSimpleValueType();
7964 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7965 NewVT, true, false))
7966 return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
7969 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7970 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7971 if (NewOp.getNode()) {
7972 MVT NewVT = NewOp.getSimpleValueType();
7973 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7974 return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
7983 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7984 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7985 SDValue V1 = Op.getOperand(0);
7986 SDValue V2 = Op.getOperand(1);
7987 MVT VT = Op.getSimpleValueType();
7989 unsigned NumElems = VT.getVectorNumElements();
7990 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7991 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7992 bool V1IsSplat = false;
7993 bool V2IsSplat = false;
7994 bool HasSSE2 = Subtarget->hasSSE2();
7995 bool HasFp256 = Subtarget->hasFp256();
7996 bool HasInt256 = Subtarget->hasInt256();
7997 MachineFunction &MF = DAG.getMachineFunction();
7998 bool OptForSize = MF.getFunction()->getAttributes().
7999 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
8001 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
8003 if (V1IsUndef && V2IsUndef)
8004 return DAG.getUNDEF(VT);
8006 // When we create a shuffle node we put the UNDEF node to second operand,
8007 // but in some cases the first operand may be transformed to UNDEF.
8008 // In this case we should just commute the node.
8010 return CommuteVectorShuffle(SVOp, DAG);
8012 // Vector shuffle lowering takes 3 steps:
8014 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
8015 // narrowing and commutation of operands should be handled.
8016 // 2) Matching of shuffles with known shuffle masks to x86 target specific
8018 // 3) Rewriting of unmatched masks into new generic shuffle operations,
8019 // so the shuffle can be broken into other shuffles and the legalizer can
8020 // try the lowering again.
8022 // The general idea is that no vector_shuffle operation should be left to
8023 // be matched during isel, all of them must be converted to a target specific
8026 // Normalize the input vectors. Here splats, zeroed vectors, profitable
8027 // narrowing and commutation of operands should be handled. The actual code
8028 // doesn't include all of those, work in progress...
8029 SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
8030 if (NewOp.getNode())
8033 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
8035 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
8036 // unpckh_undef). Only use pshufd if speed is more important than size.
8037 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
8038 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
8039 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
8040 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
8042 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
8043 V2IsUndef && MayFoldVectorLoad(V1))
8044 return getMOVDDup(Op, dl, V1, DAG);
8046 if (isMOVHLPS_v_undef_Mask(M, VT))
8047 return getMOVHighToLow(Op, dl, DAG);
8049 // Use to match splats
8050 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
8051 (VT == MVT::v2f64 || VT == MVT::v2i64))
8052 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
8054 if (isPSHUFDMask(M, VT)) {
8055 // The actual implementation will match the mask in the if above and then
8056 // during isel it can match several different instructions, not only pshufd
8057 // as its name says, sad but true, emulate the behavior for now...
8058 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
8059 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
8061 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
8063 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
8064 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
8066 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
8067 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
8070 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
8074 if (isPALIGNRMask(M, VT, Subtarget))
8075 return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
8076 getShufflePALIGNRImmediate(SVOp),
8079 // Check if this can be converted into a logical shift.
8080 bool isLeft = false;
8083 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
8084 if (isShift && ShVal.hasOneUse()) {
8085 // If the shifted value has multiple uses, it may be cheaper to use
8086 // v_set0 + movlhps or movhlps, etc.
8087 MVT EltVT = VT.getVectorElementType();
8088 ShAmt *= EltVT.getSizeInBits();
8089 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
8092 if (isMOVLMask(M, VT)) {
8093 if (ISD::isBuildVectorAllZeros(V1.getNode()))
8094 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
8095 if (!isMOVLPMask(M, VT)) {
8096 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
8097 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
8099 if (VT == MVT::v4i32 || VT == MVT::v4f32)
8100 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
8104 // FIXME: fold these into legal mask.
8105 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
8106 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
8108 if (isMOVHLPSMask(M, VT))
8109 return getMOVHighToLow(Op, dl, DAG);
8111 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
8112 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
8114 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
8115 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
8117 if (isMOVLPMask(M, VT))
8118 return getMOVLP(Op, dl, DAG, HasSSE2);
8120 if (ShouldXformToMOVHLPS(M, VT) ||
8121 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
8122 return CommuteVectorShuffle(SVOp, DAG);
8125 // No better options. Use a vshldq / vsrldq.
8126 MVT EltVT = VT.getVectorElementType();
8127 ShAmt *= EltVT.getSizeInBits();
8128 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
8131 bool Commuted = false;
8132 // FIXME: This should also accept a bitcast of a splat? Be careful, not
8133 // 1,1,1,1 -> v8i16 though.
8134 V1IsSplat = isSplatVector(V1.getNode());
8135 V2IsSplat = isSplatVector(V2.getNode());
8137 // Canonicalize the splat or undef, if present, to be on the RHS.
8138 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
8139 CommuteVectorShuffleMask(M, NumElems);
8141 std::swap(V1IsSplat, V2IsSplat);
8145 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
8146 // Shuffling low element of v1 into undef, just return v1.
8149 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
8150 // the instruction selector will not match, so get a canonical MOVL with
8151 // swapped operands to undo the commute.
8152 return getMOVL(DAG, dl, VT, V2, V1);
8155 if (isUNPCKLMask(M, VT, HasInt256))
8156 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
8158 if (isUNPCKHMask(M, VT, HasInt256))
8159 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
8162 // Normalize mask so all entries that point to V2 points to its first
8163 // element then try to match unpck{h|l} again. If match, return a
8164 // new vector_shuffle with the corrected mask.p
8165 SmallVector<int, 8> NewMask(M.begin(), M.end());
8166 NormalizeMask(NewMask, NumElems);
8167 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
8168 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
8169 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
8170 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
8174 // Commute is back and try unpck* again.
8175 // FIXME: this seems wrong.
8176 CommuteVectorShuffleMask(M, NumElems);
8178 std::swap(V1IsSplat, V2IsSplat);
8180 if (isUNPCKLMask(M, VT, HasInt256))
8181 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
8183 if (isUNPCKHMask(M, VT, HasInt256))
8184 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
8187 // Normalize the node to match x86 shuffle ops if needed
8188 if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
8189 return CommuteVectorShuffle(SVOp, DAG);
8191 // The checks below are all present in isShuffleMaskLegal, but they are
8192 // inlined here right now to enable us to directly emit target specific
8193 // nodes, and remove one by one until they don't return Op anymore.
8195 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
8196 SVOp->getSplatIndex() == 0 && V2IsUndef) {
8197 if (VT == MVT::v2f64 || VT == MVT::v2i64)
8198 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
8201 if (isPSHUFHWMask(M, VT, HasInt256))
8202 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
8203 getShufflePSHUFHWImmediate(SVOp),
8206 if (isPSHUFLWMask(M, VT, HasInt256))
8207 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
8208 getShufflePSHUFLWImmediate(SVOp),
8211 if (isSHUFPMask(M, VT))
8212 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
8213 getShuffleSHUFImmediate(SVOp), DAG);
8215 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
8216 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
8217 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
8218 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
8220 //===--------------------------------------------------------------------===//
8221 // Generate target specific nodes for 128 or 256-bit shuffles only
8222 // supported in the AVX instruction set.
8225 // Handle VMOVDDUPY permutations
8226 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
8227 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
8229 // Handle VPERMILPS/D* permutations
8230 if (isVPERMILPMask(M, VT)) {
8231 if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
8232 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
8233 getShuffleSHUFImmediate(SVOp), DAG);
8234 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
8235 getShuffleSHUFImmediate(SVOp), DAG);
8239 if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
8240 return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
8241 Idx*(NumElems/2), DAG, dl);
8243 // Handle VPERM2F128/VPERM2I128 permutations
8244 if (isVPERM2X128Mask(M, VT, HasFp256))
8245 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
8246 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
8249 if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
8251 return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
8253 if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
8254 return getINSERTPS(SVOp, dl, DAG);
8257 if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
8258 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
8260 if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
8261 VT.is512BitVector()) {
8262 MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
8263 MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
8264 SmallVector<SDValue, 16> permclMask;
8265 for (unsigned i = 0; i != NumElems; ++i) {
8266 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
8269 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
8271 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
8272 return DAG.getNode(X86ISD::VPERMV, dl, VT,
8273 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
8274 return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
8275 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
8278 //===--------------------------------------------------------------------===//
8279 // Since no target specific shuffle was selected for this generic one,
8280 // lower it into other known shuffles. FIXME: this isn't true yet, but
8281 // this is the plan.
8284 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
8285 if (VT == MVT::v8i16) {
8286 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
8287 if (NewOp.getNode())
8291 if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
8292 SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
8293 if (NewOp.getNode())
8297 if (VT == MVT::v16i8) {
8298 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
8299 if (NewOp.getNode())
8303 if (VT == MVT::v32i8) {
8304 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
8305 if (NewOp.getNode())
8309 // Handle all 128-bit wide vectors with 4 elements, and match them with
8310 // several different shuffle types.
8311 if (NumElems == 4 && VT.is128BitVector())
8312 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
8314 // Handle general 256-bit shuffles
8315 if (VT.is256BitVector())
8316 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
8321 // This function assumes its argument is a BUILD_VECTOR of constants or
8322 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
8324 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
8325 unsigned &MaskValue) {
8327 unsigned NumElems = BuildVector->getNumOperands();
8328 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
8329 unsigned NumLanes = (NumElems - 1) / 8 + 1;
8330 unsigned NumElemsInLane = NumElems / NumLanes;
8332 // Blend for v16i16 should be symetric for the both lanes.
8333 for (unsigned i = 0; i < NumElemsInLane; ++i) {
8334 SDValue EltCond = BuildVector->getOperand(i);
8335 SDValue SndLaneEltCond =
8336 (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
8338 int Lane1Cond = -1, Lane2Cond = -1;
8339 if (isa<ConstantSDNode>(EltCond))
8340 Lane1Cond = !isZero(EltCond);
8341 if (isa<ConstantSDNode>(SndLaneEltCond))
8342 Lane2Cond = !isZero(SndLaneEltCond);
8344 if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
8345 // Lane1Cond != 0, means we want the first argument.
8346 // Lane1Cond == 0, means we want the second argument.
8347 // The encoding of this argument is 0 for the first argument, 1
8348 // for the second. Therefore, invert the condition.
8349 MaskValue |= !Lane1Cond << i;
8350 else if (Lane1Cond < 0)
8351 MaskValue |= !Lane2Cond << i;
8358 // Try to lower a vselect node into a simple blend instruction.
8359 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
8360 SelectionDAG &DAG) {
8361 SDValue Cond = Op.getOperand(0);
8362 SDValue LHS = Op.getOperand(1);
8363 SDValue RHS = Op.getOperand(2);
8365 MVT VT = Op.getSimpleValueType();
8366 MVT EltVT = VT.getVectorElementType();
8367 unsigned NumElems = VT.getVectorNumElements();
8369 // There is no blend with immediate in AVX-512.
8370 if (VT.is512BitVector())
8373 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
8375 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
8378 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
8381 // Check the mask for BLEND and build the value.
8382 unsigned MaskValue = 0;
8383 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
8386 // Convert i32 vectors to floating point if it is not AVX2.
8387 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
8389 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
8390 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
8392 LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
8393 RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
8396 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
8397 DAG.getConstant(MaskValue, MVT::i32));
8398 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
8401 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
8402 SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
8403 if (BlendOp.getNode())
8406 // Some types for vselect were previously set to Expand, not Legal or
8407 // Custom. Return an empty SDValue so we fall-through to Expand, after
8408 // the Custom lowering phase.
8409 MVT VT = Op.getSimpleValueType();
8410 switch (VT.SimpleTy) {
8418 // We couldn't create a "Blend with immediate" node.
8419 // This node should still be legal, but we'll have to emit a blendv*
8424 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8425 MVT VT = Op.getSimpleValueType();
8428 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
8431 if (VT.getSizeInBits() == 8) {
8432 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
8433 Op.getOperand(0), Op.getOperand(1));
8434 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
8435 DAG.getValueType(VT));
8436 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8439 if (VT.getSizeInBits() == 16) {
8440 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8441 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
8443 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8444 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8445 DAG.getNode(ISD::BITCAST, dl,
8449 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
8450 Op.getOperand(0), Op.getOperand(1));
8451 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
8452 DAG.getValueType(VT));
8453 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8456 if (VT == MVT::f32) {
8457 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
8458 // the result back to FR32 register. It's only worth matching if the
8459 // result has a single use which is a store or a bitcast to i32. And in
8460 // the case of a store, it's not worth it if the index is a constant 0,
8461 // because a MOVSSmr can be used instead, which is smaller and faster.
8462 if (!Op.hasOneUse())
8464 SDNode *User = *Op.getNode()->use_begin();
8465 if ((User->getOpcode() != ISD::STORE ||
8466 (isa<ConstantSDNode>(Op.getOperand(1)) &&
8467 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
8468 (User->getOpcode() != ISD::BITCAST ||
8469 User->getValueType(0) != MVT::i32))
8471 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8472 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
8475 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
8478 if (VT == MVT::i32 || VT == MVT::i64) {
8479 // ExtractPS/pextrq works with constant index.
8480 if (isa<ConstantSDNode>(Op.getOperand(1)))
8486 /// Extract one bit from mask vector, like v16i1 or v8i1.
8487 /// AVX-512 feature.
8489 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
8490 SDValue Vec = Op.getOperand(0);
8492 MVT VecVT = Vec.getSimpleValueType();
8493 SDValue Idx = Op.getOperand(1);
8494 MVT EltVT = Op.getSimpleValueType();
8496 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
8498 // variable index can't be handled in mask registers,
8499 // extend vector to VR512
8500 if (!isa<ConstantSDNode>(Idx)) {
8501 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
8502 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
8503 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
8504 ExtVT.getVectorElementType(), Ext, Idx);
8505 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
8508 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8509 const TargetRegisterClass* rc = getRegClassFor(VecVT);
8510 unsigned MaxSift = rc->getSize()*8 - 1;
8511 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
8512 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8513 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
8514 DAG.getConstant(MaxSift, MVT::i8));
8515 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
8516 DAG.getIntPtrConstant(0));
8520 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
8521 SelectionDAG &DAG) const {
8523 SDValue Vec = Op.getOperand(0);
8524 MVT VecVT = Vec.getSimpleValueType();
8525 SDValue Idx = Op.getOperand(1);
8527 if (Op.getSimpleValueType() == MVT::i1)
8528 return ExtractBitFromMaskVector(Op, DAG);
8530 if (!isa<ConstantSDNode>(Idx)) {
8531 if (VecVT.is512BitVector() ||
8532 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
8533 VecVT.getVectorElementType().getSizeInBits() == 32)) {
8536 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
8537 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
8538 MaskEltVT.getSizeInBits());
8540 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
8541 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
8542 getZeroVector(MaskVT, Subtarget, DAG, dl),
8543 Idx, DAG.getConstant(0, getPointerTy()));
8544 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
8545 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
8546 Perm, DAG.getConstant(0, getPointerTy()));
8551 // If this is a 256-bit vector result, first extract the 128-bit vector and
8552 // then extract the element from the 128-bit vector.
8553 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
8555 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8556 // Get the 128-bit vector.
8557 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
8558 MVT EltVT = VecVT.getVectorElementType();
8560 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
8562 //if (IdxVal >= NumElems/2)
8563 // IdxVal -= NumElems/2;
8564 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
8565 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
8566 DAG.getConstant(IdxVal, MVT::i32));
8569 assert(VecVT.is128BitVector() && "Unexpected vector length");
8571 if (Subtarget->hasSSE41()) {
8572 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
8577 MVT VT = Op.getSimpleValueType();
8578 // TODO: handle v16i8.
8579 if (VT.getSizeInBits() == 16) {
8580 SDValue Vec = Op.getOperand(0);
8581 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8583 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8584 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8585 DAG.getNode(ISD::BITCAST, dl,
8588 // Transform it so it match pextrw which produces a 32-bit result.
8589 MVT EltVT = MVT::i32;
8590 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
8591 Op.getOperand(0), Op.getOperand(1));
8592 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
8593 DAG.getValueType(VT));
8594 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8597 if (VT.getSizeInBits() == 32) {
8598 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8602 // SHUFPS the element to the lowest double word, then movss.
8603 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
8604 MVT VVT = Op.getOperand(0).getSimpleValueType();
8605 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8606 DAG.getUNDEF(VVT), Mask);
8607 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8608 DAG.getIntPtrConstant(0));
8611 if (VT.getSizeInBits() == 64) {
8612 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
8613 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
8614 // to match extract_elt for f64.
8615 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8619 // UNPCKHPD the element to the lowest double word, then movsd.
8620 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
8621 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
8622 int Mask[2] = { 1, -1 };
8623 MVT VVT = Op.getOperand(0).getSimpleValueType();
8624 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8625 DAG.getUNDEF(VVT), Mask);
8626 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8627 DAG.getIntPtrConstant(0));
8633 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8634 MVT VT = Op.getSimpleValueType();
8635 MVT EltVT = VT.getVectorElementType();
8638 SDValue N0 = Op.getOperand(0);
8639 SDValue N1 = Op.getOperand(1);
8640 SDValue N2 = Op.getOperand(2);
8642 if (!VT.is128BitVector())
8645 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
8646 isa<ConstantSDNode>(N2)) {
8648 if (VT == MVT::v8i16)
8649 Opc = X86ISD::PINSRW;
8650 else if (VT == MVT::v16i8)
8651 Opc = X86ISD::PINSRB;
8653 Opc = X86ISD::PINSRB;
8655 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
8657 if (N1.getValueType() != MVT::i32)
8658 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8659 if (N2.getValueType() != MVT::i32)
8660 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8661 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
8664 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
8665 // Bits [7:6] of the constant are the source select. This will always be
8666 // zero here. The DAG Combiner may combine an extract_elt index into these
8667 // bits. For example (insert (extract, 3), 2) could be matched by putting
8668 // the '3' into bits [7:6] of X86ISD::INSERTPS.
8669 // Bits [5:4] of the constant are the destination select. This is the
8670 // value of the incoming immediate.
8671 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
8672 // combine either bitwise AND or insert of float 0.0 to set these bits.
8673 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
8674 // Create this as a scalar to vector..
8675 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
8676 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
8679 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
8680 // PINSR* works with constant index.
8686 /// Insert one bit to mask vector, like v16i1 or v8i1.
8687 /// AVX-512 feature.
8689 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
8691 SDValue Vec = Op.getOperand(0);
8692 SDValue Elt = Op.getOperand(1);
8693 SDValue Idx = Op.getOperand(2);
8694 MVT VecVT = Vec.getSimpleValueType();
8696 if (!isa<ConstantSDNode>(Idx)) {
8697 // Non constant index. Extend source and destination,
8698 // insert element and then truncate the result.
8699 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
8700 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
8701 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
8702 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
8703 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
8704 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
8707 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8708 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
8709 if (Vec.getOpcode() == ISD::UNDEF)
8710 return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8711 DAG.getConstant(IdxVal, MVT::i8));
8712 const TargetRegisterClass* rc = getRegClassFor(VecVT);
8713 unsigned MaxSift = rc->getSize()*8 - 1;
8714 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8715 DAG.getConstant(MaxSift, MVT::i8));
8716 EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
8717 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8718 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
8721 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
8722 MVT VT = Op.getSimpleValueType();
8723 MVT EltVT = VT.getVectorElementType();
8725 if (EltVT == MVT::i1)
8726 return InsertBitToMaskVector(Op, DAG);
8729 SDValue N0 = Op.getOperand(0);
8730 SDValue N1 = Op.getOperand(1);
8731 SDValue N2 = Op.getOperand(2);
8733 // If this is a 256-bit vector result, first extract the 128-bit vector,
8734 // insert the element into the extracted half and then place it back.
8735 if (VT.is256BitVector() || VT.is512BitVector()) {
8736 if (!isa<ConstantSDNode>(N2))
8739 // Get the desired 128-bit vector half.
8740 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
8741 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
8743 // Insert the element into the desired half.
8744 unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
8745 unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
8747 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
8748 DAG.getConstant(IdxIn128, MVT::i32));
8750 // Insert the changed part back to the 256-bit vector
8751 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
8754 if (Subtarget->hasSSE41())
8755 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
8757 if (EltVT == MVT::i8)
8760 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
8761 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
8762 // as its second argument.
8763 if (N1.getValueType() != MVT::i32)
8764 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8765 if (N2.getValueType() != MVT::i32)
8766 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8767 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
8772 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
8774 MVT OpVT = Op.getSimpleValueType();
8776 // If this is a 256-bit vector result, first insert into a 128-bit
8777 // vector and then insert into the 256-bit vector.
8778 if (!OpVT.is128BitVector()) {
8779 // Insert into a 128-bit vector.
8780 unsigned SizeFactor = OpVT.getSizeInBits()/128;
8781 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
8782 OpVT.getVectorNumElements() / SizeFactor);
8784 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
8786 // Insert the 128-bit vector.
8787 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
8790 if (OpVT == MVT::v1i64 &&
8791 Op.getOperand(0).getValueType() == MVT::i64)
8792 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
8794 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
8795 assert(OpVT.is128BitVector() && "Expected an SSE type!");
8796 return DAG.getNode(ISD::BITCAST, dl, OpVT,
8797 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
8800 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
8801 // a simple subregister reference or explicit instructions to grab
8802 // upper bits of a vector.
8803 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8804 SelectionDAG &DAG) {
8806 SDValue In = Op.getOperand(0);
8807 SDValue Idx = Op.getOperand(1);
8808 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8809 MVT ResVT = Op.getSimpleValueType();
8810 MVT InVT = In.getSimpleValueType();
8812 if (Subtarget->hasFp256()) {
8813 if (ResVT.is128BitVector() &&
8814 (InVT.is256BitVector() || InVT.is512BitVector()) &&
8815 isa<ConstantSDNode>(Idx)) {
8816 return Extract128BitVector(In, IdxVal, DAG, dl);
8818 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
8819 isa<ConstantSDNode>(Idx)) {
8820 return Extract256BitVector(In, IdxVal, DAG, dl);
8826 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
8827 // simple superregister reference or explicit instructions to insert
8828 // the upper bits of a vector.
8829 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8830 SelectionDAG &DAG) {
8831 if (Subtarget->hasFp256()) {
8832 SDLoc dl(Op.getNode());
8833 SDValue Vec = Op.getNode()->getOperand(0);
8834 SDValue SubVec = Op.getNode()->getOperand(1);
8835 SDValue Idx = Op.getNode()->getOperand(2);
8837 if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8838 Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8839 SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8840 isa<ConstantSDNode>(Idx)) {
8841 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8842 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8845 if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8846 SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8847 isa<ConstantSDNode>(Idx)) {
8848 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8849 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8855 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8856 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8857 // one of the above mentioned nodes. It has to be wrapped because otherwise
8858 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8859 // be used to form addressing mode. These wrapped nodes will be selected
8862 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8863 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8865 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8867 unsigned char OpFlag = 0;
8868 unsigned WrapperKind = X86ISD::Wrapper;
8869 CodeModel::Model M = DAG.getTarget().getCodeModel();
8871 if (Subtarget->isPICStyleRIPRel() &&
8872 (M == CodeModel::Small || M == CodeModel::Kernel))
8873 WrapperKind = X86ISD::WrapperRIP;
8874 else if (Subtarget->isPICStyleGOT())
8875 OpFlag = X86II::MO_GOTOFF;
8876 else if (Subtarget->isPICStyleStubPIC())
8877 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8879 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8881 CP->getOffset(), OpFlag);
8883 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8884 // With PIC, the address is actually $g + Offset.
8886 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8887 DAG.getNode(X86ISD::GlobalBaseReg,
8888 SDLoc(), getPointerTy()),
8895 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8896 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8898 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8900 unsigned char OpFlag = 0;
8901 unsigned WrapperKind = X86ISD::Wrapper;
8902 CodeModel::Model M = DAG.getTarget().getCodeModel();
8904 if (Subtarget->isPICStyleRIPRel() &&
8905 (M == CodeModel::Small || M == CodeModel::Kernel))
8906 WrapperKind = X86ISD::WrapperRIP;
8907 else if (Subtarget->isPICStyleGOT())
8908 OpFlag = X86II::MO_GOTOFF;
8909 else if (Subtarget->isPICStyleStubPIC())
8910 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8912 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8915 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8917 // With PIC, the address is actually $g + Offset.
8919 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8920 DAG.getNode(X86ISD::GlobalBaseReg,
8921 SDLoc(), getPointerTy()),
8928 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8929 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8931 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8933 unsigned char OpFlag = 0;
8934 unsigned WrapperKind = X86ISD::Wrapper;
8935 CodeModel::Model M = DAG.getTarget().getCodeModel();
8937 if (Subtarget->isPICStyleRIPRel() &&
8938 (M == CodeModel::Small || M == CodeModel::Kernel)) {
8939 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8940 OpFlag = X86II::MO_GOTPCREL;
8941 WrapperKind = X86ISD::WrapperRIP;
8942 } else if (Subtarget->isPICStyleGOT()) {
8943 OpFlag = X86II::MO_GOT;
8944 } else if (Subtarget->isPICStyleStubPIC()) {
8945 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8946 } else if (Subtarget->isPICStyleStubNoDynamic()) {
8947 OpFlag = X86II::MO_DARWIN_NONLAZY;
8950 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8953 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8955 // With PIC, the address is actually $g + Offset.
8956 if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
8957 !Subtarget->is64Bit()) {
8958 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8959 DAG.getNode(X86ISD::GlobalBaseReg,
8960 SDLoc(), getPointerTy()),
8964 // For symbols that require a load from a stub to get the address, emit the
8966 if (isGlobalStubReference(OpFlag))
8967 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8968 MachinePointerInfo::getGOT(), false, false, false, 0);
8974 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8975 // Create the TargetBlockAddressAddress node.
8976 unsigned char OpFlags =
8977 Subtarget->ClassifyBlockAddressReference();
8978 CodeModel::Model M = DAG.getTarget().getCodeModel();
8979 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8980 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8982 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8985 if (Subtarget->isPICStyleRIPRel() &&
8986 (M == CodeModel::Small || M == CodeModel::Kernel))
8987 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8989 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8991 // With PIC, the address is actually $g + Offset.
8992 if (isGlobalRelativeToPICBase(OpFlags)) {
8993 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8994 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
9002 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
9003 int64_t Offset, SelectionDAG &DAG) const {
9004 // Create the TargetGlobalAddress node, folding in the constant
9005 // offset if it is legal.
9006 unsigned char OpFlags =
9007 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
9008 CodeModel::Model M = DAG.getTarget().getCodeModel();
9010 if (OpFlags == X86II::MO_NO_FLAG &&
9011 X86::isOffsetSuitableForCodeModel(Offset, M)) {
9012 // A direct static reference to a global.
9013 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
9016 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
9019 if (Subtarget->isPICStyleRIPRel() &&
9020 (M == CodeModel::Small || M == CodeModel::Kernel))
9021 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
9023 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
9025 // With PIC, the address is actually $g + Offset.
9026 if (isGlobalRelativeToPICBase(OpFlags)) {
9027 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
9028 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
9032 // For globals that require a load from a stub to get the address, emit the
9034 if (isGlobalStubReference(OpFlags))
9035 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
9036 MachinePointerInfo::getGOT(), false, false, false, 0);
9038 // If there was a non-zero offset that we didn't fold, create an explicit
9041 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
9042 DAG.getConstant(Offset, getPointerTy()));
9048 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
9049 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
9050 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
9051 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
9055 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
9056 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
9057 unsigned char OperandFlags, bool LocalDynamic = false) {
9058 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9059 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9061 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
9062 GA->getValueType(0),
9066 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
9070 SDValue Ops[] = { Chain, TGA, *InFlag };
9071 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
9073 SDValue Ops[] = { Chain, TGA };
9074 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
9077 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
9078 MFI->setAdjustsStack(true);
9080 SDValue Flag = Chain.getValue(1);
9081 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
9084 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
9086 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
9089 SDLoc dl(GA); // ? function entry point might be better
9090 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
9091 DAG.getNode(X86ISD::GlobalBaseReg,
9092 SDLoc(), PtrVT), InFlag);
9093 InFlag = Chain.getValue(1);
9095 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
9098 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
9100 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
9102 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
9103 X86::RAX, X86II::MO_TLSGD);
9106 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
9112 // Get the start address of the TLS block for this module.
9113 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
9114 .getInfo<X86MachineFunctionInfo>();
9115 MFI->incNumLocalDynamicTLSAccesses();
9119 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
9120 X86II::MO_TLSLD, /*LocalDynamic=*/true);
9123 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
9124 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
9125 InFlag = Chain.getValue(1);
9126 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
9127 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
9130 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
9134 unsigned char OperandFlags = X86II::MO_DTPOFF;
9135 unsigned WrapperKind = X86ISD::Wrapper;
9136 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
9137 GA->getValueType(0),
9138 GA->getOffset(), OperandFlags);
9139 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
9141 // Add x@dtpoff with the base.
9142 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
9145 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
9146 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
9147 const EVT PtrVT, TLSModel::Model model,
9148 bool is64Bit, bool isPIC) {
9151 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
9152 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
9153 is64Bit ? 257 : 256));
9155 SDValue ThreadPointer =
9156 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
9157 MachinePointerInfo(Ptr), false, false, false, 0);
9159 unsigned char OperandFlags = 0;
9160 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
9162 unsigned WrapperKind = X86ISD::Wrapper;
9163 if (model == TLSModel::LocalExec) {
9164 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
9165 } else if (model == TLSModel::InitialExec) {
9167 OperandFlags = X86II::MO_GOTTPOFF;
9168 WrapperKind = X86ISD::WrapperRIP;
9170 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
9173 llvm_unreachable("Unexpected model");
9176 // emit "addl x@ntpoff,%eax" (local exec)
9177 // or "addl x@indntpoff,%eax" (initial exec)
9178 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
9180 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
9181 GA->getOffset(), OperandFlags);
9182 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
9184 if (model == TLSModel::InitialExec) {
9185 if (isPIC && !is64Bit) {
9186 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
9187 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
9191 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
9192 MachinePointerInfo::getGOT(), false, false, false, 0);
9195 // The address of the thread local variable is the add of the thread
9196 // pointer with the offset of the variable.
9197 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
9201 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
9203 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
9204 const GlobalValue *GV = GA->getGlobal();
9206 if (Subtarget->isTargetELF()) {
9207 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
9210 case TLSModel::GeneralDynamic:
9211 if (Subtarget->is64Bit())
9212 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
9213 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
9214 case TLSModel::LocalDynamic:
9215 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
9216 Subtarget->is64Bit());
9217 case TLSModel::InitialExec:
9218 case TLSModel::LocalExec:
9219 return LowerToTLSExecModel(
9220 GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
9221 DAG.getTarget().getRelocationModel() == Reloc::PIC_);
9223 llvm_unreachable("Unknown TLS model.");
9226 if (Subtarget->isTargetDarwin()) {
9227 // Darwin only has one model of TLS. Lower to that.
9228 unsigned char OpFlag = 0;
9229 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
9230 X86ISD::WrapperRIP : X86ISD::Wrapper;
9232 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
9234 bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
9235 !Subtarget->is64Bit();
9237 OpFlag = X86II::MO_TLVP_PIC_BASE;
9239 OpFlag = X86II::MO_TLVP;
9241 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
9242 GA->getValueType(0),
9243 GA->getOffset(), OpFlag);
9244 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
9246 // With PIC32, the address is actually $g + Offset.
9248 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9249 DAG.getNode(X86ISD::GlobalBaseReg,
9250 SDLoc(), getPointerTy()),
9253 // Lowering the machine isd will make sure everything is in the right
9255 SDValue Chain = DAG.getEntryNode();
9256 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9257 SDValue Args[] = { Chain, Offset };
9258 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
9260 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
9261 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9262 MFI->setAdjustsStack(true);
9264 // And our return value (tls address) is in the standard call return value
9266 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
9267 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
9271 if (Subtarget->isTargetKnownWindowsMSVC() ||
9272 Subtarget->isTargetWindowsGNU()) {
9273 // Just use the implicit TLS architecture
9274 // Need to generate someting similar to:
9275 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
9277 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
9278 // mov rcx, qword [rdx+rcx*8]
9279 // mov eax, .tls$:tlsvar
9280 // [rax+rcx] contains the address
9281 // Windows 64bit: gs:0x58
9282 // Windows 32bit: fs:__tls_array
9285 SDValue Chain = DAG.getEntryNode();
9287 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
9288 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
9289 // use its literal value of 0x2C.
9290 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
9291 ? Type::getInt8PtrTy(*DAG.getContext(),
9293 : Type::getInt32PtrTy(*DAG.getContext(),
9297 Subtarget->is64Bit()
9298 ? DAG.getIntPtrConstant(0x58)
9299 : (Subtarget->isTargetWindowsGNU()
9300 ? DAG.getIntPtrConstant(0x2C)
9301 : DAG.getExternalSymbol("_tls_array", getPointerTy()));
9303 SDValue ThreadPointer =
9304 DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
9305 MachinePointerInfo(Ptr), false, false, false, 0);
9307 // Load the _tls_index variable
9308 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
9309 if (Subtarget->is64Bit())
9310 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
9311 IDX, MachinePointerInfo(), MVT::i32,
9314 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
9315 false, false, false, 0);
9317 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
9319 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
9321 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
9322 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
9323 false, false, false, 0);
9325 // Get the offset of start of .tls section
9326 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
9327 GA->getValueType(0),
9328 GA->getOffset(), X86II::MO_SECREL);
9329 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
9331 // The address of the thread local variable is the add of the thread
9332 // pointer with the offset of the variable.
9333 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
9336 llvm_unreachable("TLS not implemented for this target.");
9339 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
9340 /// and take a 2 x i32 value to shift plus a shift amount.
9341 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
9342 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
9343 MVT VT = Op.getSimpleValueType();
9344 unsigned VTBits = VT.getSizeInBits();
9346 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
9347 SDValue ShOpLo = Op.getOperand(0);
9348 SDValue ShOpHi = Op.getOperand(1);
9349 SDValue ShAmt = Op.getOperand(2);
9350 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
9351 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
9353 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
9354 DAG.getConstant(VTBits - 1, MVT::i8));
9355 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
9356 DAG.getConstant(VTBits - 1, MVT::i8))
9357 : DAG.getConstant(0, VT);
9360 if (Op.getOpcode() == ISD::SHL_PARTS) {
9361 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
9362 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
9364 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
9365 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
9368 // If the shift amount is larger or equal than the width of a part we can't
9369 // rely on the results of shld/shrd. Insert a test and select the appropriate
9370 // values for large shift amounts.
9371 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
9372 DAG.getConstant(VTBits, MVT::i8));
9373 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9374 AndNode, DAG.getConstant(0, MVT::i8));
9377 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9378 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
9379 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
9381 if (Op.getOpcode() == ISD::SHL_PARTS) {
9382 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
9383 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
9385 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
9386 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
9389 SDValue Ops[2] = { Lo, Hi };
9390 return DAG.getMergeValues(Ops, dl);
9393 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
9394 SelectionDAG &DAG) const {
9395 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
9397 if (SrcVT.isVector())
9400 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
9401 "Unknown SINT_TO_FP to lower!");
9403 // These are really Legal; return the operand so the caller accepts it as
9405 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
9407 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
9408 Subtarget->is64Bit()) {
9413 unsigned Size = SrcVT.getSizeInBits()/8;
9414 MachineFunction &MF = DAG.getMachineFunction();
9415 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
9416 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9417 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9419 MachinePointerInfo::getFixedStack(SSFI),
9421 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
9424 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
9426 SelectionDAG &DAG) const {
9430 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
9432 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
9434 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
9436 unsigned ByteSize = SrcVT.getSizeInBits()/8;
9438 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
9439 MachineMemOperand *MMO;
9441 int SSFI = FI->getIndex();
9443 DAG.getMachineFunction()
9444 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9445 MachineMemOperand::MOLoad, ByteSize, ByteSize);
9447 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
9448 StackSlot = StackSlot.getOperand(1);
9450 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
9451 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
9453 Tys, Ops, SrcVT, MMO);
9456 Chain = Result.getValue(1);
9457 SDValue InFlag = Result.getValue(2);
9459 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
9460 // shouldn't be necessary except that RFP cannot be live across
9461 // multiple blocks. When stackifier is fixed, they can be uncoupled.
9462 MachineFunction &MF = DAG.getMachineFunction();
9463 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
9464 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
9465 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9466 Tys = DAG.getVTList(MVT::Other);
9468 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
9470 MachineMemOperand *MMO =
9471 DAG.getMachineFunction()
9472 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9473 MachineMemOperand::MOStore, SSFISize, SSFISize);
9475 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
9476 Ops, Op.getValueType(), MMO);
9477 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
9478 MachinePointerInfo::getFixedStack(SSFI),
9479 false, false, false, 0);
9485 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
9486 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
9487 SelectionDAG &DAG) const {
9488 // This algorithm is not obvious. Here it is what we're trying to output:
9491 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
9492 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
9496 pshufd $0x4e, %xmm0, %xmm1
9502 LLVMContext *Context = DAG.getContext();
9504 // Build some magic constants.
9505 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
9506 Constant *C0 = ConstantDataVector::get(*Context, CV0);
9507 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
9509 SmallVector<Constant*,2> CV1;
9511 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9512 APInt(64, 0x4330000000000000ULL))));
9514 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9515 APInt(64, 0x4530000000000000ULL))));
9516 Constant *C1 = ConstantVector::get(CV1);
9517 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
9519 // Load the 64-bit value into an XMM register.
9520 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
9522 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
9523 MachinePointerInfo::getConstantPool(),
9524 false, false, false, 16);
9525 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
9526 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
9529 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
9530 MachinePointerInfo::getConstantPool(),
9531 false, false, false, 16);
9532 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
9533 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
9536 if (Subtarget->hasSSE3()) {
9537 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
9538 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
9540 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
9541 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
9543 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
9544 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
9548 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
9549 DAG.getIntPtrConstant(0));
9552 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
9553 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
9554 SelectionDAG &DAG) const {
9556 // FP constant to bias correct the final result.
9557 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
9560 // Load the 32-bit value into an XMM register.
9561 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
9564 // Zero out the upper parts of the register.
9565 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
9567 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9568 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
9569 DAG.getIntPtrConstant(0));
9571 // Or the load with the bias.
9572 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
9573 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9574 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9576 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9577 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9578 MVT::v2f64, Bias)));
9579 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9580 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
9581 DAG.getIntPtrConstant(0));
9583 // Subtract the bias.
9584 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
9586 // Handle final rounding.
9587 EVT DestVT = Op.getValueType();
9589 if (DestVT.bitsLT(MVT::f64))
9590 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
9591 DAG.getIntPtrConstant(0));
9592 if (DestVT.bitsGT(MVT::f64))
9593 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
9595 // Handle final rounding.
9599 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
9600 SelectionDAG &DAG) const {
9601 SDValue N0 = Op.getOperand(0);
9602 MVT SVT = N0.getSimpleValueType();
9605 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
9606 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
9607 "Custom UINT_TO_FP is not supported!");
9609 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
9610 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
9611 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
9614 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
9615 SelectionDAG &DAG) const {
9616 SDValue N0 = Op.getOperand(0);
9619 if (Op.getValueType().isVector())
9620 return lowerUINT_TO_FP_vec(Op, DAG);
9622 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
9623 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
9624 // the optimization here.
9625 if (DAG.SignBitIsZero(N0))
9626 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
9628 MVT SrcVT = N0.getSimpleValueType();
9629 MVT DstVT = Op.getSimpleValueType();
9630 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
9631 return LowerUINT_TO_FP_i64(Op, DAG);
9632 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
9633 return LowerUINT_TO_FP_i32(Op, DAG);
9634 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
9637 // Make a 64-bit buffer, and use it to build an FILD.
9638 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
9639 if (SrcVT == MVT::i32) {
9640 SDValue WordOff = DAG.getConstant(4, getPointerTy());
9641 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
9642 getPointerTy(), StackSlot, WordOff);
9643 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9644 StackSlot, MachinePointerInfo(),
9646 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
9647 OffsetSlot, MachinePointerInfo(),
9649 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
9653 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
9654 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9655 StackSlot, MachinePointerInfo(),
9657 // For i64 source, we need to add the appropriate power of 2 if the input
9658 // was negative. This is the same as the optimization in
9659 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
9660 // we must be careful to do the computation in x87 extended precision, not
9661 // in SSE. (The generic code can't know it's OK to do this, or how to.)
9662 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
9663 MachineMemOperand *MMO =
9664 DAG.getMachineFunction()
9665 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9666 MachineMemOperand::MOLoad, 8, 8);
9668 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
9669 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
9670 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
9673 APInt FF(32, 0x5F800000ULL);
9675 // Check whether the sign bit is set.
9676 SDValue SignSet = DAG.getSetCC(dl,
9677 getSetCCResultType(*DAG.getContext(), MVT::i64),
9678 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
9681 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
9682 SDValue FudgePtr = DAG.getConstantPool(
9683 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
9686 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
9687 SDValue Zero = DAG.getIntPtrConstant(0);
9688 SDValue Four = DAG.getIntPtrConstant(4);
9689 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
9691 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
9693 // Load the value out, extending it from f32 to f80.
9694 // FIXME: Avoid the extend by constructing the right constant pool?
9695 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
9696 FudgePtr, MachinePointerInfo::getConstantPool(),
9697 MVT::f32, false, false, 4);
9698 // Extend everything to 80 bits to force it to be done on x87.
9699 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
9700 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
9703 std::pair<SDValue,SDValue>
9704 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
9705 bool IsSigned, bool IsReplace) const {
9708 EVT DstTy = Op.getValueType();
9710 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
9711 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
9715 assert(DstTy.getSimpleVT() <= MVT::i64 &&
9716 DstTy.getSimpleVT() >= MVT::i16 &&
9717 "Unknown FP_TO_INT to lower!");
9719 // These are really Legal.
9720 if (DstTy == MVT::i32 &&
9721 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9722 return std::make_pair(SDValue(), SDValue());
9723 if (Subtarget->is64Bit() &&
9724 DstTy == MVT::i64 &&
9725 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9726 return std::make_pair(SDValue(), SDValue());
9728 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
9729 // stack slot, or into the FTOL runtime function.
9730 MachineFunction &MF = DAG.getMachineFunction();
9731 unsigned MemSize = DstTy.getSizeInBits()/8;
9732 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9733 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9736 if (!IsSigned && isIntegerTypeFTOL(DstTy))
9737 Opc = X86ISD::WIN_FTOL;
9739 switch (DstTy.getSimpleVT().SimpleTy) {
9740 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
9741 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
9742 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
9743 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
9746 SDValue Chain = DAG.getEntryNode();
9747 SDValue Value = Op.getOperand(0);
9748 EVT TheVT = Op.getOperand(0).getValueType();
9749 // FIXME This causes a redundant load/store if the SSE-class value is already
9750 // in memory, such as if it is on the callstack.
9751 if (isScalarFPTypeInSSEReg(TheVT)) {
9752 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
9753 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
9754 MachinePointerInfo::getFixedStack(SSFI),
9756 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
9758 Chain, StackSlot, DAG.getValueType(TheVT)
9761 MachineMemOperand *MMO =
9762 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9763 MachineMemOperand::MOLoad, MemSize, MemSize);
9764 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
9765 Chain = Value.getValue(1);
9766 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9767 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9770 MachineMemOperand *MMO =
9771 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9772 MachineMemOperand::MOStore, MemSize, MemSize);
9774 if (Opc != X86ISD::WIN_FTOL) {
9775 // Build the FP_TO_INT*_IN_MEM
9776 SDValue Ops[] = { Chain, Value, StackSlot };
9777 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
9779 return std::make_pair(FIST, StackSlot);
9781 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
9782 DAG.getVTList(MVT::Other, MVT::Glue),
9784 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
9785 MVT::i32, ftol.getValue(1));
9786 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
9787 MVT::i32, eax.getValue(2));
9788 SDValue Ops[] = { eax, edx };
9789 SDValue pair = IsReplace
9790 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
9791 : DAG.getMergeValues(Ops, DL);
9792 return std::make_pair(pair, SDValue());
9796 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
9797 const X86Subtarget *Subtarget) {
9798 MVT VT = Op->getSimpleValueType(0);
9799 SDValue In = Op->getOperand(0);
9800 MVT InVT = In.getSimpleValueType();
9803 // Optimize vectors in AVX mode:
9806 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
9807 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
9808 // Concat upper and lower parts.
9811 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
9812 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
9813 // Concat upper and lower parts.
9816 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
9817 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
9818 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
9821 if (Subtarget->hasInt256())
9822 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
9824 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
9825 SDValue Undef = DAG.getUNDEF(InVT);
9826 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9827 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9828 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9830 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9831 VT.getVectorNumElements()/2);
9833 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9834 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9836 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9839 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9840 SelectionDAG &DAG) {
9841 MVT VT = Op->getSimpleValueType(0);
9842 SDValue In = Op->getOperand(0);
9843 MVT InVT = In.getSimpleValueType();
9845 unsigned int NumElts = VT.getVectorNumElements();
9846 if (NumElts != 8 && NumElts != 16)
9849 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9850 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9852 EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9853 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9854 // Now we have only mask extension
9855 assert(InVT.getVectorElementType() == MVT::i1);
9856 SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9857 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9858 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9859 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9860 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9861 MachinePointerInfo::getConstantPool(),
9862 false, false, false, Alignment);
9864 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9865 if (VT.is512BitVector())
9867 return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9870 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9871 SelectionDAG &DAG) {
9872 if (Subtarget->hasFp256()) {
9873 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9881 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9882 SelectionDAG &DAG) {
9884 MVT VT = Op.getSimpleValueType();
9885 SDValue In = Op.getOperand(0);
9886 MVT SVT = In.getSimpleValueType();
9888 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9889 return LowerZERO_EXTEND_AVX512(Op, DAG);
9891 if (Subtarget->hasFp256()) {
9892 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9897 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9898 VT.getVectorNumElements() != SVT.getVectorNumElements());
9902 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9904 MVT VT = Op.getSimpleValueType();
9905 SDValue In = Op.getOperand(0);
9906 MVT InVT = In.getSimpleValueType();
9908 if (VT == MVT::i1) {
9909 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9910 "Invalid scalar TRUNCATE operation");
9911 if (InVT == MVT::i32)
9913 if (InVT.getSizeInBits() == 64)
9914 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9915 else if (InVT.getSizeInBits() < 32)
9916 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9917 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
9919 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9920 "Invalid TRUNCATE operation");
9922 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9923 if (VT.getVectorElementType().getSizeInBits() >=8)
9924 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9926 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9927 unsigned NumElts = InVT.getVectorNumElements();
9928 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9929 if (InVT.getSizeInBits() < 512) {
9930 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9931 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9935 SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9936 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9937 SDValue CP = DAG.getConstantPool(C, getPointerTy());
9938 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9939 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9940 MachinePointerInfo::getConstantPool(),
9941 false, false, false, Alignment);
9942 SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9943 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9944 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9947 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9948 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9949 if (Subtarget->hasInt256()) {
9950 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9951 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9952 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9954 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9955 DAG.getIntPtrConstant(0));
9958 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9959 DAG.getIntPtrConstant(0));
9960 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9961 DAG.getIntPtrConstant(2));
9962 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9963 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9964 static const int ShufMask[] = {0, 2, 4, 6};
9965 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
9968 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9969 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9970 if (Subtarget->hasInt256()) {
9971 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9973 SmallVector<SDValue,32> pshufbMask;
9974 for (unsigned i = 0; i < 2; ++i) {
9975 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9976 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9977 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9978 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9979 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9980 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9981 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9982 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9983 for (unsigned j = 0; j < 8; ++j)
9984 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9986 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
9987 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9988 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9990 static const int ShufMask[] = {0, 2, -1, -1};
9991 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
9993 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9994 DAG.getIntPtrConstant(0));
9995 return DAG.getNode(ISD::BITCAST, DL, VT, In);
9998 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9999 DAG.getIntPtrConstant(0));
10001 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
10002 DAG.getIntPtrConstant(4));
10004 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
10005 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
10007 // The PSHUFB mask:
10008 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
10009 -1, -1, -1, -1, -1, -1, -1, -1};
10011 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
10012 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
10013 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
10015 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
10016 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
10018 // The MOVLHPS Mask:
10019 static const int ShufMask2[] = {0, 1, 4, 5};
10020 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
10021 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
10024 // Handle truncation of V256 to V128 using shuffles.
10025 if (!VT.is128BitVector() || !InVT.is256BitVector())
10028 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
10030 unsigned NumElems = VT.getVectorNumElements();
10031 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
10033 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
10034 // Prepare truncation shuffle mask
10035 for (unsigned i = 0; i != NumElems; ++i)
10036 MaskVec[i] = i * 2;
10037 SDValue V = DAG.getVectorShuffle(NVT, DL,
10038 DAG.getNode(ISD::BITCAST, DL, NVT, In),
10039 DAG.getUNDEF(NVT), &MaskVec[0]);
10040 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
10041 DAG.getIntPtrConstant(0));
10044 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
10045 SelectionDAG &DAG) const {
10046 assert(!Op.getSimpleValueType().isVector());
10048 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
10049 /*IsSigned=*/ true, /*IsReplace=*/ false);
10050 SDValue FIST = Vals.first, StackSlot = Vals.second;
10051 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
10052 if (!FIST.getNode()) return Op;
10054 if (StackSlot.getNode())
10055 // Load the result.
10056 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
10057 FIST, StackSlot, MachinePointerInfo(),
10058 false, false, false, 0);
10060 // The node is the result.
10064 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
10065 SelectionDAG &DAG) const {
10066 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
10067 /*IsSigned=*/ false, /*IsReplace=*/ false);
10068 SDValue FIST = Vals.first, StackSlot = Vals.second;
10069 assert(FIST.getNode() && "Unexpected failure");
10071 if (StackSlot.getNode())
10072 // Load the result.
10073 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
10074 FIST, StackSlot, MachinePointerInfo(),
10075 false, false, false, 0);
10077 // The node is the result.
10081 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
10083 MVT VT = Op.getSimpleValueType();
10084 SDValue In = Op.getOperand(0);
10085 MVT SVT = In.getSimpleValueType();
10087 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
10089 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
10090 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
10091 In, DAG.getUNDEF(SVT)));
10094 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
10095 LLVMContext *Context = DAG.getContext();
10097 MVT VT = Op.getSimpleValueType();
10099 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
10100 if (VT.isVector()) {
10101 EltVT = VT.getVectorElementType();
10102 NumElts = VT.getVectorNumElements();
10105 if (EltVT == MVT::f64)
10106 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
10107 APInt(64, ~(1ULL << 63))));
10109 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
10110 APInt(32, ~(1U << 31))));
10111 C = ConstantVector::getSplat(NumElts, C);
10112 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10113 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
10114 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
10115 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10116 MachinePointerInfo::getConstantPool(),
10117 false, false, false, Alignment);
10118 if (VT.isVector()) {
10119 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
10120 return DAG.getNode(ISD::BITCAST, dl, VT,
10121 DAG.getNode(ISD::AND, dl, ANDVT,
10122 DAG.getNode(ISD::BITCAST, dl, ANDVT,
10124 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
10126 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
10129 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
10130 LLVMContext *Context = DAG.getContext();
10132 MVT VT = Op.getSimpleValueType();
10134 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
10135 if (VT.isVector()) {
10136 EltVT = VT.getVectorElementType();
10137 NumElts = VT.getVectorNumElements();
10140 if (EltVT == MVT::f64)
10141 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
10142 APInt(64, 1ULL << 63)));
10144 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
10145 APInt(32, 1U << 31)));
10146 C = ConstantVector::getSplat(NumElts, C);
10147 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10148 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
10149 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
10150 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10151 MachinePointerInfo::getConstantPool(),
10152 false, false, false, Alignment);
10153 if (VT.isVector()) {
10154 MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
10155 return DAG.getNode(ISD::BITCAST, dl, VT,
10156 DAG.getNode(ISD::XOR, dl, XORVT,
10157 DAG.getNode(ISD::BITCAST, dl, XORVT,
10159 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
10162 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
10165 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
10166 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10167 LLVMContext *Context = DAG.getContext();
10168 SDValue Op0 = Op.getOperand(0);
10169 SDValue Op1 = Op.getOperand(1);
10171 MVT VT = Op.getSimpleValueType();
10172 MVT SrcVT = Op1.getSimpleValueType();
10174 // If second operand is smaller, extend it first.
10175 if (SrcVT.bitsLT(VT)) {
10176 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
10179 // And if it is bigger, shrink it first.
10180 if (SrcVT.bitsGT(VT)) {
10181 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
10185 // At this point the operands and the result should have the same
10186 // type, and that won't be f80 since that is not custom lowered.
10188 // First get the sign bit of second operand.
10189 SmallVector<Constant*,4> CV;
10190 if (SrcVT == MVT::f64) {
10191 const fltSemantics &Sem = APFloat::IEEEdouble;
10192 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
10193 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
10195 const fltSemantics &Sem = APFloat::IEEEsingle;
10196 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
10197 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10198 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10199 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10201 Constant *C = ConstantVector::get(CV);
10202 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
10203 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
10204 MachinePointerInfo::getConstantPool(),
10205 false, false, false, 16);
10206 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
10208 // Shift sign bit right or left if the two operands have different types.
10209 if (SrcVT.bitsGT(VT)) {
10210 // Op0 is MVT::f32, Op1 is MVT::f64.
10211 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
10212 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
10213 DAG.getConstant(32, MVT::i32));
10214 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
10215 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
10216 DAG.getIntPtrConstant(0));
10219 // Clear first operand sign bit.
10221 if (VT == MVT::f64) {
10222 const fltSemantics &Sem = APFloat::IEEEdouble;
10223 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
10224 APInt(64, ~(1ULL << 63)))));
10225 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
10227 const fltSemantics &Sem = APFloat::IEEEsingle;
10228 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
10229 APInt(32, ~(1U << 31)))));
10230 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10231 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10232 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10234 C = ConstantVector::get(CV);
10235 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
10236 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10237 MachinePointerInfo::getConstantPool(),
10238 false, false, false, 16);
10239 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
10241 // Or the value with the sign bit.
10242 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
10245 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
10246 SDValue N0 = Op.getOperand(0);
10248 MVT VT = Op.getSimpleValueType();
10250 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
10251 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
10252 DAG.getConstant(1, VT));
10253 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
10256 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
10258 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
10259 SelectionDAG &DAG) {
10260 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
10262 if (!Subtarget->hasSSE41())
10265 if (!Op->hasOneUse())
10268 SDNode *N = Op.getNode();
10271 SmallVector<SDValue, 8> Opnds;
10272 DenseMap<SDValue, unsigned> VecInMap;
10273 SmallVector<SDValue, 8> VecIns;
10274 EVT VT = MVT::Other;
10276 // Recognize a special case where a vector is casted into wide integer to
10278 Opnds.push_back(N->getOperand(0));
10279 Opnds.push_back(N->getOperand(1));
10281 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
10282 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
10283 // BFS traverse all OR'd operands.
10284 if (I->getOpcode() == ISD::OR) {
10285 Opnds.push_back(I->getOperand(0));
10286 Opnds.push_back(I->getOperand(1));
10287 // Re-evaluate the number of nodes to be traversed.
10288 e += 2; // 2 more nodes (LHS and RHS) are pushed.
10292 // Quit if a non-EXTRACT_VECTOR_ELT
10293 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10296 // Quit if without a constant index.
10297 SDValue Idx = I->getOperand(1);
10298 if (!isa<ConstantSDNode>(Idx))
10301 SDValue ExtractedFromVec = I->getOperand(0);
10302 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
10303 if (M == VecInMap.end()) {
10304 VT = ExtractedFromVec.getValueType();
10305 // Quit if not 128/256-bit vector.
10306 if (!VT.is128BitVector() && !VT.is256BitVector())
10308 // Quit if not the same type.
10309 if (VecInMap.begin() != VecInMap.end() &&
10310 VT != VecInMap.begin()->first.getValueType())
10312 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
10313 VecIns.push_back(ExtractedFromVec);
10315 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
10318 assert((VT.is128BitVector() || VT.is256BitVector()) &&
10319 "Not extracted from 128-/256-bit vector.");
10321 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
10323 for (DenseMap<SDValue, unsigned>::const_iterator
10324 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
10325 // Quit if not all elements are used.
10326 if (I->second != FullMask)
10330 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
10332 // Cast all vectors into TestVT for PTEST.
10333 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
10334 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
10336 // If more than one full vectors are evaluated, OR them first before PTEST.
10337 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
10338 // Each iteration will OR 2 nodes and append the result until there is only
10339 // 1 node left, i.e. the final OR'd value of all vectors.
10340 SDValue LHS = VecIns[Slot];
10341 SDValue RHS = VecIns[Slot + 1];
10342 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
10345 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
10346 VecIns.back(), VecIns.back());
10349 /// \brief return true if \c Op has a use that doesn't just read flags.
10350 static bool hasNonFlagsUse(SDValue Op) {
10351 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
10353 SDNode *User = *UI;
10354 unsigned UOpNo = UI.getOperandNo();
10355 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
10356 // Look pass truncate.
10357 UOpNo = User->use_begin().getOperandNo();
10358 User = *User->use_begin();
10361 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
10362 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
10368 /// Emit nodes that will be selected as "test Op0,Op0", or something
10370 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
10371 SelectionDAG &DAG) const {
10372 if (Op.getValueType() == MVT::i1)
10373 // KORTEST instruction should be selected
10374 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10375 DAG.getConstant(0, Op.getValueType()));
10377 // CF and OF aren't always set the way we want. Determine which
10378 // of these we need.
10379 bool NeedCF = false;
10380 bool NeedOF = false;
10383 case X86::COND_A: case X86::COND_AE:
10384 case X86::COND_B: case X86::COND_BE:
10387 case X86::COND_G: case X86::COND_GE:
10388 case X86::COND_L: case X86::COND_LE:
10389 case X86::COND_O: case X86::COND_NO: {
10390 // Check if we really need to set the
10391 // Overflow flag. If NoSignedWrap is present
10392 // that is not actually needed.
10393 switch (Op->getOpcode()) {
10398 const BinaryWithFlagsSDNode *BinNode =
10399 cast<BinaryWithFlagsSDNode>(Op.getNode());
10400 if (BinNode->hasNoSignedWrap())
10410 // See if we can use the EFLAGS value from the operand instead of
10411 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
10412 // we prove that the arithmetic won't overflow, we can't use OF or CF.
10413 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
10414 // Emit a CMP with 0, which is the TEST pattern.
10415 //if (Op.getValueType() == MVT::i1)
10416 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
10417 // DAG.getConstant(0, MVT::i1));
10418 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10419 DAG.getConstant(0, Op.getValueType()));
10421 unsigned Opcode = 0;
10422 unsigned NumOperands = 0;
10424 // Truncate operations may prevent the merge of the SETCC instruction
10425 // and the arithmetic instruction before it. Attempt to truncate the operands
10426 // of the arithmetic instruction and use a reduced bit-width instruction.
10427 bool NeedTruncation = false;
10428 SDValue ArithOp = Op;
10429 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
10430 SDValue Arith = Op->getOperand(0);
10431 // Both the trunc and the arithmetic op need to have one user each.
10432 if (Arith->hasOneUse())
10433 switch (Arith.getOpcode()) {
10440 NeedTruncation = true;
10446 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
10447 // which may be the result of a CAST. We use the variable 'Op', which is the
10448 // non-casted variable when we check for possible users.
10449 switch (ArithOp.getOpcode()) {
10451 // Due to an isel shortcoming, be conservative if this add is likely to be
10452 // selected as part of a load-modify-store instruction. When the root node
10453 // in a match is a store, isel doesn't know how to remap non-chain non-flag
10454 // uses of other nodes in the match, such as the ADD in this case. This
10455 // leads to the ADD being left around and reselected, with the result being
10456 // two adds in the output. Alas, even if none our users are stores, that
10457 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
10458 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
10459 // climbing the DAG back to the root, and it doesn't seem to be worth the
10461 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
10462 UE = Op.getNode()->use_end(); UI != UE; ++UI)
10463 if (UI->getOpcode() != ISD::CopyToReg &&
10464 UI->getOpcode() != ISD::SETCC &&
10465 UI->getOpcode() != ISD::STORE)
10468 if (ConstantSDNode *C =
10469 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
10470 // An add of one will be selected as an INC.
10471 if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
10472 Opcode = X86ISD::INC;
10477 // An add of negative one (subtract of one) will be selected as a DEC.
10478 if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
10479 Opcode = X86ISD::DEC;
10485 // Otherwise use a regular EFLAGS-setting add.
10486 Opcode = X86ISD::ADD;
10491 // If we have a constant logical shift that's only used in a comparison
10492 // against zero turn it into an equivalent AND. This allows turning it into
10493 // a TEST instruction later.
10494 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
10495 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
10496 EVT VT = Op.getValueType();
10497 unsigned BitWidth = VT.getSizeInBits();
10498 unsigned ShAmt = Op->getConstantOperandVal(1);
10499 if (ShAmt >= BitWidth) // Avoid undefined shifts.
10501 APInt Mask = ArithOp.getOpcode() == ISD::SRL
10502 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
10503 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
10504 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
10506 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
10507 DAG.getConstant(Mask, VT));
10508 DAG.ReplaceAllUsesWith(Op, New);
10514 // If the primary and result isn't used, don't bother using X86ISD::AND,
10515 // because a TEST instruction will be better.
10516 if (!hasNonFlagsUse(Op))
10522 // Due to the ISEL shortcoming noted above, be conservative if this op is
10523 // likely to be selected as part of a load-modify-store instruction.
10524 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
10525 UE = Op.getNode()->use_end(); UI != UE; ++UI)
10526 if (UI->getOpcode() == ISD::STORE)
10529 // Otherwise use a regular EFLAGS-setting instruction.
10530 switch (ArithOp.getOpcode()) {
10531 default: llvm_unreachable("unexpected operator!");
10532 case ISD::SUB: Opcode = X86ISD::SUB; break;
10533 case ISD::XOR: Opcode = X86ISD::XOR; break;
10534 case ISD::AND: Opcode = X86ISD::AND; break;
10536 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
10537 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
10538 if (EFLAGS.getNode())
10541 Opcode = X86ISD::OR;
10555 return SDValue(Op.getNode(), 1);
10561 // If we found that truncation is beneficial, perform the truncation and
10563 if (NeedTruncation) {
10564 EVT VT = Op.getValueType();
10565 SDValue WideVal = Op->getOperand(0);
10566 EVT WideVT = WideVal.getValueType();
10567 unsigned ConvertedOp = 0;
10568 // Use a target machine opcode to prevent further DAGCombine
10569 // optimizations that may separate the arithmetic operations
10570 // from the setcc node.
10571 switch (WideVal.getOpcode()) {
10573 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
10574 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
10575 case ISD::AND: ConvertedOp = X86ISD::AND; break;
10576 case ISD::OR: ConvertedOp = X86ISD::OR; break;
10577 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
10581 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10582 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
10583 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
10584 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
10585 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
10591 // Emit a CMP with 0, which is the TEST pattern.
10592 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10593 DAG.getConstant(0, Op.getValueType()));
10595 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10596 SmallVector<SDValue, 4> Ops;
10597 for (unsigned i = 0; i != NumOperands; ++i)
10598 Ops.push_back(Op.getOperand(i));
10600 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
10601 DAG.ReplaceAllUsesWith(Op, New);
10602 return SDValue(New.getNode(), 1);
10605 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
10607 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
10608 SDLoc dl, SelectionDAG &DAG) const {
10609 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
10610 if (C->getAPIntValue() == 0)
10611 return EmitTest(Op0, X86CC, dl, DAG);
10613 if (Op0.getValueType() == MVT::i1)
10614 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
10617 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
10618 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
10619 // Do the comparison at i32 if it's smaller, besides the Atom case.
10620 // This avoids subregister aliasing issues. Keep the smaller reference
10621 // if we're optimizing for size, however, as that'll allow better folding
10622 // of memory operations.
10623 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
10624 !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
10625 AttributeSet::FunctionIndex, Attribute::MinSize) &&
10626 !Subtarget->isAtom()) {
10627 unsigned ExtendOp =
10628 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
10629 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
10630 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
10632 // Use SUB instead of CMP to enable CSE between SUB and CMP.
10633 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
10634 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
10636 return SDValue(Sub.getNode(), 1);
10638 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
10641 /// Convert a comparison if required by the subtarget.
10642 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
10643 SelectionDAG &DAG) const {
10644 // If the subtarget does not support the FUCOMI instruction, floating-point
10645 // comparisons have to be converted.
10646 if (Subtarget->hasCMov() ||
10647 Cmp.getOpcode() != X86ISD::CMP ||
10648 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
10649 !Cmp.getOperand(1).getValueType().isFloatingPoint())
10652 // The instruction selector will select an FUCOM instruction instead of
10653 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
10654 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
10655 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
10657 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
10658 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
10659 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
10660 DAG.getConstant(8, MVT::i8));
10661 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
10662 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
10665 static bool isAllOnes(SDValue V) {
10666 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10667 return C && C->isAllOnesValue();
10670 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
10671 /// if it's possible.
10672 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
10673 SDLoc dl, SelectionDAG &DAG) const {
10674 SDValue Op0 = And.getOperand(0);
10675 SDValue Op1 = And.getOperand(1);
10676 if (Op0.getOpcode() == ISD::TRUNCATE)
10677 Op0 = Op0.getOperand(0);
10678 if (Op1.getOpcode() == ISD::TRUNCATE)
10679 Op1 = Op1.getOperand(0);
10682 if (Op1.getOpcode() == ISD::SHL)
10683 std::swap(Op0, Op1);
10684 if (Op0.getOpcode() == ISD::SHL) {
10685 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
10686 if (And00C->getZExtValue() == 1) {
10687 // If we looked past a truncate, check that it's only truncating away
10689 unsigned BitWidth = Op0.getValueSizeInBits();
10690 unsigned AndBitWidth = And.getValueSizeInBits();
10691 if (BitWidth > AndBitWidth) {
10693 DAG.computeKnownBits(Op0, Zeros, Ones);
10694 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
10698 RHS = Op0.getOperand(1);
10700 } else if (Op1.getOpcode() == ISD::Constant) {
10701 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
10702 uint64_t AndRHSVal = AndRHS->getZExtValue();
10703 SDValue AndLHS = Op0;
10705 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
10706 LHS = AndLHS.getOperand(0);
10707 RHS = AndLHS.getOperand(1);
10710 // Use BT if the immediate can't be encoded in a TEST instruction.
10711 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
10713 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
10717 if (LHS.getNode()) {
10718 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
10719 // instruction. Since the shift amount is in-range-or-undefined, we know
10720 // that doing a bittest on the i32 value is ok. We extend to i32 because
10721 // the encoding for the i16 version is larger than the i32 version.
10722 // Also promote i16 to i32 for performance / code size reason.
10723 if (LHS.getValueType() == MVT::i8 ||
10724 LHS.getValueType() == MVT::i16)
10725 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
10727 // If the operand types disagree, extend the shift amount to match. Since
10728 // BT ignores high bits (like shifts) we can use anyextend.
10729 if (LHS.getValueType() != RHS.getValueType())
10730 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
10732 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
10733 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
10734 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10735 DAG.getConstant(Cond, MVT::i8), BT);
10741 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
10743 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
10748 // SSE Condition code mapping:
10757 switch (SetCCOpcode) {
10758 default: llvm_unreachable("Unexpected SETCC condition");
10760 case ISD::SETEQ: SSECC = 0; break;
10762 case ISD::SETGT: Swap = true; // Fallthrough
10764 case ISD::SETOLT: SSECC = 1; break;
10766 case ISD::SETGE: Swap = true; // Fallthrough
10768 case ISD::SETOLE: SSECC = 2; break;
10769 case ISD::SETUO: SSECC = 3; break;
10771 case ISD::SETNE: SSECC = 4; break;
10772 case ISD::SETULE: Swap = true; // Fallthrough
10773 case ISD::SETUGE: SSECC = 5; break;
10774 case ISD::SETULT: Swap = true; // Fallthrough
10775 case ISD::SETUGT: SSECC = 6; break;
10776 case ISD::SETO: SSECC = 7; break;
10778 case ISD::SETONE: SSECC = 8; break;
10781 std::swap(Op0, Op1);
10786 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
10787 // ones, and then concatenate the result back.
10788 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
10789 MVT VT = Op.getSimpleValueType();
10791 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
10792 "Unsupported value type for operation");
10794 unsigned NumElems = VT.getVectorNumElements();
10796 SDValue CC = Op.getOperand(2);
10798 // Extract the LHS vectors
10799 SDValue LHS = Op.getOperand(0);
10800 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10801 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10803 // Extract the RHS vectors
10804 SDValue RHS = Op.getOperand(1);
10805 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10806 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10808 // Issue the operation on the smaller types and concatenate the result back
10809 MVT EltVT = VT.getVectorElementType();
10810 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10811 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10812 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
10813 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
10816 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
10817 const X86Subtarget *Subtarget) {
10818 SDValue Op0 = Op.getOperand(0);
10819 SDValue Op1 = Op.getOperand(1);
10820 SDValue CC = Op.getOperand(2);
10821 MVT VT = Op.getSimpleValueType();
10824 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
10825 Op.getValueType().getScalarType() == MVT::i1 &&
10826 "Cannot set masked compare for this operation");
10828 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10830 bool Unsigned = false;
10833 switch (SetCCOpcode) {
10834 default: llvm_unreachable("Unexpected SETCC condition");
10835 case ISD::SETNE: SSECC = 4; break;
10836 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
10837 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
10838 case ISD::SETLT: Swap = true; //fall-through
10839 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
10840 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
10841 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
10842 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
10843 case ISD::SETULE: Unsigned = true; //fall-through
10844 case ISD::SETLE: SSECC = 2; break;
10848 std::swap(Op0, Op1);
10850 return DAG.getNode(Opc, dl, VT, Op0, Op1);
10851 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
10852 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10853 DAG.getConstant(SSECC, MVT::i8));
10856 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
10857 /// operand \p Op1. If non-trivial (for example because it's not constant)
10858 /// return an empty value.
10859 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
10861 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
10865 MVT VT = Op1.getSimpleValueType();
10866 MVT EVT = VT.getVectorElementType();
10867 unsigned n = VT.getVectorNumElements();
10868 SmallVector<SDValue, 8> ULTOp1;
10870 for (unsigned i = 0; i < n; ++i) {
10871 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
10872 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
10875 // Avoid underflow.
10876 APInt Val = Elt->getAPIntValue();
10880 ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
10883 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
10886 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
10887 SelectionDAG &DAG) {
10888 SDValue Op0 = Op.getOperand(0);
10889 SDValue Op1 = Op.getOperand(1);
10890 SDValue CC = Op.getOperand(2);
10891 MVT VT = Op.getSimpleValueType();
10892 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10893 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10898 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10899 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10902 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10903 unsigned Opc = X86ISD::CMPP;
10904 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10905 assert(VT.getVectorNumElements() <= 16);
10906 Opc = X86ISD::CMPM;
10908 // In the two special cases we can't handle, emit two comparisons.
10911 unsigned CombineOpc;
10912 if (SetCCOpcode == ISD::SETUEQ) {
10913 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10915 assert(SetCCOpcode == ISD::SETONE);
10916 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10919 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10920 DAG.getConstant(CC0, MVT::i8));
10921 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10922 DAG.getConstant(CC1, MVT::i8));
10923 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10925 // Handle all other FP comparisons here.
10926 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10927 DAG.getConstant(SSECC, MVT::i8));
10930 // Break 256-bit integer vector compare into smaller ones.
10931 if (VT.is256BitVector() && !Subtarget->hasInt256())
10932 return Lower256IntVSETCC(Op, DAG);
10934 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10935 EVT OpVT = Op1.getValueType();
10936 if (Subtarget->hasAVX512()) {
10937 if (Op1.getValueType().is512BitVector() ||
10938 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10939 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
10941 // In AVX-512 architecture setcc returns mask with i1 elements,
10942 // But there is no compare instruction for i8 and i16 elements.
10943 // We are not talking about 512-bit operands in this case, these
10944 // types are illegal.
10946 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10947 OpVT.getVectorElementType().getSizeInBits() >= 8))
10948 return DAG.getNode(ISD::TRUNCATE, dl, VT,
10949 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10952 // We are handling one of the integer comparisons here. Since SSE only has
10953 // GT and EQ comparisons for integer, swapping operands and multiple
10954 // operations may be required for some comparisons.
10956 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10957 bool Subus = false;
10959 switch (SetCCOpcode) {
10960 default: llvm_unreachable("Unexpected SETCC condition");
10961 case ISD::SETNE: Invert = true;
10962 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
10963 case ISD::SETLT: Swap = true;
10964 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
10965 case ISD::SETGE: Swap = true;
10966 case ISD::SETLE: Opc = X86ISD::PCMPGT;
10967 Invert = true; break;
10968 case ISD::SETULT: Swap = true;
10969 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
10970 FlipSigns = true; break;
10971 case ISD::SETUGE: Swap = true;
10972 case ISD::SETULE: Opc = X86ISD::PCMPGT;
10973 FlipSigns = true; Invert = true; break;
10976 // Special case: Use min/max operations for SETULE/SETUGE
10977 MVT VET = VT.getVectorElementType();
10979 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10980 || (Subtarget->hasSSE2() && (VET == MVT::i8));
10983 switch (SetCCOpcode) {
10985 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10986 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10989 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10992 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
10993 if (!MinMax && hasSubus) {
10994 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
10996 // t = psubus Op0, Op1
10997 // pcmpeq t, <0..0>
10998 switch (SetCCOpcode) {
11000 case ISD::SETULT: {
11001 // If the comparison is against a constant we can turn this into a
11002 // setule. With psubus, setule does not require a swap. This is
11003 // beneficial because the constant in the register is no longer
11004 // destructed as the destination so it can be hoisted out of a loop.
11005 // Only do this pre-AVX since vpcmp* is no longer destructive.
11006 if (Subtarget->hasAVX())
11008 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
11009 if (ULEOp1.getNode()) {
11011 Subus = true; Invert = false; Swap = false;
11015 // Psubus is better than flip-sign because it requires no inversion.
11016 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
11017 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
11021 Opc = X86ISD::SUBUS;
11027 std::swap(Op0, Op1);
11029 // Check that the operation in question is available (most are plain SSE2,
11030 // but PCMPGTQ and PCMPEQQ have different requirements).
11031 if (VT == MVT::v2i64) {
11032 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
11033 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
11035 // First cast everything to the right type.
11036 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
11037 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
11039 // Since SSE has no unsigned integer comparisons, we need to flip the sign
11040 // bits of the inputs before performing those operations. The lower
11041 // compare is always unsigned.
11044 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
11046 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
11047 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
11048 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
11049 Sign, Zero, Sign, Zero);
11051 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
11052 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
11054 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
11055 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
11056 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
11058 // Create masks for only the low parts/high parts of the 64 bit integers.
11059 static const int MaskHi[] = { 1, 1, 3, 3 };
11060 static const int MaskLo[] = { 0, 0, 2, 2 };
11061 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
11062 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
11063 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
11065 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
11066 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
11069 Result = DAG.getNOT(dl, Result, MVT::v4i32);
11071 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
11074 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
11075 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
11076 // pcmpeqd + pshufd + pand.
11077 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
11079 // First cast everything to the right type.
11080 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
11081 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
11084 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
11086 // Make sure the lower and upper halves are both all-ones.
11087 static const int Mask[] = { 1, 0, 3, 2 };
11088 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
11089 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
11092 Result = DAG.getNOT(dl, Result, MVT::v4i32);
11094 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
11098 // Since SSE has no unsigned integer comparisons, we need to flip the sign
11099 // bits of the inputs before performing those operations.
11101 EVT EltVT = VT.getVectorElementType();
11102 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
11103 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
11104 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
11107 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
11109 // If the logical-not of the result is required, perform that now.
11111 Result = DAG.getNOT(dl, Result, VT);
11114 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
11117 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
11118 getZeroVector(VT, Subtarget, DAG, dl));
11123 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
11125 MVT VT = Op.getSimpleValueType();
11127 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
11129 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
11130 && "SetCC type must be 8-bit or 1-bit integer");
11131 SDValue Op0 = Op.getOperand(0);
11132 SDValue Op1 = Op.getOperand(1);
11134 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
11136 // Optimize to BT if possible.
11137 // Lower (X & (1 << N)) == 0 to BT(X, N).
11138 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
11139 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
11140 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
11141 Op1.getOpcode() == ISD::Constant &&
11142 cast<ConstantSDNode>(Op1)->isNullValue() &&
11143 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
11144 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
11145 if (NewSetCC.getNode())
11149 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
11151 if (Op1.getOpcode() == ISD::Constant &&
11152 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
11153 cast<ConstantSDNode>(Op1)->isNullValue()) &&
11154 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
11156 // If the input is a setcc, then reuse the input setcc or use a new one with
11157 // the inverted condition.
11158 if (Op0.getOpcode() == X86ISD::SETCC) {
11159 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
11160 bool Invert = (CC == ISD::SETNE) ^
11161 cast<ConstantSDNode>(Op1)->isNullValue();
11165 CCode = X86::GetOppositeBranchCondition(CCode);
11166 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11167 DAG.getConstant(CCode, MVT::i8),
11168 Op0.getOperand(1));
11170 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
11174 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
11175 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
11176 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
11178 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
11179 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
11182 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
11183 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
11184 if (X86CC == X86::COND_INVALID)
11187 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
11188 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
11189 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11190 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
11192 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
11196 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
11197 static bool isX86LogicalCmp(SDValue Op) {
11198 unsigned Opc = Op.getNode()->getOpcode();
11199 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
11200 Opc == X86ISD::SAHF)
11202 if (Op.getResNo() == 1 &&
11203 (Opc == X86ISD::ADD ||
11204 Opc == X86ISD::SUB ||
11205 Opc == X86ISD::ADC ||
11206 Opc == X86ISD::SBB ||
11207 Opc == X86ISD::SMUL ||
11208 Opc == X86ISD::UMUL ||
11209 Opc == X86ISD::INC ||
11210 Opc == X86ISD::DEC ||
11211 Opc == X86ISD::OR ||
11212 Opc == X86ISD::XOR ||
11213 Opc == X86ISD::AND))
11216 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
11222 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
11223 if (V.getOpcode() != ISD::TRUNCATE)
11226 SDValue VOp0 = V.getOperand(0);
11227 unsigned InBits = VOp0.getValueSizeInBits();
11228 unsigned Bits = V.getValueSizeInBits();
11229 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
11232 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
11233 bool addTest = true;
11234 SDValue Cond = Op.getOperand(0);
11235 SDValue Op1 = Op.getOperand(1);
11236 SDValue Op2 = Op.getOperand(2);
11238 EVT VT = Op1.getValueType();
11241 // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
11242 // are available. Otherwise fp cmovs get lowered into a less efficient branch
11243 // sequence later on.
11244 if (Cond.getOpcode() == ISD::SETCC &&
11245 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
11246 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
11247 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
11248 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
11249 int SSECC = translateX86FSETCC(
11250 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
11253 if (Subtarget->hasAVX512()) {
11254 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
11255 DAG.getConstant(SSECC, MVT::i8));
11256 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
11258 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
11259 DAG.getConstant(SSECC, MVT::i8));
11260 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
11261 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
11262 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
11266 if (Cond.getOpcode() == ISD::SETCC) {
11267 SDValue NewCond = LowerSETCC(Cond, DAG);
11268 if (NewCond.getNode())
11272 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
11273 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
11274 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
11275 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
11276 if (Cond.getOpcode() == X86ISD::SETCC &&
11277 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
11278 isZero(Cond.getOperand(1).getOperand(1))) {
11279 SDValue Cmp = Cond.getOperand(1);
11281 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
11283 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
11284 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
11285 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
11287 SDValue CmpOp0 = Cmp.getOperand(0);
11288 // Apply further optimizations for special cases
11289 // (select (x != 0), -1, 0) -> neg & sbb
11290 // (select (x == 0), 0, -1) -> neg & sbb
11291 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
11292 if (YC->isNullValue() &&
11293 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
11294 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
11295 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
11296 DAG.getConstant(0, CmpOp0.getValueType()),
11298 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
11299 DAG.getConstant(X86::COND_B, MVT::i8),
11300 SDValue(Neg.getNode(), 1));
11304 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
11305 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
11306 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11308 SDValue Res = // Res = 0 or -1.
11309 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
11310 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
11312 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
11313 Res = DAG.getNOT(DL, Res, Res.getValueType());
11315 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
11316 if (!N2C || !N2C->isNullValue())
11317 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
11322 // Look past (and (setcc_carry (cmp ...)), 1).
11323 if (Cond.getOpcode() == ISD::AND &&
11324 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
11325 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11326 if (C && C->getAPIntValue() == 1)
11327 Cond = Cond.getOperand(0);
11330 // If condition flag is set by a X86ISD::CMP, then use it as the condition
11331 // setting operand in place of the X86ISD::SETCC.
11332 unsigned CondOpcode = Cond.getOpcode();
11333 if (CondOpcode == X86ISD::SETCC ||
11334 CondOpcode == X86ISD::SETCC_CARRY) {
11335 CC = Cond.getOperand(0);
11337 SDValue Cmp = Cond.getOperand(1);
11338 unsigned Opc = Cmp.getOpcode();
11339 MVT VT = Op.getSimpleValueType();
11341 bool IllegalFPCMov = false;
11342 if (VT.isFloatingPoint() && !VT.isVector() &&
11343 !isScalarFPTypeInSSEReg(VT)) // FPStack?
11344 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
11346 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
11347 Opc == X86ISD::BT) { // FIXME
11351 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11352 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11353 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11354 Cond.getOperand(0).getValueType() != MVT::i8)) {
11355 SDValue LHS = Cond.getOperand(0);
11356 SDValue RHS = Cond.getOperand(1);
11357 unsigned X86Opcode;
11360 switch (CondOpcode) {
11361 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11362 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11363 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11364 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11365 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11366 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11367 default: llvm_unreachable("unexpected overflowing operator");
11369 if (CondOpcode == ISD::UMULO)
11370 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11373 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11375 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
11377 if (CondOpcode == ISD::UMULO)
11378 Cond = X86Op.getValue(2);
11380 Cond = X86Op.getValue(1);
11382 CC = DAG.getConstant(X86Cond, MVT::i8);
11387 // Look pass the truncate if the high bits are known zero.
11388 if (isTruncWithZeroHighBitsInput(Cond, DAG))
11389 Cond = Cond.getOperand(0);
11391 // We know the result of AND is compared against zero. Try to match
11393 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11394 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
11395 if (NewSetCC.getNode()) {
11396 CC = NewSetCC.getOperand(0);
11397 Cond = NewSetCC.getOperand(1);
11404 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11405 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
11408 // a < b ? -1 : 0 -> RES = ~setcc_carry
11409 // a < b ? 0 : -1 -> RES = setcc_carry
11410 // a >= b ? -1 : 0 -> RES = setcc_carry
11411 // a >= b ? 0 : -1 -> RES = ~setcc_carry
11412 if (Cond.getOpcode() == X86ISD::SUB) {
11413 Cond = ConvertCmpIfNecessary(Cond, DAG);
11414 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
11416 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
11417 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
11418 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
11419 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
11420 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
11421 return DAG.getNOT(DL, Res, Res.getValueType());
11426 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
11427 // widen the cmov and push the truncate through. This avoids introducing a new
11428 // branch during isel and doesn't add any extensions.
11429 if (Op.getValueType() == MVT::i8 &&
11430 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
11431 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
11432 if (T1.getValueType() == T2.getValueType() &&
11433 // Blacklist CopyFromReg to avoid partial register stalls.
11434 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
11435 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
11436 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
11437 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
11441 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
11442 // condition is true.
11443 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
11444 SDValue Ops[] = { Op2, Op1, CC, Cond };
11445 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
11448 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
11449 MVT VT = Op->getSimpleValueType(0);
11450 SDValue In = Op->getOperand(0);
11451 MVT InVT = In.getSimpleValueType();
11454 unsigned int NumElts = VT.getVectorNumElements();
11455 if (NumElts != 8 && NumElts != 16)
11458 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11459 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
11461 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11462 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11464 MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
11465 Constant *C = ConstantInt::get(*DAG.getContext(),
11466 APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
11468 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11469 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11470 SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
11471 MachinePointerInfo::getConstantPool(),
11472 false, false, false, Alignment);
11473 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
11474 if (VT.is512BitVector())
11476 return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
11479 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11480 SelectionDAG &DAG) {
11481 MVT VT = Op->getSimpleValueType(0);
11482 SDValue In = Op->getOperand(0);
11483 MVT InVT = In.getSimpleValueType();
11486 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
11487 return LowerSIGN_EXTEND_AVX512(Op, DAG);
11489 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
11490 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
11491 (VT != MVT::v16i16 || InVT != MVT::v16i8))
11494 if (Subtarget->hasInt256())
11495 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
11497 // Optimize vectors in AVX mode
11498 // Sign extend v8i16 to v8i32 and
11501 // Divide input vector into two parts
11502 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
11503 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
11504 // concat the vectors to original VT
11506 unsigned NumElems = InVT.getVectorNumElements();
11507 SDValue Undef = DAG.getUNDEF(InVT);
11509 SmallVector<int,8> ShufMask1(NumElems, -1);
11510 for (unsigned i = 0; i != NumElems/2; ++i)
11513 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
11515 SmallVector<int,8> ShufMask2(NumElems, -1);
11516 for (unsigned i = 0; i != NumElems/2; ++i)
11517 ShufMask2[i] = i + NumElems/2;
11519 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
11521 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
11522 VT.getVectorNumElements()/2);
11524 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
11525 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
11527 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11530 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
11531 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
11532 // from the AND / OR.
11533 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
11534 Opc = Op.getOpcode();
11535 if (Opc != ISD::OR && Opc != ISD::AND)
11537 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
11538 Op.getOperand(0).hasOneUse() &&
11539 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
11540 Op.getOperand(1).hasOneUse());
11543 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
11544 // 1 and that the SETCC node has a single use.
11545 static bool isXor1OfSetCC(SDValue Op) {
11546 if (Op.getOpcode() != ISD::XOR)
11548 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
11549 if (N1C && N1C->getAPIntValue() == 1) {
11550 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
11551 Op.getOperand(0).hasOneUse();
11556 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
11557 bool addTest = true;
11558 SDValue Chain = Op.getOperand(0);
11559 SDValue Cond = Op.getOperand(1);
11560 SDValue Dest = Op.getOperand(2);
11563 bool Inverted = false;
11565 if (Cond.getOpcode() == ISD::SETCC) {
11566 // Check for setcc([su]{add,sub,mul}o == 0).
11567 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
11568 isa<ConstantSDNode>(Cond.getOperand(1)) &&
11569 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
11570 Cond.getOperand(0).getResNo() == 1 &&
11571 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
11572 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
11573 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
11574 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
11575 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
11576 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
11578 Cond = Cond.getOperand(0);
11580 SDValue NewCond = LowerSETCC(Cond, DAG);
11581 if (NewCond.getNode())
11586 // FIXME: LowerXALUO doesn't handle these!!
11587 else if (Cond.getOpcode() == X86ISD::ADD ||
11588 Cond.getOpcode() == X86ISD::SUB ||
11589 Cond.getOpcode() == X86ISD::SMUL ||
11590 Cond.getOpcode() == X86ISD::UMUL)
11591 Cond = LowerXALUO(Cond, DAG);
11594 // Look pass (and (setcc_carry (cmp ...)), 1).
11595 if (Cond.getOpcode() == ISD::AND &&
11596 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
11597 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11598 if (C && C->getAPIntValue() == 1)
11599 Cond = Cond.getOperand(0);
11602 // If condition flag is set by a X86ISD::CMP, then use it as the condition
11603 // setting operand in place of the X86ISD::SETCC.
11604 unsigned CondOpcode = Cond.getOpcode();
11605 if (CondOpcode == X86ISD::SETCC ||
11606 CondOpcode == X86ISD::SETCC_CARRY) {
11607 CC = Cond.getOperand(0);
11609 SDValue Cmp = Cond.getOperand(1);
11610 unsigned Opc = Cmp.getOpcode();
11611 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
11612 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
11616 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
11620 // These can only come from an arithmetic instruction with overflow,
11621 // e.g. SADDO, UADDO.
11622 Cond = Cond.getNode()->getOperand(1);
11628 CondOpcode = Cond.getOpcode();
11629 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11630 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11631 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11632 Cond.getOperand(0).getValueType() != MVT::i8)) {
11633 SDValue LHS = Cond.getOperand(0);
11634 SDValue RHS = Cond.getOperand(1);
11635 unsigned X86Opcode;
11638 // Keep this in sync with LowerXALUO, otherwise we might create redundant
11639 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
11641 switch (CondOpcode) {
11642 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11644 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11646 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
11649 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11650 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11652 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11654 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
11657 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11658 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11659 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11660 default: llvm_unreachable("unexpected overflowing operator");
11663 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
11664 if (CondOpcode == ISD::UMULO)
11665 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11668 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11670 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
11672 if (CondOpcode == ISD::UMULO)
11673 Cond = X86Op.getValue(2);
11675 Cond = X86Op.getValue(1);
11677 CC = DAG.getConstant(X86Cond, MVT::i8);
11681 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
11682 SDValue Cmp = Cond.getOperand(0).getOperand(1);
11683 if (CondOpc == ISD::OR) {
11684 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
11685 // two branches instead of an explicit OR instruction with a
11687 if (Cmp == Cond.getOperand(1).getOperand(1) &&
11688 isX86LogicalCmp(Cmp)) {
11689 CC = Cond.getOperand(0).getOperand(0);
11690 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11691 Chain, Dest, CC, Cmp);
11692 CC = Cond.getOperand(1).getOperand(0);
11696 } else { // ISD::AND
11697 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
11698 // two branches instead of an explicit AND instruction with a
11699 // separate test. However, we only do this if this block doesn't
11700 // have a fall-through edge, because this requires an explicit
11701 // jmp when the condition is false.
11702 if (Cmp == Cond.getOperand(1).getOperand(1) &&
11703 isX86LogicalCmp(Cmp) &&
11704 Op.getNode()->hasOneUse()) {
11705 X86::CondCode CCode =
11706 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11707 CCode = X86::GetOppositeBranchCondition(CCode);
11708 CC = DAG.getConstant(CCode, MVT::i8);
11709 SDNode *User = *Op.getNode()->use_begin();
11710 // Look for an unconditional branch following this conditional branch.
11711 // We need this because we need to reverse the successors in order
11712 // to implement FCMP_OEQ.
11713 if (User->getOpcode() == ISD::BR) {
11714 SDValue FalseBB = User->getOperand(1);
11716 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11717 assert(NewBR == User);
11721 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11722 Chain, Dest, CC, Cmp);
11723 X86::CondCode CCode =
11724 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
11725 CCode = X86::GetOppositeBranchCondition(CCode);
11726 CC = DAG.getConstant(CCode, MVT::i8);
11732 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
11733 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
11734 // It should be transformed during dag combiner except when the condition
11735 // is set by a arithmetics with overflow node.
11736 X86::CondCode CCode =
11737 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11738 CCode = X86::GetOppositeBranchCondition(CCode);
11739 CC = DAG.getConstant(CCode, MVT::i8);
11740 Cond = Cond.getOperand(0).getOperand(1);
11742 } else if (Cond.getOpcode() == ISD::SETCC &&
11743 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
11744 // For FCMP_OEQ, we can emit
11745 // two branches instead of an explicit AND instruction with a
11746 // separate test. However, we only do this if this block doesn't
11747 // have a fall-through edge, because this requires an explicit
11748 // jmp when the condition is false.
11749 if (Op.getNode()->hasOneUse()) {
11750 SDNode *User = *Op.getNode()->use_begin();
11751 // Look for an unconditional branch following this conditional branch.
11752 // We need this because we need to reverse the successors in order
11753 // to implement FCMP_OEQ.
11754 if (User->getOpcode() == ISD::BR) {
11755 SDValue FalseBB = User->getOperand(1);
11757 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11758 assert(NewBR == User);
11762 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11763 Cond.getOperand(0), Cond.getOperand(1));
11764 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11765 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11766 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11767 Chain, Dest, CC, Cmp);
11768 CC = DAG.getConstant(X86::COND_P, MVT::i8);
11773 } else if (Cond.getOpcode() == ISD::SETCC &&
11774 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
11775 // For FCMP_UNE, we can emit
11776 // two branches instead of an explicit AND instruction with a
11777 // separate test. However, we only do this if this block doesn't
11778 // have a fall-through edge, because this requires an explicit
11779 // jmp when the condition is false.
11780 if (Op.getNode()->hasOneUse()) {
11781 SDNode *User = *Op.getNode()->use_begin();
11782 // Look for an unconditional branch following this conditional branch.
11783 // We need this because we need to reverse the successors in order
11784 // to implement FCMP_UNE.
11785 if (User->getOpcode() == ISD::BR) {
11786 SDValue FalseBB = User->getOperand(1);
11788 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11789 assert(NewBR == User);
11792 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11793 Cond.getOperand(0), Cond.getOperand(1));
11794 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11795 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11796 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11797 Chain, Dest, CC, Cmp);
11798 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
11808 // Look pass the truncate if the high bits are known zero.
11809 if (isTruncWithZeroHighBitsInput(Cond, DAG))
11810 Cond = Cond.getOperand(0);
11812 // We know the result of AND is compared against zero. Try to match
11814 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11815 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
11816 if (NewSetCC.getNode()) {
11817 CC = NewSetCC.getOperand(0);
11818 Cond = NewSetCC.getOperand(1);
11825 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
11826 CC = DAG.getConstant(X86Cond, MVT::i8);
11827 Cond = EmitTest(Cond, X86Cond, dl, DAG);
11829 Cond = ConvertCmpIfNecessary(Cond, DAG);
11830 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11831 Chain, Dest, CC, Cond);
11834 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
11835 // Calls to _alloca is needed to probe the stack when allocating more than 4k
11836 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
11837 // that the guard pages used by the OS virtual memory manager are allocated in
11838 // correct sequence.
11840 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
11841 SelectionDAG &DAG) const {
11842 MachineFunction &MF = DAG.getMachineFunction();
11843 bool SplitStack = MF.shouldSplitStack();
11844 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
11849 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11850 SDNode* Node = Op.getNode();
11852 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
11853 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
11854 " not tell us which reg is the stack pointer!");
11855 EVT VT = Node->getValueType(0);
11856 SDValue Tmp1 = SDValue(Node, 0);
11857 SDValue Tmp2 = SDValue(Node, 1);
11858 SDValue Tmp3 = Node->getOperand(2);
11859 SDValue Chain = Tmp1.getOperand(0);
11861 // Chain the dynamic stack allocation so that it doesn't modify the stack
11862 // pointer when other instructions are using the stack.
11863 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
11866 SDValue Size = Tmp2.getOperand(1);
11867 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
11868 Chain = SP.getValue(1);
11869 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
11870 const TargetFrameLowering &TFI = *DAG.getTarget().getFrameLowering();
11871 unsigned StackAlign = TFI.getStackAlignment();
11872 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
11873 if (Align > StackAlign)
11874 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
11875 DAG.getConstant(-(uint64_t)Align, VT));
11876 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
11878 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
11879 DAG.getIntPtrConstant(0, true), SDValue(),
11882 SDValue Ops[2] = { Tmp1, Tmp2 };
11883 return DAG.getMergeValues(Ops, dl);
11887 SDValue Chain = Op.getOperand(0);
11888 SDValue Size = Op.getOperand(1);
11889 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11890 EVT VT = Op.getNode()->getValueType(0);
11892 bool Is64Bit = Subtarget->is64Bit();
11893 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
11896 MachineRegisterInfo &MRI = MF.getRegInfo();
11899 // The 64 bit implementation of segmented stacks needs to clobber both r10
11900 // r11. This makes it impossible to use it along with nested parameters.
11901 const Function *F = MF.getFunction();
11903 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
11905 if (I->hasNestAttr())
11906 report_fatal_error("Cannot use segmented stacks with functions that "
11907 "have nested arguments.");
11910 const TargetRegisterClass *AddrRegClass =
11911 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
11912 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
11913 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
11914 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
11915 DAG.getRegister(Vreg, SPTy));
11916 SDValue Ops1[2] = { Value, Chain };
11917 return DAG.getMergeValues(Ops1, dl);
11920 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
11922 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
11923 Flag = Chain.getValue(1);
11924 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11926 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
11928 const X86RegisterInfo *RegInfo =
11929 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
11930 unsigned SPReg = RegInfo->getStackRegister();
11931 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
11932 Chain = SP.getValue(1);
11935 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11936 DAG.getConstant(-(uint64_t)Align, VT));
11937 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
11940 SDValue Ops1[2] = { SP, Chain };
11941 return DAG.getMergeValues(Ops1, dl);
11945 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
11946 MachineFunction &MF = DAG.getMachineFunction();
11947 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
11949 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11952 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
11953 // vastart just stores the address of the VarArgsFrameIndex slot into the
11954 // memory location argument.
11955 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11957 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
11958 MachinePointerInfo(SV), false, false, 0);
11962 // gp_offset (0 - 6 * 8)
11963 // fp_offset (48 - 48 + 8 * 16)
11964 // overflow_arg_area (point to parameters coming in memory).
11966 SmallVector<SDValue, 8> MemOps;
11967 SDValue FIN = Op.getOperand(1);
11969 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
11970 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
11972 FIN, MachinePointerInfo(SV), false, false, 0);
11973 MemOps.push_back(Store);
11976 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11977 FIN, DAG.getIntPtrConstant(4));
11978 Store = DAG.getStore(Op.getOperand(0), DL,
11979 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
11981 FIN, MachinePointerInfo(SV, 4), false, false, 0);
11982 MemOps.push_back(Store);
11984 // Store ptr to overflow_arg_area
11985 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11986 FIN, DAG.getIntPtrConstant(4));
11987 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11989 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11990 MachinePointerInfo(SV, 8),
11992 MemOps.push_back(Store);
11994 // Store ptr to reg_save_area.
11995 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11996 FIN, DAG.getIntPtrConstant(8));
11997 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11999 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
12000 MachinePointerInfo(SV, 16), false, false, 0);
12001 MemOps.push_back(Store);
12002 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
12005 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
12006 assert(Subtarget->is64Bit() &&
12007 "LowerVAARG only handles 64-bit va_arg!");
12008 assert((Subtarget->isTargetLinux() ||
12009 Subtarget->isTargetDarwin()) &&
12010 "Unhandled target in LowerVAARG");
12011 assert(Op.getNode()->getNumOperands() == 4);
12012 SDValue Chain = Op.getOperand(0);
12013 SDValue SrcPtr = Op.getOperand(1);
12014 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
12015 unsigned Align = Op.getConstantOperandVal(3);
12018 EVT ArgVT = Op.getNode()->getValueType(0);
12019 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
12020 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
12023 // Decide which area this value should be read from.
12024 // TODO: Implement the AMD64 ABI in its entirety. This simple
12025 // selection mechanism works only for the basic types.
12026 if (ArgVT == MVT::f80) {
12027 llvm_unreachable("va_arg for f80 not yet implemented");
12028 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
12029 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
12030 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
12031 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
12033 llvm_unreachable("Unhandled argument type in LowerVAARG");
12036 if (ArgMode == 2) {
12037 // Sanity Check: Make sure using fp_offset makes sense.
12038 assert(!DAG.getTarget().Options.UseSoftFloat &&
12039 !(DAG.getMachineFunction()
12040 .getFunction()->getAttributes()
12041 .hasAttribute(AttributeSet::FunctionIndex,
12042 Attribute::NoImplicitFloat)) &&
12043 Subtarget->hasSSE1());
12046 // Insert VAARG_64 node into the DAG
12047 // VAARG_64 returns two values: Variable Argument Address, Chain
12048 SmallVector<SDValue, 11> InstOps;
12049 InstOps.push_back(Chain);
12050 InstOps.push_back(SrcPtr);
12051 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
12052 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
12053 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
12054 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
12055 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
12056 VTs, InstOps, MVT::i64,
12057 MachinePointerInfo(SV),
12059 /*Volatile=*/false,
12061 /*WriteMem=*/true);
12062 Chain = VAARG.getValue(1);
12064 // Load the next argument and return it
12065 return DAG.getLoad(ArgVT, dl,
12068 MachinePointerInfo(),
12069 false, false, false, 0);
12072 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
12073 SelectionDAG &DAG) {
12074 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
12075 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
12076 SDValue Chain = Op.getOperand(0);
12077 SDValue DstPtr = Op.getOperand(1);
12078 SDValue SrcPtr = Op.getOperand(2);
12079 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
12080 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
12083 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
12084 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
12086 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
12089 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
12090 // amount is a constant. Takes immediate version of shift as input.
12091 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
12092 SDValue SrcOp, uint64_t ShiftAmt,
12093 SelectionDAG &DAG) {
12094 MVT ElementType = VT.getVectorElementType();
12096 // Fold this packed shift into its first operand if ShiftAmt is 0.
12100 // Check for ShiftAmt >= element width
12101 if (ShiftAmt >= ElementType.getSizeInBits()) {
12102 if (Opc == X86ISD::VSRAI)
12103 ShiftAmt = ElementType.getSizeInBits() - 1;
12105 return DAG.getConstant(0, VT);
12108 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
12109 && "Unknown target vector shift-by-constant node");
12111 // Fold this packed vector shift into a build vector if SrcOp is a
12112 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
12113 if (VT == SrcOp.getSimpleValueType() &&
12114 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
12115 SmallVector<SDValue, 8> Elts;
12116 unsigned NumElts = SrcOp->getNumOperands();
12117 ConstantSDNode *ND;
12120 default: llvm_unreachable(nullptr);
12121 case X86ISD::VSHLI:
12122 for (unsigned i=0; i!=NumElts; ++i) {
12123 SDValue CurrentOp = SrcOp->getOperand(i);
12124 if (CurrentOp->getOpcode() == ISD::UNDEF) {
12125 Elts.push_back(CurrentOp);
12128 ND = cast<ConstantSDNode>(CurrentOp);
12129 const APInt &C = ND->getAPIntValue();
12130 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
12133 case X86ISD::VSRLI:
12134 for (unsigned i=0; i!=NumElts; ++i) {
12135 SDValue CurrentOp = SrcOp->getOperand(i);
12136 if (CurrentOp->getOpcode() == ISD::UNDEF) {
12137 Elts.push_back(CurrentOp);
12140 ND = cast<ConstantSDNode>(CurrentOp);
12141 const APInt &C = ND->getAPIntValue();
12142 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
12145 case X86ISD::VSRAI:
12146 for (unsigned i=0; i!=NumElts; ++i) {
12147 SDValue CurrentOp = SrcOp->getOperand(i);
12148 if (CurrentOp->getOpcode() == ISD::UNDEF) {
12149 Elts.push_back(CurrentOp);
12152 ND = cast<ConstantSDNode>(CurrentOp);
12153 const APInt &C = ND->getAPIntValue();
12154 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
12159 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
12162 return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
12165 // getTargetVShiftNode - Handle vector element shifts where the shift amount
12166 // may or may not be a constant. Takes immediate version of shift as input.
12167 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
12168 SDValue SrcOp, SDValue ShAmt,
12169 SelectionDAG &DAG) {
12170 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
12172 // Catch shift-by-constant.
12173 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
12174 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
12175 CShAmt->getZExtValue(), DAG);
12177 // Change opcode to non-immediate version
12179 default: llvm_unreachable("Unknown target vector shift node");
12180 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
12181 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
12182 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
12185 // Need to build a vector containing shift amount
12186 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
12189 ShOps[1] = DAG.getConstant(0, MVT::i32);
12190 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
12191 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
12193 // The return type has to be a 128-bit type with the same element
12194 // type as the input type.
12195 MVT EltVT = VT.getVectorElementType();
12196 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
12198 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
12199 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
12202 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
12204 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12206 default: return SDValue(); // Don't custom lower most intrinsics.
12207 // Comparison intrinsics.
12208 case Intrinsic::x86_sse_comieq_ss:
12209 case Intrinsic::x86_sse_comilt_ss:
12210 case Intrinsic::x86_sse_comile_ss:
12211 case Intrinsic::x86_sse_comigt_ss:
12212 case Intrinsic::x86_sse_comige_ss:
12213 case Intrinsic::x86_sse_comineq_ss:
12214 case Intrinsic::x86_sse_ucomieq_ss:
12215 case Intrinsic::x86_sse_ucomilt_ss:
12216 case Intrinsic::x86_sse_ucomile_ss:
12217 case Intrinsic::x86_sse_ucomigt_ss:
12218 case Intrinsic::x86_sse_ucomige_ss:
12219 case Intrinsic::x86_sse_ucomineq_ss:
12220 case Intrinsic::x86_sse2_comieq_sd:
12221 case Intrinsic::x86_sse2_comilt_sd:
12222 case Intrinsic::x86_sse2_comile_sd:
12223 case Intrinsic::x86_sse2_comigt_sd:
12224 case Intrinsic::x86_sse2_comige_sd:
12225 case Intrinsic::x86_sse2_comineq_sd:
12226 case Intrinsic::x86_sse2_ucomieq_sd:
12227 case Intrinsic::x86_sse2_ucomilt_sd:
12228 case Intrinsic::x86_sse2_ucomile_sd:
12229 case Intrinsic::x86_sse2_ucomigt_sd:
12230 case Intrinsic::x86_sse2_ucomige_sd:
12231 case Intrinsic::x86_sse2_ucomineq_sd: {
12235 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12236 case Intrinsic::x86_sse_comieq_ss:
12237 case Intrinsic::x86_sse2_comieq_sd:
12238 Opc = X86ISD::COMI;
12241 case Intrinsic::x86_sse_comilt_ss:
12242 case Intrinsic::x86_sse2_comilt_sd:
12243 Opc = X86ISD::COMI;
12246 case Intrinsic::x86_sse_comile_ss:
12247 case Intrinsic::x86_sse2_comile_sd:
12248 Opc = X86ISD::COMI;
12251 case Intrinsic::x86_sse_comigt_ss:
12252 case Intrinsic::x86_sse2_comigt_sd:
12253 Opc = X86ISD::COMI;
12256 case Intrinsic::x86_sse_comige_ss:
12257 case Intrinsic::x86_sse2_comige_sd:
12258 Opc = X86ISD::COMI;
12261 case Intrinsic::x86_sse_comineq_ss:
12262 case Intrinsic::x86_sse2_comineq_sd:
12263 Opc = X86ISD::COMI;
12266 case Intrinsic::x86_sse_ucomieq_ss:
12267 case Intrinsic::x86_sse2_ucomieq_sd:
12268 Opc = X86ISD::UCOMI;
12271 case Intrinsic::x86_sse_ucomilt_ss:
12272 case Intrinsic::x86_sse2_ucomilt_sd:
12273 Opc = X86ISD::UCOMI;
12276 case Intrinsic::x86_sse_ucomile_ss:
12277 case Intrinsic::x86_sse2_ucomile_sd:
12278 Opc = X86ISD::UCOMI;
12281 case Intrinsic::x86_sse_ucomigt_ss:
12282 case Intrinsic::x86_sse2_ucomigt_sd:
12283 Opc = X86ISD::UCOMI;
12286 case Intrinsic::x86_sse_ucomige_ss:
12287 case Intrinsic::x86_sse2_ucomige_sd:
12288 Opc = X86ISD::UCOMI;
12291 case Intrinsic::x86_sse_ucomineq_ss:
12292 case Intrinsic::x86_sse2_ucomineq_sd:
12293 Opc = X86ISD::UCOMI;
12298 SDValue LHS = Op.getOperand(1);
12299 SDValue RHS = Op.getOperand(2);
12300 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
12301 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
12302 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
12303 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12304 DAG.getConstant(X86CC, MVT::i8), Cond);
12305 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12308 // Arithmetic intrinsics.
12309 case Intrinsic::x86_sse2_pmulu_dq:
12310 case Intrinsic::x86_avx2_pmulu_dq:
12311 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
12312 Op.getOperand(1), Op.getOperand(2));
12314 case Intrinsic::x86_sse41_pmuldq:
12315 case Intrinsic::x86_avx2_pmul_dq:
12316 return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
12317 Op.getOperand(1), Op.getOperand(2));
12319 case Intrinsic::x86_sse2_pmulhu_w:
12320 case Intrinsic::x86_avx2_pmulhu_w:
12321 return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
12322 Op.getOperand(1), Op.getOperand(2));
12324 case Intrinsic::x86_sse2_pmulh_w:
12325 case Intrinsic::x86_avx2_pmulh_w:
12326 return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
12327 Op.getOperand(1), Op.getOperand(2));
12329 // SSE2/AVX2 sub with unsigned saturation intrinsics
12330 case Intrinsic::x86_sse2_psubus_b:
12331 case Intrinsic::x86_sse2_psubus_w:
12332 case Intrinsic::x86_avx2_psubus_b:
12333 case Intrinsic::x86_avx2_psubus_w:
12334 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
12335 Op.getOperand(1), Op.getOperand(2));
12337 // SSE3/AVX horizontal add/sub intrinsics
12338 case Intrinsic::x86_sse3_hadd_ps:
12339 case Intrinsic::x86_sse3_hadd_pd:
12340 case Intrinsic::x86_avx_hadd_ps_256:
12341 case Intrinsic::x86_avx_hadd_pd_256:
12342 case Intrinsic::x86_sse3_hsub_ps:
12343 case Intrinsic::x86_sse3_hsub_pd:
12344 case Intrinsic::x86_avx_hsub_ps_256:
12345 case Intrinsic::x86_avx_hsub_pd_256:
12346 case Intrinsic::x86_ssse3_phadd_w_128:
12347 case Intrinsic::x86_ssse3_phadd_d_128:
12348 case Intrinsic::x86_avx2_phadd_w:
12349 case Intrinsic::x86_avx2_phadd_d:
12350 case Intrinsic::x86_ssse3_phsub_w_128:
12351 case Intrinsic::x86_ssse3_phsub_d_128:
12352 case Intrinsic::x86_avx2_phsub_w:
12353 case Intrinsic::x86_avx2_phsub_d: {
12356 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12357 case Intrinsic::x86_sse3_hadd_ps:
12358 case Intrinsic::x86_sse3_hadd_pd:
12359 case Intrinsic::x86_avx_hadd_ps_256:
12360 case Intrinsic::x86_avx_hadd_pd_256:
12361 Opcode = X86ISD::FHADD;
12363 case Intrinsic::x86_sse3_hsub_ps:
12364 case Intrinsic::x86_sse3_hsub_pd:
12365 case Intrinsic::x86_avx_hsub_ps_256:
12366 case Intrinsic::x86_avx_hsub_pd_256:
12367 Opcode = X86ISD::FHSUB;
12369 case Intrinsic::x86_ssse3_phadd_w_128:
12370 case Intrinsic::x86_ssse3_phadd_d_128:
12371 case Intrinsic::x86_avx2_phadd_w:
12372 case Intrinsic::x86_avx2_phadd_d:
12373 Opcode = X86ISD::HADD;
12375 case Intrinsic::x86_ssse3_phsub_w_128:
12376 case Intrinsic::x86_ssse3_phsub_d_128:
12377 case Intrinsic::x86_avx2_phsub_w:
12378 case Intrinsic::x86_avx2_phsub_d:
12379 Opcode = X86ISD::HSUB;
12382 return DAG.getNode(Opcode, dl, Op.getValueType(),
12383 Op.getOperand(1), Op.getOperand(2));
12386 // SSE2/SSE41/AVX2 integer max/min intrinsics.
12387 case Intrinsic::x86_sse2_pmaxu_b:
12388 case Intrinsic::x86_sse41_pmaxuw:
12389 case Intrinsic::x86_sse41_pmaxud:
12390 case Intrinsic::x86_avx2_pmaxu_b:
12391 case Intrinsic::x86_avx2_pmaxu_w:
12392 case Intrinsic::x86_avx2_pmaxu_d:
12393 case Intrinsic::x86_sse2_pminu_b:
12394 case Intrinsic::x86_sse41_pminuw:
12395 case Intrinsic::x86_sse41_pminud:
12396 case Intrinsic::x86_avx2_pminu_b:
12397 case Intrinsic::x86_avx2_pminu_w:
12398 case Intrinsic::x86_avx2_pminu_d:
12399 case Intrinsic::x86_sse41_pmaxsb:
12400 case Intrinsic::x86_sse2_pmaxs_w:
12401 case Intrinsic::x86_sse41_pmaxsd:
12402 case Intrinsic::x86_avx2_pmaxs_b:
12403 case Intrinsic::x86_avx2_pmaxs_w:
12404 case Intrinsic::x86_avx2_pmaxs_d:
12405 case Intrinsic::x86_sse41_pminsb:
12406 case Intrinsic::x86_sse2_pmins_w:
12407 case Intrinsic::x86_sse41_pminsd:
12408 case Intrinsic::x86_avx2_pmins_b:
12409 case Intrinsic::x86_avx2_pmins_w:
12410 case Intrinsic::x86_avx2_pmins_d: {
12413 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12414 case Intrinsic::x86_sse2_pmaxu_b:
12415 case Intrinsic::x86_sse41_pmaxuw:
12416 case Intrinsic::x86_sse41_pmaxud:
12417 case Intrinsic::x86_avx2_pmaxu_b:
12418 case Intrinsic::x86_avx2_pmaxu_w:
12419 case Intrinsic::x86_avx2_pmaxu_d:
12420 Opcode = X86ISD::UMAX;
12422 case Intrinsic::x86_sse2_pminu_b:
12423 case Intrinsic::x86_sse41_pminuw:
12424 case Intrinsic::x86_sse41_pminud:
12425 case Intrinsic::x86_avx2_pminu_b:
12426 case Intrinsic::x86_avx2_pminu_w:
12427 case Intrinsic::x86_avx2_pminu_d:
12428 Opcode = X86ISD::UMIN;
12430 case Intrinsic::x86_sse41_pmaxsb:
12431 case Intrinsic::x86_sse2_pmaxs_w:
12432 case Intrinsic::x86_sse41_pmaxsd:
12433 case Intrinsic::x86_avx2_pmaxs_b:
12434 case Intrinsic::x86_avx2_pmaxs_w:
12435 case Intrinsic::x86_avx2_pmaxs_d:
12436 Opcode = X86ISD::SMAX;
12438 case Intrinsic::x86_sse41_pminsb:
12439 case Intrinsic::x86_sse2_pmins_w:
12440 case Intrinsic::x86_sse41_pminsd:
12441 case Intrinsic::x86_avx2_pmins_b:
12442 case Intrinsic::x86_avx2_pmins_w:
12443 case Intrinsic::x86_avx2_pmins_d:
12444 Opcode = X86ISD::SMIN;
12447 return DAG.getNode(Opcode, dl, Op.getValueType(),
12448 Op.getOperand(1), Op.getOperand(2));
12451 // SSE/SSE2/AVX floating point max/min intrinsics.
12452 case Intrinsic::x86_sse_max_ps:
12453 case Intrinsic::x86_sse2_max_pd:
12454 case Intrinsic::x86_avx_max_ps_256:
12455 case Intrinsic::x86_avx_max_pd_256:
12456 case Intrinsic::x86_sse_min_ps:
12457 case Intrinsic::x86_sse2_min_pd:
12458 case Intrinsic::x86_avx_min_ps_256:
12459 case Intrinsic::x86_avx_min_pd_256: {
12462 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12463 case Intrinsic::x86_sse_max_ps:
12464 case Intrinsic::x86_sse2_max_pd:
12465 case Intrinsic::x86_avx_max_ps_256:
12466 case Intrinsic::x86_avx_max_pd_256:
12467 Opcode = X86ISD::FMAX;
12469 case Intrinsic::x86_sse_min_ps:
12470 case Intrinsic::x86_sse2_min_pd:
12471 case Intrinsic::x86_avx_min_ps_256:
12472 case Intrinsic::x86_avx_min_pd_256:
12473 Opcode = X86ISD::FMIN;
12476 return DAG.getNode(Opcode, dl, Op.getValueType(),
12477 Op.getOperand(1), Op.getOperand(2));
12480 // AVX2 variable shift intrinsics
12481 case Intrinsic::x86_avx2_psllv_d:
12482 case Intrinsic::x86_avx2_psllv_q:
12483 case Intrinsic::x86_avx2_psllv_d_256:
12484 case Intrinsic::x86_avx2_psllv_q_256:
12485 case Intrinsic::x86_avx2_psrlv_d:
12486 case Intrinsic::x86_avx2_psrlv_q:
12487 case Intrinsic::x86_avx2_psrlv_d_256:
12488 case Intrinsic::x86_avx2_psrlv_q_256:
12489 case Intrinsic::x86_avx2_psrav_d:
12490 case Intrinsic::x86_avx2_psrav_d_256: {
12493 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12494 case Intrinsic::x86_avx2_psllv_d:
12495 case Intrinsic::x86_avx2_psllv_q:
12496 case Intrinsic::x86_avx2_psllv_d_256:
12497 case Intrinsic::x86_avx2_psllv_q_256:
12500 case Intrinsic::x86_avx2_psrlv_d:
12501 case Intrinsic::x86_avx2_psrlv_q:
12502 case Intrinsic::x86_avx2_psrlv_d_256:
12503 case Intrinsic::x86_avx2_psrlv_q_256:
12506 case Intrinsic::x86_avx2_psrav_d:
12507 case Intrinsic::x86_avx2_psrav_d_256:
12511 return DAG.getNode(Opcode, dl, Op.getValueType(),
12512 Op.getOperand(1), Op.getOperand(2));
12515 case Intrinsic::x86_sse2_packssdw_128:
12516 case Intrinsic::x86_sse2_packsswb_128:
12517 case Intrinsic::x86_avx2_packssdw:
12518 case Intrinsic::x86_avx2_packsswb:
12519 return DAG.getNode(X86ISD::PACKSS, dl, Op.getValueType(),
12520 Op.getOperand(1), Op.getOperand(2));
12522 case Intrinsic::x86_sse2_packuswb_128:
12523 case Intrinsic::x86_sse41_packusdw:
12524 case Intrinsic::x86_avx2_packuswb:
12525 case Intrinsic::x86_avx2_packusdw:
12526 return DAG.getNode(X86ISD::PACKUS, dl, Op.getValueType(),
12527 Op.getOperand(1), Op.getOperand(2));
12529 case Intrinsic::x86_ssse3_pshuf_b_128:
12530 case Intrinsic::x86_avx2_pshuf_b:
12531 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
12532 Op.getOperand(1), Op.getOperand(2));
12534 case Intrinsic::x86_ssse3_psign_b_128:
12535 case Intrinsic::x86_ssse3_psign_w_128:
12536 case Intrinsic::x86_ssse3_psign_d_128:
12537 case Intrinsic::x86_avx2_psign_b:
12538 case Intrinsic::x86_avx2_psign_w:
12539 case Intrinsic::x86_avx2_psign_d:
12540 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
12541 Op.getOperand(1), Op.getOperand(2));
12543 case Intrinsic::x86_sse41_insertps:
12544 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
12545 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
12547 case Intrinsic::x86_avx_vperm2f128_ps_256:
12548 case Intrinsic::x86_avx_vperm2f128_pd_256:
12549 case Intrinsic::x86_avx_vperm2f128_si_256:
12550 case Intrinsic::x86_avx2_vperm2i128:
12551 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
12552 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
12554 case Intrinsic::x86_avx2_permd:
12555 case Intrinsic::x86_avx2_permps:
12556 // Operands intentionally swapped. Mask is last operand to intrinsic,
12557 // but second operand for node/instruction.
12558 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
12559 Op.getOperand(2), Op.getOperand(1));
12561 case Intrinsic::x86_sse_sqrt_ps:
12562 case Intrinsic::x86_sse2_sqrt_pd:
12563 case Intrinsic::x86_avx_sqrt_ps_256:
12564 case Intrinsic::x86_avx_sqrt_pd_256:
12565 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
12567 // ptest and testp intrinsics. The intrinsic these come from are designed to
12568 // return an integer value, not just an instruction so lower it to the ptest
12569 // or testp pattern and a setcc for the result.
12570 case Intrinsic::x86_sse41_ptestz:
12571 case Intrinsic::x86_sse41_ptestc:
12572 case Intrinsic::x86_sse41_ptestnzc:
12573 case Intrinsic::x86_avx_ptestz_256:
12574 case Intrinsic::x86_avx_ptestc_256:
12575 case Intrinsic::x86_avx_ptestnzc_256:
12576 case Intrinsic::x86_avx_vtestz_ps:
12577 case Intrinsic::x86_avx_vtestc_ps:
12578 case Intrinsic::x86_avx_vtestnzc_ps:
12579 case Intrinsic::x86_avx_vtestz_pd:
12580 case Intrinsic::x86_avx_vtestc_pd:
12581 case Intrinsic::x86_avx_vtestnzc_pd:
12582 case Intrinsic::x86_avx_vtestz_ps_256:
12583 case Intrinsic::x86_avx_vtestc_ps_256:
12584 case Intrinsic::x86_avx_vtestnzc_ps_256:
12585 case Intrinsic::x86_avx_vtestz_pd_256:
12586 case Intrinsic::x86_avx_vtestc_pd_256:
12587 case Intrinsic::x86_avx_vtestnzc_pd_256: {
12588 bool IsTestPacked = false;
12591 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
12592 case Intrinsic::x86_avx_vtestz_ps:
12593 case Intrinsic::x86_avx_vtestz_pd:
12594 case Intrinsic::x86_avx_vtestz_ps_256:
12595 case Intrinsic::x86_avx_vtestz_pd_256:
12596 IsTestPacked = true; // Fallthrough
12597 case Intrinsic::x86_sse41_ptestz:
12598 case Intrinsic::x86_avx_ptestz_256:
12600 X86CC = X86::COND_E;
12602 case Intrinsic::x86_avx_vtestc_ps:
12603 case Intrinsic::x86_avx_vtestc_pd:
12604 case Intrinsic::x86_avx_vtestc_ps_256:
12605 case Intrinsic::x86_avx_vtestc_pd_256:
12606 IsTestPacked = true; // Fallthrough
12607 case Intrinsic::x86_sse41_ptestc:
12608 case Intrinsic::x86_avx_ptestc_256:
12610 X86CC = X86::COND_B;
12612 case Intrinsic::x86_avx_vtestnzc_ps:
12613 case Intrinsic::x86_avx_vtestnzc_pd:
12614 case Intrinsic::x86_avx_vtestnzc_ps_256:
12615 case Intrinsic::x86_avx_vtestnzc_pd_256:
12616 IsTestPacked = true; // Fallthrough
12617 case Intrinsic::x86_sse41_ptestnzc:
12618 case Intrinsic::x86_avx_ptestnzc_256:
12620 X86CC = X86::COND_A;
12624 SDValue LHS = Op.getOperand(1);
12625 SDValue RHS = Op.getOperand(2);
12626 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
12627 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
12628 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12629 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
12630 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12632 case Intrinsic::x86_avx512_kortestz_w:
12633 case Intrinsic::x86_avx512_kortestc_w: {
12634 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
12635 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
12636 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
12637 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12638 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
12639 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
12640 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12643 // SSE/AVX shift intrinsics
12644 case Intrinsic::x86_sse2_psll_w:
12645 case Intrinsic::x86_sse2_psll_d:
12646 case Intrinsic::x86_sse2_psll_q:
12647 case Intrinsic::x86_avx2_psll_w:
12648 case Intrinsic::x86_avx2_psll_d:
12649 case Intrinsic::x86_avx2_psll_q:
12650 case Intrinsic::x86_sse2_psrl_w:
12651 case Intrinsic::x86_sse2_psrl_d:
12652 case Intrinsic::x86_sse2_psrl_q:
12653 case Intrinsic::x86_avx2_psrl_w:
12654 case Intrinsic::x86_avx2_psrl_d:
12655 case Intrinsic::x86_avx2_psrl_q:
12656 case Intrinsic::x86_sse2_psra_w:
12657 case Intrinsic::x86_sse2_psra_d:
12658 case Intrinsic::x86_avx2_psra_w:
12659 case Intrinsic::x86_avx2_psra_d: {
12662 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12663 case Intrinsic::x86_sse2_psll_w:
12664 case Intrinsic::x86_sse2_psll_d:
12665 case Intrinsic::x86_sse2_psll_q:
12666 case Intrinsic::x86_avx2_psll_w:
12667 case Intrinsic::x86_avx2_psll_d:
12668 case Intrinsic::x86_avx2_psll_q:
12669 Opcode = X86ISD::VSHL;
12671 case Intrinsic::x86_sse2_psrl_w:
12672 case Intrinsic::x86_sse2_psrl_d:
12673 case Intrinsic::x86_sse2_psrl_q:
12674 case Intrinsic::x86_avx2_psrl_w:
12675 case Intrinsic::x86_avx2_psrl_d:
12676 case Intrinsic::x86_avx2_psrl_q:
12677 Opcode = X86ISD::VSRL;
12679 case Intrinsic::x86_sse2_psra_w:
12680 case Intrinsic::x86_sse2_psra_d:
12681 case Intrinsic::x86_avx2_psra_w:
12682 case Intrinsic::x86_avx2_psra_d:
12683 Opcode = X86ISD::VSRA;
12686 return DAG.getNode(Opcode, dl, Op.getValueType(),
12687 Op.getOperand(1), Op.getOperand(2));
12690 // SSE/AVX immediate shift intrinsics
12691 case Intrinsic::x86_sse2_pslli_w:
12692 case Intrinsic::x86_sse2_pslli_d:
12693 case Intrinsic::x86_sse2_pslli_q:
12694 case Intrinsic::x86_avx2_pslli_w:
12695 case Intrinsic::x86_avx2_pslli_d:
12696 case Intrinsic::x86_avx2_pslli_q:
12697 case Intrinsic::x86_sse2_psrli_w:
12698 case Intrinsic::x86_sse2_psrli_d:
12699 case Intrinsic::x86_sse2_psrli_q:
12700 case Intrinsic::x86_avx2_psrli_w:
12701 case Intrinsic::x86_avx2_psrli_d:
12702 case Intrinsic::x86_avx2_psrli_q:
12703 case Intrinsic::x86_sse2_psrai_w:
12704 case Intrinsic::x86_sse2_psrai_d:
12705 case Intrinsic::x86_avx2_psrai_w:
12706 case Intrinsic::x86_avx2_psrai_d: {
12709 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12710 case Intrinsic::x86_sse2_pslli_w:
12711 case Intrinsic::x86_sse2_pslli_d:
12712 case Intrinsic::x86_sse2_pslli_q:
12713 case Intrinsic::x86_avx2_pslli_w:
12714 case Intrinsic::x86_avx2_pslli_d:
12715 case Intrinsic::x86_avx2_pslli_q:
12716 Opcode = X86ISD::VSHLI;
12718 case Intrinsic::x86_sse2_psrli_w:
12719 case Intrinsic::x86_sse2_psrli_d:
12720 case Intrinsic::x86_sse2_psrli_q:
12721 case Intrinsic::x86_avx2_psrli_w:
12722 case Intrinsic::x86_avx2_psrli_d:
12723 case Intrinsic::x86_avx2_psrli_q:
12724 Opcode = X86ISD::VSRLI;
12726 case Intrinsic::x86_sse2_psrai_w:
12727 case Intrinsic::x86_sse2_psrai_d:
12728 case Intrinsic::x86_avx2_psrai_w:
12729 case Intrinsic::x86_avx2_psrai_d:
12730 Opcode = X86ISD::VSRAI;
12733 return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
12734 Op.getOperand(1), Op.getOperand(2), DAG);
12737 case Intrinsic::x86_sse42_pcmpistria128:
12738 case Intrinsic::x86_sse42_pcmpestria128:
12739 case Intrinsic::x86_sse42_pcmpistric128:
12740 case Intrinsic::x86_sse42_pcmpestric128:
12741 case Intrinsic::x86_sse42_pcmpistrio128:
12742 case Intrinsic::x86_sse42_pcmpestrio128:
12743 case Intrinsic::x86_sse42_pcmpistris128:
12744 case Intrinsic::x86_sse42_pcmpestris128:
12745 case Intrinsic::x86_sse42_pcmpistriz128:
12746 case Intrinsic::x86_sse42_pcmpestriz128: {
12750 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12751 case Intrinsic::x86_sse42_pcmpistria128:
12752 Opcode = X86ISD::PCMPISTRI;
12753 X86CC = X86::COND_A;
12755 case Intrinsic::x86_sse42_pcmpestria128:
12756 Opcode = X86ISD::PCMPESTRI;
12757 X86CC = X86::COND_A;
12759 case Intrinsic::x86_sse42_pcmpistric128:
12760 Opcode = X86ISD::PCMPISTRI;
12761 X86CC = X86::COND_B;
12763 case Intrinsic::x86_sse42_pcmpestric128:
12764 Opcode = X86ISD::PCMPESTRI;
12765 X86CC = X86::COND_B;
12767 case Intrinsic::x86_sse42_pcmpistrio128:
12768 Opcode = X86ISD::PCMPISTRI;
12769 X86CC = X86::COND_O;
12771 case Intrinsic::x86_sse42_pcmpestrio128:
12772 Opcode = X86ISD::PCMPESTRI;
12773 X86CC = X86::COND_O;
12775 case Intrinsic::x86_sse42_pcmpistris128:
12776 Opcode = X86ISD::PCMPISTRI;
12777 X86CC = X86::COND_S;
12779 case Intrinsic::x86_sse42_pcmpestris128:
12780 Opcode = X86ISD::PCMPESTRI;
12781 X86CC = X86::COND_S;
12783 case Intrinsic::x86_sse42_pcmpistriz128:
12784 Opcode = X86ISD::PCMPISTRI;
12785 X86CC = X86::COND_E;
12787 case Intrinsic::x86_sse42_pcmpestriz128:
12788 Opcode = X86ISD::PCMPESTRI;
12789 X86CC = X86::COND_E;
12792 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12793 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12794 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
12795 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12796 DAG.getConstant(X86CC, MVT::i8),
12797 SDValue(PCMP.getNode(), 1));
12798 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12801 case Intrinsic::x86_sse42_pcmpistri128:
12802 case Intrinsic::x86_sse42_pcmpestri128: {
12804 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
12805 Opcode = X86ISD::PCMPISTRI;
12807 Opcode = X86ISD::PCMPESTRI;
12809 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12810 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12811 return DAG.getNode(Opcode, dl, VTs, NewOps);
12813 case Intrinsic::x86_fma_vfmadd_ps:
12814 case Intrinsic::x86_fma_vfmadd_pd:
12815 case Intrinsic::x86_fma_vfmsub_ps:
12816 case Intrinsic::x86_fma_vfmsub_pd:
12817 case Intrinsic::x86_fma_vfnmadd_ps:
12818 case Intrinsic::x86_fma_vfnmadd_pd:
12819 case Intrinsic::x86_fma_vfnmsub_ps:
12820 case Intrinsic::x86_fma_vfnmsub_pd:
12821 case Intrinsic::x86_fma_vfmaddsub_ps:
12822 case Intrinsic::x86_fma_vfmaddsub_pd:
12823 case Intrinsic::x86_fma_vfmsubadd_ps:
12824 case Intrinsic::x86_fma_vfmsubadd_pd:
12825 case Intrinsic::x86_fma_vfmadd_ps_256:
12826 case Intrinsic::x86_fma_vfmadd_pd_256:
12827 case Intrinsic::x86_fma_vfmsub_ps_256:
12828 case Intrinsic::x86_fma_vfmsub_pd_256:
12829 case Intrinsic::x86_fma_vfnmadd_ps_256:
12830 case Intrinsic::x86_fma_vfnmadd_pd_256:
12831 case Intrinsic::x86_fma_vfnmsub_ps_256:
12832 case Intrinsic::x86_fma_vfnmsub_pd_256:
12833 case Intrinsic::x86_fma_vfmaddsub_ps_256:
12834 case Intrinsic::x86_fma_vfmaddsub_pd_256:
12835 case Intrinsic::x86_fma_vfmsubadd_ps_256:
12836 case Intrinsic::x86_fma_vfmsubadd_pd_256:
12837 case Intrinsic::x86_fma_vfmadd_ps_512:
12838 case Intrinsic::x86_fma_vfmadd_pd_512:
12839 case Intrinsic::x86_fma_vfmsub_ps_512:
12840 case Intrinsic::x86_fma_vfmsub_pd_512:
12841 case Intrinsic::x86_fma_vfnmadd_ps_512:
12842 case Intrinsic::x86_fma_vfnmadd_pd_512:
12843 case Intrinsic::x86_fma_vfnmsub_ps_512:
12844 case Intrinsic::x86_fma_vfnmsub_pd_512:
12845 case Intrinsic::x86_fma_vfmaddsub_ps_512:
12846 case Intrinsic::x86_fma_vfmaddsub_pd_512:
12847 case Intrinsic::x86_fma_vfmsubadd_ps_512:
12848 case Intrinsic::x86_fma_vfmsubadd_pd_512: {
12851 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12852 case Intrinsic::x86_fma_vfmadd_ps:
12853 case Intrinsic::x86_fma_vfmadd_pd:
12854 case Intrinsic::x86_fma_vfmadd_ps_256:
12855 case Intrinsic::x86_fma_vfmadd_pd_256:
12856 case Intrinsic::x86_fma_vfmadd_ps_512:
12857 case Intrinsic::x86_fma_vfmadd_pd_512:
12858 Opc = X86ISD::FMADD;
12860 case Intrinsic::x86_fma_vfmsub_ps:
12861 case Intrinsic::x86_fma_vfmsub_pd:
12862 case Intrinsic::x86_fma_vfmsub_ps_256:
12863 case Intrinsic::x86_fma_vfmsub_pd_256:
12864 case Intrinsic::x86_fma_vfmsub_ps_512:
12865 case Intrinsic::x86_fma_vfmsub_pd_512:
12866 Opc = X86ISD::FMSUB;
12868 case Intrinsic::x86_fma_vfnmadd_ps:
12869 case Intrinsic::x86_fma_vfnmadd_pd:
12870 case Intrinsic::x86_fma_vfnmadd_ps_256:
12871 case Intrinsic::x86_fma_vfnmadd_pd_256:
12872 case Intrinsic::x86_fma_vfnmadd_ps_512:
12873 case Intrinsic::x86_fma_vfnmadd_pd_512:
12874 Opc = X86ISD::FNMADD;
12876 case Intrinsic::x86_fma_vfnmsub_ps:
12877 case Intrinsic::x86_fma_vfnmsub_pd:
12878 case Intrinsic::x86_fma_vfnmsub_ps_256:
12879 case Intrinsic::x86_fma_vfnmsub_pd_256:
12880 case Intrinsic::x86_fma_vfnmsub_ps_512:
12881 case Intrinsic::x86_fma_vfnmsub_pd_512:
12882 Opc = X86ISD::FNMSUB;
12884 case Intrinsic::x86_fma_vfmaddsub_ps:
12885 case Intrinsic::x86_fma_vfmaddsub_pd:
12886 case Intrinsic::x86_fma_vfmaddsub_ps_256:
12887 case Intrinsic::x86_fma_vfmaddsub_pd_256:
12888 case Intrinsic::x86_fma_vfmaddsub_ps_512:
12889 case Intrinsic::x86_fma_vfmaddsub_pd_512:
12890 Opc = X86ISD::FMADDSUB;
12892 case Intrinsic::x86_fma_vfmsubadd_ps:
12893 case Intrinsic::x86_fma_vfmsubadd_pd:
12894 case Intrinsic::x86_fma_vfmsubadd_ps_256:
12895 case Intrinsic::x86_fma_vfmsubadd_pd_256:
12896 case Intrinsic::x86_fma_vfmsubadd_ps_512:
12897 case Intrinsic::x86_fma_vfmsubadd_pd_512:
12898 Opc = X86ISD::FMSUBADD;
12902 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
12903 Op.getOperand(2), Op.getOperand(3));
12908 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12909 SDValue Src, SDValue Mask, SDValue Base,
12910 SDValue Index, SDValue ScaleOp, SDValue Chain,
12911 const X86Subtarget * Subtarget) {
12913 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12914 assert(C && "Invalid scale type");
12915 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12916 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12917 Index.getSimpleValueType().getVectorNumElements());
12919 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12921 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12923 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12924 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12925 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12926 SDValue Segment = DAG.getRegister(0, MVT::i32);
12927 if (Src.getOpcode() == ISD::UNDEF)
12928 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12929 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12930 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12931 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12932 return DAG.getMergeValues(RetOps, dl);
12935 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12936 SDValue Src, SDValue Mask, SDValue Base,
12937 SDValue Index, SDValue ScaleOp, SDValue Chain) {
12939 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12940 assert(C && "Invalid scale type");
12941 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12942 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12943 SDValue Segment = DAG.getRegister(0, MVT::i32);
12944 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12945 Index.getSimpleValueType().getVectorNumElements());
12947 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12949 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12951 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12952 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12953 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12954 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12955 return SDValue(Res, 1);
12958 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12959 SDValue Mask, SDValue Base, SDValue Index,
12960 SDValue ScaleOp, SDValue Chain) {
12962 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12963 assert(C && "Invalid scale type");
12964 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12965 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12966 SDValue Segment = DAG.getRegister(0, MVT::i32);
12968 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
12970 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12972 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12974 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12975 //SDVTList VTs = DAG.getVTList(MVT::Other);
12976 SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12977 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
12978 return SDValue(Res, 0);
12981 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
12982 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
12983 // also used to custom lower READCYCLECOUNTER nodes.
12984 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
12985 SelectionDAG &DAG, const X86Subtarget *Subtarget,
12986 SmallVectorImpl<SDValue> &Results) {
12987 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12988 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
12991 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
12992 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
12993 // and the EAX register is loaded with the low-order 32 bits.
12994 if (Subtarget->is64Bit()) {
12995 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
12996 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
12999 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
13000 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
13003 SDValue Chain = HI.getValue(1);
13005 if (Opcode == X86ISD::RDTSCP_DAG) {
13006 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
13008 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
13009 // the ECX register. Add 'ecx' explicitly to the chain.
13010 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
13012 // Explicitly store the content of ECX at the location passed in input
13013 // to the 'rdtscp' intrinsic.
13014 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
13015 MachinePointerInfo(), false, false, 0);
13018 if (Subtarget->is64Bit()) {
13019 // The EDX register is loaded with the high-order 32 bits of the MSR, and
13020 // the EAX register is loaded with the low-order 32 bits.
13021 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
13022 DAG.getConstant(32, MVT::i8));
13023 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
13024 Results.push_back(Chain);
13028 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
13029 SDValue Ops[] = { LO, HI };
13030 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
13031 Results.push_back(Pair);
13032 Results.push_back(Chain);
13035 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
13036 SelectionDAG &DAG) {
13037 SmallVector<SDValue, 2> Results;
13039 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
13041 return DAG.getMergeValues(Results, DL);
13044 enum IntrinsicType {
13045 GATHER, SCATTER, PREFETCH, RDSEED, RDRAND, RDTSC, XTEST
13048 struct IntrinsicData {
13049 IntrinsicData(IntrinsicType IType, unsigned IOpc0, unsigned IOpc1)
13050 :Type(IType), Opc0(IOpc0), Opc1(IOpc1) {}
13051 IntrinsicType Type;
13056 std::map < unsigned, IntrinsicData> IntrMap;
13057 static void InitIntinsicsMap() {
13058 static bool Initialized = false;
13061 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
13062 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
13063 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
13064 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
13065 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpd_512,
13066 IntrinsicData(GATHER, X86::VGATHERQPDZrm, 0)));
13067 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpd_512,
13068 IntrinsicData(GATHER, X86::VGATHERDPDZrm, 0)));
13069 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dps_512,
13070 IntrinsicData(GATHER, X86::VGATHERDPSZrm, 0)));
13071 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpi_512,
13072 IntrinsicData(GATHER, X86::VPGATHERQDZrm, 0)));
13073 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpq_512,
13074 IntrinsicData(GATHER, X86::VPGATHERQQZrm, 0)));
13075 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpi_512,
13076 IntrinsicData(GATHER, X86::VPGATHERDDZrm, 0)));
13077 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpq_512,
13078 IntrinsicData(GATHER, X86::VPGATHERDQZrm, 0)));
13080 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qps_512,
13081 IntrinsicData(SCATTER, X86::VSCATTERQPSZmr, 0)));
13082 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpd_512,
13083 IntrinsicData(SCATTER, X86::VSCATTERQPDZmr, 0)));
13084 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpd_512,
13085 IntrinsicData(SCATTER, X86::VSCATTERDPDZmr, 0)));
13086 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dps_512,
13087 IntrinsicData(SCATTER, X86::VSCATTERDPSZmr, 0)));
13088 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpi_512,
13089 IntrinsicData(SCATTER, X86::VPSCATTERQDZmr, 0)));
13090 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpq_512,
13091 IntrinsicData(SCATTER, X86::VPSCATTERQQZmr, 0)));
13092 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpi_512,
13093 IntrinsicData(SCATTER, X86::VPSCATTERDDZmr, 0)));
13094 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpq_512,
13095 IntrinsicData(SCATTER, X86::VPSCATTERDQZmr, 0)));
13097 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qps_512,
13098 IntrinsicData(PREFETCH, X86::VGATHERPF0QPSm,
13099 X86::VGATHERPF1QPSm)));
13100 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qpd_512,
13101 IntrinsicData(PREFETCH, X86::VGATHERPF0QPDm,
13102 X86::VGATHERPF1QPDm)));
13103 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dpd_512,
13104 IntrinsicData(PREFETCH, X86::VGATHERPF0DPDm,
13105 X86::VGATHERPF1DPDm)));
13106 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dps_512,
13107 IntrinsicData(PREFETCH, X86::VGATHERPF0DPSm,
13108 X86::VGATHERPF1DPSm)));
13109 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qps_512,
13110 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPSm,
13111 X86::VSCATTERPF1QPSm)));
13112 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qpd_512,
13113 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPDm,
13114 X86::VSCATTERPF1QPDm)));
13115 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dpd_512,
13116 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPDm,
13117 X86::VSCATTERPF1DPDm)));
13118 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dps_512,
13119 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPSm,
13120 X86::VSCATTERPF1DPSm)));
13121 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_16,
13122 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
13123 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_32,
13124 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
13125 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_64,
13126 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
13127 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_16,
13128 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
13129 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_32,
13130 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
13131 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_64,
13132 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
13133 IntrMap.insert(std::make_pair(Intrinsic::x86_xtest,
13134 IntrinsicData(XTEST, X86ISD::XTEST, 0)));
13135 IntrMap.insert(std::make_pair(Intrinsic::x86_rdtsc,
13136 IntrinsicData(RDTSC, X86ISD::RDTSC_DAG, 0)));
13137 IntrMap.insert(std::make_pair(Intrinsic::x86_rdtscp,
13138 IntrinsicData(RDTSC, X86ISD::RDTSCP_DAG, 0)));
13139 Initialized = true;
13142 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
13143 SelectionDAG &DAG) {
13144 InitIntinsicsMap();
13145 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
13146 std::map < unsigned, IntrinsicData>::const_iterator itr = IntrMap.find(IntNo);
13147 if (itr == IntrMap.end())
13151 IntrinsicData Intr = itr->second;
13152 switch(Intr.Type) {
13155 // Emit the node with the right value type.
13156 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
13157 SDValue Result = DAG.getNode(Intr.Opc0, dl, VTs, Op.getOperand(0));
13159 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
13160 // Otherwise return the value from Rand, which is always 0, casted to i32.
13161 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
13162 DAG.getConstant(1, Op->getValueType(1)),
13163 DAG.getConstant(X86::COND_B, MVT::i32),
13164 SDValue(Result.getNode(), 1) };
13165 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
13166 DAG.getVTList(Op->getValueType(1), MVT::Glue),
13169 // Return { result, isValid, chain }.
13170 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
13171 SDValue(Result.getNode(), 2));
13174 //gather(v1, mask, index, base, scale);
13175 SDValue Chain = Op.getOperand(0);
13176 SDValue Src = Op.getOperand(2);
13177 SDValue Base = Op.getOperand(3);
13178 SDValue Index = Op.getOperand(4);
13179 SDValue Mask = Op.getOperand(5);
13180 SDValue Scale = Op.getOperand(6);
13181 return getGatherNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
13185 //scatter(base, mask, index, v1, scale);
13186 SDValue Chain = Op.getOperand(0);
13187 SDValue Base = Op.getOperand(2);
13188 SDValue Mask = Op.getOperand(3);
13189 SDValue Index = Op.getOperand(4);
13190 SDValue Src = Op.getOperand(5);
13191 SDValue Scale = Op.getOperand(6);
13192 return getScatterNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
13195 SDValue Hint = Op.getOperand(6);
13197 if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
13198 (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
13199 llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
13200 unsigned Opcode = (HintVal ? Intr.Opc1 : Intr.Opc0);
13201 SDValue Chain = Op.getOperand(0);
13202 SDValue Mask = Op.getOperand(2);
13203 SDValue Index = Op.getOperand(3);
13204 SDValue Base = Op.getOperand(4);
13205 SDValue Scale = Op.getOperand(5);
13206 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
13208 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
13210 SmallVector<SDValue, 2> Results;
13211 getReadTimeStampCounter(Op.getNode(), dl, Intr.Opc0, DAG, Subtarget, Results);
13212 return DAG.getMergeValues(Results, dl);
13214 // XTEST intrinsics.
13216 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
13217 SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
13218 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13219 DAG.getConstant(X86::COND_NE, MVT::i8),
13221 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
13222 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
13223 Ret, SDValue(InTrans.getNode(), 1));
13226 llvm_unreachable("Unknown Intrinsic Type");
13229 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
13230 SelectionDAG &DAG) const {
13231 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13232 MFI->setReturnAddressIsTaken(true);
13234 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
13237 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13239 EVT PtrVT = getPointerTy();
13242 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
13243 const X86RegisterInfo *RegInfo =
13244 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13245 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
13246 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
13247 DAG.getNode(ISD::ADD, dl, PtrVT,
13248 FrameAddr, Offset),
13249 MachinePointerInfo(), false, false, false, 0);
13252 // Just load the return address.
13253 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
13254 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
13255 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
13258 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
13259 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13260 MFI->setFrameAddressIsTaken(true);
13262 EVT VT = Op.getValueType();
13263 SDLoc dl(Op); // FIXME probably not meaningful
13264 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13265 const X86RegisterInfo *RegInfo =
13266 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13267 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
13268 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
13269 (FrameReg == X86::EBP && VT == MVT::i32)) &&
13270 "Invalid Frame Register!");
13271 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
13273 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
13274 MachinePointerInfo(),
13275 false, false, false, 0);
13279 // FIXME? Maybe this could be a TableGen attribute on some registers and
13280 // this table could be generated automatically from RegInfo.
13281 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
13283 unsigned Reg = StringSwitch<unsigned>(RegName)
13284 .Case("esp", X86::ESP)
13285 .Case("rsp", X86::RSP)
13289 report_fatal_error("Invalid register name global variable");
13292 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
13293 SelectionDAG &DAG) const {
13294 const X86RegisterInfo *RegInfo =
13295 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13296 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
13299 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
13300 SDValue Chain = Op.getOperand(0);
13301 SDValue Offset = Op.getOperand(1);
13302 SDValue Handler = Op.getOperand(2);
13305 EVT PtrVT = getPointerTy();
13306 const X86RegisterInfo *RegInfo =
13307 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13308 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
13309 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
13310 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
13311 "Invalid Frame Register!");
13312 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
13313 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
13315 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
13316 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
13317 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
13318 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
13320 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
13322 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
13323 DAG.getRegister(StoreAddrReg, PtrVT));
13326 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
13327 SelectionDAG &DAG) const {
13329 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
13330 DAG.getVTList(MVT::i32, MVT::Other),
13331 Op.getOperand(0), Op.getOperand(1));
13334 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
13335 SelectionDAG &DAG) const {
13337 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
13338 Op.getOperand(0), Op.getOperand(1));
13341 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
13342 return Op.getOperand(0);
13345 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
13346 SelectionDAG &DAG) const {
13347 SDValue Root = Op.getOperand(0);
13348 SDValue Trmp = Op.getOperand(1); // trampoline
13349 SDValue FPtr = Op.getOperand(2); // nested function
13350 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
13353 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
13354 const TargetRegisterInfo* TRI = DAG.getTarget().getRegisterInfo();
13356 if (Subtarget->is64Bit()) {
13357 SDValue OutChains[6];
13359 // Large code-model.
13360 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
13361 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
13363 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
13364 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
13366 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
13368 // Load the pointer to the nested function into R11.
13369 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
13370 SDValue Addr = Trmp;
13371 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13372 Addr, MachinePointerInfo(TrmpAddr),
13375 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13376 DAG.getConstant(2, MVT::i64));
13377 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
13378 MachinePointerInfo(TrmpAddr, 2),
13381 // Load the 'nest' parameter value into R10.
13382 // R10 is specified in X86CallingConv.td
13383 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
13384 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13385 DAG.getConstant(10, MVT::i64));
13386 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13387 Addr, MachinePointerInfo(TrmpAddr, 10),
13390 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13391 DAG.getConstant(12, MVT::i64));
13392 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
13393 MachinePointerInfo(TrmpAddr, 12),
13396 // Jump to the nested function.
13397 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
13398 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13399 DAG.getConstant(20, MVT::i64));
13400 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13401 Addr, MachinePointerInfo(TrmpAddr, 20),
13404 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
13405 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13406 DAG.getConstant(22, MVT::i64));
13407 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
13408 MachinePointerInfo(TrmpAddr, 22),
13411 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
13413 const Function *Func =
13414 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
13415 CallingConv::ID CC = Func->getCallingConv();
13420 llvm_unreachable("Unsupported calling convention");
13421 case CallingConv::C:
13422 case CallingConv::X86_StdCall: {
13423 // Pass 'nest' parameter in ECX.
13424 // Must be kept in sync with X86CallingConv.td
13425 NestReg = X86::ECX;
13427 // Check that ECX wasn't needed by an 'inreg' parameter.
13428 FunctionType *FTy = Func->getFunctionType();
13429 const AttributeSet &Attrs = Func->getAttributes();
13431 if (!Attrs.isEmpty() && !Func->isVarArg()) {
13432 unsigned InRegCount = 0;
13435 for (FunctionType::param_iterator I = FTy->param_begin(),
13436 E = FTy->param_end(); I != E; ++I, ++Idx)
13437 if (Attrs.hasAttribute(Idx, Attribute::InReg))
13438 // FIXME: should only count parameters that are lowered to integers.
13439 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
13441 if (InRegCount > 2) {
13442 report_fatal_error("Nest register in use - reduce number of inreg"
13448 case CallingConv::X86_FastCall:
13449 case CallingConv::X86_ThisCall:
13450 case CallingConv::Fast:
13451 // Pass 'nest' parameter in EAX.
13452 // Must be kept in sync with X86CallingConv.td
13453 NestReg = X86::EAX;
13457 SDValue OutChains[4];
13458 SDValue Addr, Disp;
13460 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13461 DAG.getConstant(10, MVT::i32));
13462 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
13464 // This is storing the opcode for MOV32ri.
13465 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
13466 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
13467 OutChains[0] = DAG.getStore(Root, dl,
13468 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
13469 Trmp, MachinePointerInfo(TrmpAddr),
13472 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13473 DAG.getConstant(1, MVT::i32));
13474 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
13475 MachinePointerInfo(TrmpAddr, 1),
13478 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
13479 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13480 DAG.getConstant(5, MVT::i32));
13481 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
13482 MachinePointerInfo(TrmpAddr, 5),
13485 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13486 DAG.getConstant(6, MVT::i32));
13487 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
13488 MachinePointerInfo(TrmpAddr, 6),
13491 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
13495 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
13496 SelectionDAG &DAG) const {
13498 The rounding mode is in bits 11:10 of FPSR, and has the following
13500 00 Round to nearest
13505 FLT_ROUNDS, on the other hand, expects the following:
13512 To perform the conversion, we do:
13513 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
13516 MachineFunction &MF = DAG.getMachineFunction();
13517 const TargetMachine &TM = MF.getTarget();
13518 const TargetFrameLowering &TFI = *TM.getFrameLowering();
13519 unsigned StackAlignment = TFI.getStackAlignment();
13520 MVT VT = Op.getSimpleValueType();
13523 // Save FP Control Word to stack slot
13524 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
13525 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
13527 MachineMemOperand *MMO =
13528 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
13529 MachineMemOperand::MOStore, 2, 2);
13531 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
13532 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
13533 DAG.getVTList(MVT::Other),
13534 Ops, MVT::i16, MMO);
13536 // Load FP Control Word from stack slot
13537 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
13538 MachinePointerInfo(), false, false, false, 0);
13540 // Transform as necessary
13542 DAG.getNode(ISD::SRL, DL, MVT::i16,
13543 DAG.getNode(ISD::AND, DL, MVT::i16,
13544 CWD, DAG.getConstant(0x800, MVT::i16)),
13545 DAG.getConstant(11, MVT::i8));
13547 DAG.getNode(ISD::SRL, DL, MVT::i16,
13548 DAG.getNode(ISD::AND, DL, MVT::i16,
13549 CWD, DAG.getConstant(0x400, MVT::i16)),
13550 DAG.getConstant(9, MVT::i8));
13553 DAG.getNode(ISD::AND, DL, MVT::i16,
13554 DAG.getNode(ISD::ADD, DL, MVT::i16,
13555 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
13556 DAG.getConstant(1, MVT::i16)),
13557 DAG.getConstant(3, MVT::i16));
13559 return DAG.getNode((VT.getSizeInBits() < 16 ?
13560 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
13563 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
13564 MVT VT = Op.getSimpleValueType();
13566 unsigned NumBits = VT.getSizeInBits();
13569 Op = Op.getOperand(0);
13570 if (VT == MVT::i8) {
13571 // Zero extend to i32 since there is not an i8 bsr.
13573 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13576 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
13577 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13578 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13580 // If src is zero (i.e. bsr sets ZF), returns NumBits.
13583 DAG.getConstant(NumBits+NumBits-1, OpVT),
13584 DAG.getConstant(X86::COND_E, MVT::i8),
13587 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
13589 // Finally xor with NumBits-1.
13590 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13593 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13597 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
13598 MVT VT = Op.getSimpleValueType();
13600 unsigned NumBits = VT.getSizeInBits();
13603 Op = Op.getOperand(0);
13604 if (VT == MVT::i8) {
13605 // Zero extend to i32 since there is not an i8 bsr.
13607 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13610 // Issue a bsr (scan bits in reverse).
13611 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13612 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13614 // And xor with NumBits-1.
13615 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13618 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13622 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
13623 MVT VT = Op.getSimpleValueType();
13624 unsigned NumBits = VT.getSizeInBits();
13626 Op = Op.getOperand(0);
13628 // Issue a bsf (scan bits forward) which also sets EFLAGS.
13629 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13630 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
13632 // If src is zero (i.e. bsf sets ZF), returns NumBits.
13635 DAG.getConstant(NumBits, VT),
13636 DAG.getConstant(X86::COND_E, MVT::i8),
13639 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
13642 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
13643 // ones, and then concatenate the result back.
13644 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
13645 MVT VT = Op.getSimpleValueType();
13647 assert(VT.is256BitVector() && VT.isInteger() &&
13648 "Unsupported value type for operation");
13650 unsigned NumElems = VT.getVectorNumElements();
13653 // Extract the LHS vectors
13654 SDValue LHS = Op.getOperand(0);
13655 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13656 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13658 // Extract the RHS vectors
13659 SDValue RHS = Op.getOperand(1);
13660 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13661 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13663 MVT EltVT = VT.getVectorElementType();
13664 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13666 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13667 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
13668 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
13671 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
13672 assert(Op.getSimpleValueType().is256BitVector() &&
13673 Op.getSimpleValueType().isInteger() &&
13674 "Only handle AVX 256-bit vector integer operation");
13675 return Lower256IntArith(Op, DAG);
13678 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
13679 assert(Op.getSimpleValueType().is256BitVector() &&
13680 Op.getSimpleValueType().isInteger() &&
13681 "Only handle AVX 256-bit vector integer operation");
13682 return Lower256IntArith(Op, DAG);
13685 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
13686 SelectionDAG &DAG) {
13688 MVT VT = Op.getSimpleValueType();
13690 // Decompose 256-bit ops into smaller 128-bit ops.
13691 if (VT.is256BitVector() && !Subtarget->hasInt256())
13692 return Lower256IntArith(Op, DAG);
13694 SDValue A = Op.getOperand(0);
13695 SDValue B = Op.getOperand(1);
13697 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
13698 if (VT == MVT::v4i32) {
13699 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
13700 "Should not custom lower when pmuldq is available!");
13702 // Extract the odd parts.
13703 static const int UnpackMask[] = { 1, -1, 3, -1 };
13704 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
13705 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
13707 // Multiply the even parts.
13708 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
13709 // Now multiply odd parts.
13710 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
13712 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
13713 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
13715 // Merge the two vectors back together with a shuffle. This expands into 2
13717 static const int ShufMask[] = { 0, 4, 2, 6 };
13718 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
13721 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
13722 "Only know how to lower V2I64/V4I64/V8I64 multiply");
13724 // Ahi = psrlqi(a, 32);
13725 // Bhi = psrlqi(b, 32);
13727 // AloBlo = pmuludq(a, b);
13728 // AloBhi = pmuludq(a, Bhi);
13729 // AhiBlo = pmuludq(Ahi, b);
13731 // AloBhi = psllqi(AloBhi, 32);
13732 // AhiBlo = psllqi(AhiBlo, 32);
13733 // return AloBlo + AloBhi + AhiBlo;
13735 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
13736 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
13738 // Bit cast to 32-bit vectors for MULUDQ
13739 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
13740 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
13741 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
13742 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
13743 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
13744 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
13746 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
13747 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
13748 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
13750 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
13751 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
13753 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
13754 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
13757 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
13758 assert(Subtarget->isTargetWin64() && "Unexpected target");
13759 EVT VT = Op.getValueType();
13760 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
13761 "Unexpected return type for lowering");
13765 switch (Op->getOpcode()) {
13766 default: llvm_unreachable("Unexpected request for libcall!");
13767 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
13768 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
13769 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
13770 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
13771 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
13772 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
13776 SDValue InChain = DAG.getEntryNode();
13778 TargetLowering::ArgListTy Args;
13779 TargetLowering::ArgListEntry Entry;
13780 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
13781 EVT ArgVT = Op->getOperand(i).getValueType();
13782 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
13783 "Unexpected argument type for lowering");
13784 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
13785 Entry.Node = StackPtr;
13786 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
13788 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13789 Entry.Ty = PointerType::get(ArgTy,0);
13790 Entry.isSExt = false;
13791 Entry.isZExt = false;
13792 Args.push_back(Entry);
13795 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
13798 TargetLowering::CallLoweringInfo CLI(DAG);
13799 CLI.setDebugLoc(dl).setChain(InChain)
13800 .setCallee(getLibcallCallingConv(LC),
13801 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
13803 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
13805 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
13806 return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
13809 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
13810 SelectionDAG &DAG) {
13811 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
13812 EVT VT = Op0.getValueType();
13815 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
13816 (VT == MVT::v8i32 && Subtarget->hasInt256()));
13818 // Get the high parts.
13819 const int Mask[] = {1, 2, 3, 4, 5, 6, 7, 8};
13820 SDValue Hi0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
13821 SDValue Hi1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
13823 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
13825 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
13826 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
13828 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
13829 SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
13830 DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
13831 SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
13832 DAG.getNode(Opcode, dl, MulVT, Hi0, Hi1));
13834 // Shuffle it back into the right order.
13835 const int HighMask[] = {1, 5, 3, 7, 9, 13, 11, 15};
13836 SDValue Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
13837 const int LowMask[] = {0, 4, 2, 6, 8, 12, 10, 14};
13838 SDValue Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
13840 // If we have a signed multiply but no PMULDQ fix up the high parts of a
13841 // unsigned multiply.
13842 if (IsSigned && !Subtarget->hasSSE41()) {
13844 DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
13845 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
13846 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
13847 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
13848 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
13850 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
13851 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
13854 return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Highs, Lows);
13857 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
13858 const X86Subtarget *Subtarget) {
13859 MVT VT = Op.getSimpleValueType();
13861 SDValue R = Op.getOperand(0);
13862 SDValue Amt = Op.getOperand(1);
13864 // Optimize shl/srl/sra with constant shift amount.
13865 if (isSplatVector(Amt.getNode())) {
13866 SDValue SclrAmt = Amt->getOperand(0);
13867 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
13868 uint64_t ShiftAmt = C->getZExtValue();
13870 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
13871 (Subtarget->hasInt256() &&
13872 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13873 (Subtarget->hasAVX512() &&
13874 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13875 if (Op.getOpcode() == ISD::SHL)
13876 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13878 if (Op.getOpcode() == ISD::SRL)
13879 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13881 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
13882 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13886 if (VT == MVT::v16i8) {
13887 if (Op.getOpcode() == ISD::SHL) {
13888 // Make a large shift.
13889 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13890 MVT::v8i16, R, ShiftAmt,
13892 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13893 // Zero out the rightmost bits.
13894 SmallVector<SDValue, 16> V(16,
13895 DAG.getConstant(uint8_t(-1U << ShiftAmt),
13897 return DAG.getNode(ISD::AND, dl, VT, SHL,
13898 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13900 if (Op.getOpcode() == ISD::SRL) {
13901 // Make a large shift.
13902 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13903 MVT::v8i16, R, ShiftAmt,
13905 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13906 // Zero out the leftmost bits.
13907 SmallVector<SDValue, 16> V(16,
13908 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13910 return DAG.getNode(ISD::AND, dl, VT, SRL,
13911 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13913 if (Op.getOpcode() == ISD::SRA) {
13914 if (ShiftAmt == 7) {
13915 // R s>> 7 === R s< 0
13916 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13917 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13920 // R s>> a === ((R u>> a) ^ m) - m
13921 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13922 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
13924 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13925 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13926 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13929 llvm_unreachable("Unknown shift opcode.");
13932 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
13933 if (Op.getOpcode() == ISD::SHL) {
13934 // Make a large shift.
13935 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13936 MVT::v16i16, R, ShiftAmt,
13938 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13939 // Zero out the rightmost bits.
13940 SmallVector<SDValue, 32> V(32,
13941 DAG.getConstant(uint8_t(-1U << ShiftAmt),
13943 return DAG.getNode(ISD::AND, dl, VT, SHL,
13944 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13946 if (Op.getOpcode() == ISD::SRL) {
13947 // Make a large shift.
13948 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13949 MVT::v16i16, R, ShiftAmt,
13951 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13952 // Zero out the leftmost bits.
13953 SmallVector<SDValue, 32> V(32,
13954 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13956 return DAG.getNode(ISD::AND, dl, VT, SRL,
13957 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13959 if (Op.getOpcode() == ISD::SRA) {
13960 if (ShiftAmt == 7) {
13961 // R s>> 7 === R s< 0
13962 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13963 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13966 // R s>> a === ((R u>> a) ^ m) - m
13967 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13968 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
13970 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13971 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13972 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13975 llvm_unreachable("Unknown shift opcode.");
13980 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13981 if (!Subtarget->is64Bit() &&
13982 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
13983 Amt.getOpcode() == ISD::BITCAST &&
13984 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13985 Amt = Amt.getOperand(0);
13986 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13987 VT.getVectorNumElements();
13988 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
13989 uint64_t ShiftAmt = 0;
13990 for (unsigned i = 0; i != Ratio; ++i) {
13991 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
13995 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
13997 // Check remaining shift amounts.
13998 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13999 uint64_t ShAmt = 0;
14000 for (unsigned j = 0; j != Ratio; ++j) {
14001 ConstantSDNode *C =
14002 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
14006 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
14008 if (ShAmt != ShiftAmt)
14011 switch (Op.getOpcode()) {
14013 llvm_unreachable("Unknown shift opcode!");
14015 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
14018 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
14021 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
14029 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
14030 const X86Subtarget* Subtarget) {
14031 MVT VT = Op.getSimpleValueType();
14033 SDValue R = Op.getOperand(0);
14034 SDValue Amt = Op.getOperand(1);
14036 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
14037 VT == MVT::v4i32 || VT == MVT::v8i16 ||
14038 (Subtarget->hasInt256() &&
14039 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
14040 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
14041 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
14043 EVT EltVT = VT.getVectorElementType();
14045 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
14046 unsigned NumElts = VT.getVectorNumElements();
14048 for (i = 0; i != NumElts; ++i) {
14049 if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
14053 for (j = i; j != NumElts; ++j) {
14054 SDValue Arg = Amt.getOperand(j);
14055 if (Arg.getOpcode() == ISD::UNDEF) continue;
14056 if (Arg != Amt.getOperand(i))
14059 if (i != NumElts && j == NumElts)
14060 BaseShAmt = Amt.getOperand(i);
14062 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
14063 Amt = Amt.getOperand(0);
14064 if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
14065 cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
14066 SDValue InVec = Amt.getOperand(0);
14067 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
14068 unsigned NumElts = InVec.getValueType().getVectorNumElements();
14070 for (; i != NumElts; ++i) {
14071 SDValue Arg = InVec.getOperand(i);
14072 if (Arg.getOpcode() == ISD::UNDEF) continue;
14076 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
14077 if (ConstantSDNode *C =
14078 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
14079 unsigned SplatIdx =
14080 cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
14081 if (C->getZExtValue() == SplatIdx)
14082 BaseShAmt = InVec.getOperand(1);
14085 if (!BaseShAmt.getNode())
14086 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
14087 DAG.getIntPtrConstant(0));
14091 if (BaseShAmt.getNode()) {
14092 if (EltVT.bitsGT(MVT::i32))
14093 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
14094 else if (EltVT.bitsLT(MVT::i32))
14095 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
14097 switch (Op.getOpcode()) {
14099 llvm_unreachable("Unknown shift opcode!");
14101 switch (VT.SimpleTy) {
14102 default: return SDValue();
14111 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
14114 switch (VT.SimpleTy) {
14115 default: return SDValue();
14122 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
14125 switch (VT.SimpleTy) {
14126 default: return SDValue();
14135 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
14141 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
14142 if (!Subtarget->is64Bit() &&
14143 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
14144 (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
14145 Amt.getOpcode() == ISD::BITCAST &&
14146 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
14147 Amt = Amt.getOperand(0);
14148 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
14149 VT.getVectorNumElements();
14150 std::vector<SDValue> Vals(Ratio);
14151 for (unsigned i = 0; i != Ratio; ++i)
14152 Vals[i] = Amt.getOperand(i);
14153 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
14154 for (unsigned j = 0; j != Ratio; ++j)
14155 if (Vals[j] != Amt.getOperand(i + j))
14158 switch (Op.getOpcode()) {
14160 llvm_unreachable("Unknown shift opcode!");
14162 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
14164 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
14166 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
14173 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
14174 SelectionDAG &DAG) {
14176 MVT VT = Op.getSimpleValueType();
14178 SDValue R = Op.getOperand(0);
14179 SDValue Amt = Op.getOperand(1);
14182 if (!Subtarget->hasSSE2())
14185 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
14189 V = LowerScalarVariableShift(Op, DAG, Subtarget);
14193 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
14195 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
14196 if (Subtarget->hasInt256()) {
14197 if (Op.getOpcode() == ISD::SRL &&
14198 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
14199 VT == MVT::v4i64 || VT == MVT::v8i32))
14201 if (Op.getOpcode() == ISD::SHL &&
14202 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
14203 VT == MVT::v4i64 || VT == MVT::v8i32))
14205 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
14209 // If possible, lower this packed shift into a vector multiply instead of
14210 // expanding it into a sequence of scalar shifts.
14211 // Do this only if the vector shift count is a constant build_vector.
14212 if (Op.getOpcode() == ISD::SHL &&
14213 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
14214 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
14215 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
14216 SmallVector<SDValue, 8> Elts;
14217 EVT SVT = VT.getScalarType();
14218 unsigned SVTBits = SVT.getSizeInBits();
14219 const APInt &One = APInt(SVTBits, 1);
14220 unsigned NumElems = VT.getVectorNumElements();
14222 for (unsigned i=0; i !=NumElems; ++i) {
14223 SDValue Op = Amt->getOperand(i);
14224 if (Op->getOpcode() == ISD::UNDEF) {
14225 Elts.push_back(Op);
14229 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
14230 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
14231 uint64_t ShAmt = C.getZExtValue();
14232 if (ShAmt >= SVTBits) {
14233 Elts.push_back(DAG.getUNDEF(SVT));
14236 Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
14238 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14239 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
14242 // Lower SHL with variable shift amount.
14243 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
14244 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
14246 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
14247 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
14248 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
14249 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
14252 // If possible, lower this shift as a sequence of two shifts by
14253 // constant plus a MOVSS/MOVSD instead of scalarizing it.
14255 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
14257 // Could be rewritten as:
14258 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
14260 // The advantage is that the two shifts from the example would be
14261 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
14262 // the vector shift into four scalar shifts plus four pairs of vector
14264 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
14265 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
14266 unsigned TargetOpcode = X86ISD::MOVSS;
14267 bool CanBeSimplified;
14268 // The splat value for the first packed shift (the 'X' from the example).
14269 SDValue Amt1 = Amt->getOperand(0);
14270 // The splat value for the second packed shift (the 'Y' from the example).
14271 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
14272 Amt->getOperand(2);
14274 // See if it is possible to replace this node with a sequence of
14275 // two shifts followed by a MOVSS/MOVSD
14276 if (VT == MVT::v4i32) {
14277 // Check if it is legal to use a MOVSS.
14278 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
14279 Amt2 == Amt->getOperand(3);
14280 if (!CanBeSimplified) {
14281 // Otherwise, check if we can still simplify this node using a MOVSD.
14282 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
14283 Amt->getOperand(2) == Amt->getOperand(3);
14284 TargetOpcode = X86ISD::MOVSD;
14285 Amt2 = Amt->getOperand(2);
14288 // Do similar checks for the case where the machine value type
14290 CanBeSimplified = Amt1 == Amt->getOperand(1);
14291 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
14292 CanBeSimplified = Amt2 == Amt->getOperand(i);
14294 if (!CanBeSimplified) {
14295 TargetOpcode = X86ISD::MOVSD;
14296 CanBeSimplified = true;
14297 Amt2 = Amt->getOperand(4);
14298 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
14299 CanBeSimplified = Amt1 == Amt->getOperand(i);
14300 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
14301 CanBeSimplified = Amt2 == Amt->getOperand(j);
14305 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
14306 isa<ConstantSDNode>(Amt2)) {
14307 // Replace this node with two shifts followed by a MOVSS/MOVSD.
14308 EVT CastVT = MVT::v4i32;
14310 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
14311 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
14313 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
14314 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
14315 if (TargetOpcode == X86ISD::MOVSD)
14316 CastVT = MVT::v2i64;
14317 SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
14318 SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
14319 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
14321 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
14325 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
14326 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
14329 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
14330 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
14332 // Turn 'a' into a mask suitable for VSELECT
14333 SDValue VSelM = DAG.getConstant(0x80, VT);
14334 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
14335 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
14337 SDValue CM1 = DAG.getConstant(0x0f, VT);
14338 SDValue CM2 = DAG.getConstant(0x3f, VT);
14340 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
14341 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
14342 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
14343 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
14344 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
14347 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
14348 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
14349 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
14351 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
14352 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
14353 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
14354 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
14355 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
14358 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
14359 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
14360 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
14362 // return VSELECT(r, r+r, a);
14363 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
14364 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
14368 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
14369 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
14370 // solution better.
14371 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
14372 MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
14374 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
14375 R = DAG.getNode(ExtOpc, dl, NewVT, R);
14376 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
14377 return DAG.getNode(ISD::TRUNCATE, dl, VT,
14378 DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
14381 // Decompose 256-bit shifts into smaller 128-bit shifts.
14382 if (VT.is256BitVector()) {
14383 unsigned NumElems = VT.getVectorNumElements();
14384 MVT EltVT = VT.getVectorElementType();
14385 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14387 // Extract the two vectors
14388 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
14389 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
14391 // Recreate the shift amount vectors
14392 SDValue Amt1, Amt2;
14393 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
14394 // Constant shift amount
14395 SmallVector<SDValue, 4> Amt1Csts;
14396 SmallVector<SDValue, 4> Amt2Csts;
14397 for (unsigned i = 0; i != NumElems/2; ++i)
14398 Amt1Csts.push_back(Amt->getOperand(i));
14399 for (unsigned i = NumElems/2; i != NumElems; ++i)
14400 Amt2Csts.push_back(Amt->getOperand(i));
14402 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
14403 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
14405 // Variable shift amount
14406 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
14407 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
14410 // Issue new vector shifts for the smaller types
14411 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
14412 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
14414 // Concatenate the result back
14415 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
14421 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
14422 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
14423 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
14424 // looks for this combo and may remove the "setcc" instruction if the "setcc"
14425 // has only one use.
14426 SDNode *N = Op.getNode();
14427 SDValue LHS = N->getOperand(0);
14428 SDValue RHS = N->getOperand(1);
14429 unsigned BaseOp = 0;
14432 switch (Op.getOpcode()) {
14433 default: llvm_unreachable("Unknown ovf instruction!");
14435 // A subtract of one will be selected as a INC. Note that INC doesn't
14436 // set CF, so we can't do this for UADDO.
14437 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14439 BaseOp = X86ISD::INC;
14440 Cond = X86::COND_O;
14443 BaseOp = X86ISD::ADD;
14444 Cond = X86::COND_O;
14447 BaseOp = X86ISD::ADD;
14448 Cond = X86::COND_B;
14451 // A subtract of one will be selected as a DEC. Note that DEC doesn't
14452 // set CF, so we can't do this for USUBO.
14453 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14455 BaseOp = X86ISD::DEC;
14456 Cond = X86::COND_O;
14459 BaseOp = X86ISD::SUB;
14460 Cond = X86::COND_O;
14463 BaseOp = X86ISD::SUB;
14464 Cond = X86::COND_B;
14467 BaseOp = X86ISD::SMUL;
14468 Cond = X86::COND_O;
14470 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
14471 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
14473 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
14476 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14477 DAG.getConstant(X86::COND_O, MVT::i32),
14478 SDValue(Sum.getNode(), 2));
14480 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
14484 // Also sets EFLAGS.
14485 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
14486 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
14489 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
14490 DAG.getConstant(Cond, MVT::i32),
14491 SDValue(Sum.getNode(), 1));
14493 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
14496 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
14497 SelectionDAG &DAG) const {
14499 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
14500 MVT VT = Op.getSimpleValueType();
14502 if (!Subtarget->hasSSE2() || !VT.isVector())
14505 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
14506 ExtraVT.getScalarType().getSizeInBits();
14508 switch (VT.SimpleTy) {
14509 default: return SDValue();
14512 if (!Subtarget->hasFp256())
14514 if (!Subtarget->hasInt256()) {
14515 // needs to be split
14516 unsigned NumElems = VT.getVectorNumElements();
14518 // Extract the LHS vectors
14519 SDValue LHS = Op.getOperand(0);
14520 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14521 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14523 MVT EltVT = VT.getVectorElementType();
14524 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14526 EVT ExtraEltVT = ExtraVT.getVectorElementType();
14527 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
14528 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
14530 SDValue Extra = DAG.getValueType(ExtraVT);
14532 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
14533 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
14535 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
14540 SDValue Op0 = Op.getOperand(0);
14541 SDValue Op00 = Op0.getOperand(0);
14543 // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
14544 if (Op0.getOpcode() == ISD::BITCAST &&
14545 Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
14546 // (sext (vzext x)) -> (vsext x)
14547 Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
14548 if (Tmp1.getNode()) {
14549 EVT ExtraEltVT = ExtraVT.getVectorElementType();
14550 // This folding is only valid when the in-reg type is a vector of i8,
14552 if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
14553 ExtraEltVT == MVT::i32) {
14554 SDValue Tmp1Op0 = Tmp1.getOperand(0);
14555 assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
14556 "This optimization is invalid without a VZEXT.");
14557 return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
14563 // If the above didn't work, then just use Shift-Left + Shift-Right.
14564 Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
14566 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
14572 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
14573 SelectionDAG &DAG) {
14575 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
14576 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
14577 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
14578 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
14580 // The only fence that needs an instruction is a sequentially-consistent
14581 // cross-thread fence.
14582 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
14583 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
14584 // no-sse2). There isn't any reason to disable it if the target processor
14586 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
14587 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
14589 SDValue Chain = Op.getOperand(0);
14590 SDValue Zero = DAG.getConstant(0, MVT::i32);
14592 DAG.getRegister(X86::ESP, MVT::i32), // Base
14593 DAG.getTargetConstant(1, MVT::i8), // Scale
14594 DAG.getRegister(0, MVT::i32), // Index
14595 DAG.getTargetConstant(0, MVT::i32), // Disp
14596 DAG.getRegister(0, MVT::i32), // Segment.
14600 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
14601 return SDValue(Res, 0);
14604 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
14605 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
14608 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
14609 SelectionDAG &DAG) {
14610 MVT T = Op.getSimpleValueType();
14614 switch(T.SimpleTy) {
14615 default: llvm_unreachable("Invalid value type!");
14616 case MVT::i8: Reg = X86::AL; size = 1; break;
14617 case MVT::i16: Reg = X86::AX; size = 2; break;
14618 case MVT::i32: Reg = X86::EAX; size = 4; break;
14620 assert(Subtarget->is64Bit() && "Node not type legal!");
14621 Reg = X86::RAX; size = 8;
14624 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
14625 Op.getOperand(2), SDValue());
14626 SDValue Ops[] = { cpIn.getValue(0),
14629 DAG.getTargetConstant(size, MVT::i8),
14630 cpIn.getValue(1) };
14631 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14632 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
14633 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
14637 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
14638 SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
14639 MVT::i32, cpOut.getValue(2));
14640 SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
14641 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
14643 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
14644 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
14645 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
14649 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
14650 SelectionDAG &DAG) {
14651 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
14652 MVT DstVT = Op.getSimpleValueType();
14654 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
14655 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14656 if (DstVT != MVT::f64)
14657 // This conversion needs to be expanded.
14660 SDValue InVec = Op->getOperand(0);
14662 unsigned NumElts = SrcVT.getVectorNumElements();
14663 EVT SVT = SrcVT.getVectorElementType();
14665 // Widen the vector in input in the case of MVT::v2i32.
14666 // Example: from MVT::v2i32 to MVT::v4i32.
14667 SmallVector<SDValue, 16> Elts;
14668 for (unsigned i = 0, e = NumElts; i != e; ++i)
14669 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
14670 DAG.getIntPtrConstant(i)));
14672 // Explicitly mark the extra elements as Undef.
14673 SDValue Undef = DAG.getUNDEF(SVT);
14674 for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
14675 Elts.push_back(Undef);
14677 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
14678 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
14679 SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
14680 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
14681 DAG.getIntPtrConstant(0));
14684 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
14685 Subtarget->hasMMX() && "Unexpected custom BITCAST");
14686 assert((DstVT == MVT::i64 ||
14687 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
14688 "Unexpected custom BITCAST");
14689 // i64 <=> MMX conversions are Legal.
14690 if (SrcVT==MVT::i64 && DstVT.isVector())
14692 if (DstVT==MVT::i64 && SrcVT.isVector())
14694 // MMX <=> MMX conversions are Legal.
14695 if (SrcVT.isVector() && DstVT.isVector())
14697 // All other conversions need to be expanded.
14701 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
14702 SDNode *Node = Op.getNode();
14704 EVT T = Node->getValueType(0);
14705 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
14706 DAG.getConstant(0, T), Node->getOperand(2));
14707 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
14708 cast<AtomicSDNode>(Node)->getMemoryVT(),
14709 Node->getOperand(0),
14710 Node->getOperand(1), negOp,
14711 cast<AtomicSDNode>(Node)->getMemOperand(),
14712 cast<AtomicSDNode>(Node)->getOrdering(),
14713 cast<AtomicSDNode>(Node)->getSynchScope());
14716 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
14717 SDNode *Node = Op.getNode();
14719 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14721 // Convert seq_cst store -> xchg
14722 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
14723 // FIXME: On 32-bit, store -> fist or movq would be more efficient
14724 // (The only way to get a 16-byte store is cmpxchg16b)
14725 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
14726 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
14727 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14728 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
14729 cast<AtomicSDNode>(Node)->getMemoryVT(),
14730 Node->getOperand(0),
14731 Node->getOperand(1), Node->getOperand(2),
14732 cast<AtomicSDNode>(Node)->getMemOperand(),
14733 cast<AtomicSDNode>(Node)->getOrdering(),
14734 cast<AtomicSDNode>(Node)->getSynchScope());
14735 return Swap.getValue(1);
14737 // Other atomic stores have a simple pattern.
14741 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
14742 EVT VT = Op.getNode()->getSimpleValueType(0);
14744 // Let legalize expand this if it isn't a legal type yet.
14745 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14748 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14751 bool ExtraOp = false;
14752 switch (Op.getOpcode()) {
14753 default: llvm_unreachable("Invalid code");
14754 case ISD::ADDC: Opc = X86ISD::ADD; break;
14755 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
14756 case ISD::SUBC: Opc = X86ISD::SUB; break;
14757 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
14761 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14763 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14764 Op.getOperand(1), Op.getOperand(2));
14767 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
14768 SelectionDAG &DAG) {
14769 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
14771 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
14772 // which returns the values as { float, float } (in XMM0) or
14773 // { double, double } (which is returned in XMM0, XMM1).
14775 SDValue Arg = Op.getOperand(0);
14776 EVT ArgVT = Arg.getValueType();
14777 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14779 TargetLowering::ArgListTy Args;
14780 TargetLowering::ArgListEntry Entry;
14784 Entry.isSExt = false;
14785 Entry.isZExt = false;
14786 Args.push_back(Entry);
14788 bool isF64 = ArgVT == MVT::f64;
14789 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
14790 // the small struct {f32, f32} is returned in (eax, edx). For f64,
14791 // the results are returned via SRet in memory.
14792 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
14793 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14794 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
14796 Type *RetTy = isF64
14797 ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
14798 : (Type*)VectorType::get(ArgTy, 4);
14800 TargetLowering::CallLoweringInfo CLI(DAG);
14801 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
14802 .setCallee(CallingConv::C, RetTy, Callee, &Args, 0);
14804 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
14807 // Returned in xmm0 and xmm1.
14808 return CallResult.first;
14810 // Returned in bits 0:31 and 32:64 xmm0.
14811 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14812 CallResult.first, DAG.getIntPtrConstant(0));
14813 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14814 CallResult.first, DAG.getIntPtrConstant(1));
14815 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
14816 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
14819 /// LowerOperation - Provide custom lowering hooks for some operations.
14821 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
14822 switch (Op.getOpcode()) {
14823 default: llvm_unreachable("Should not custom lower this!");
14824 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
14825 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
14826 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
14827 return LowerCMP_SWAP(Op, Subtarget, DAG);
14828 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
14829 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
14830 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
14831 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
14832 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
14833 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
14834 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
14835 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
14836 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
14837 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
14838 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
14839 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
14840 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
14841 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
14842 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
14843 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
14844 case ISD::SHL_PARTS:
14845 case ISD::SRA_PARTS:
14846 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
14847 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
14848 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
14849 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
14850 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
14851 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
14852 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
14853 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
14854 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
14855 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
14856 case ISD::FABS: return LowerFABS(Op, DAG);
14857 case ISD::FNEG: return LowerFNEG(Op, DAG);
14858 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
14859 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
14860 case ISD::SETCC: return LowerSETCC(Op, DAG);
14861 case ISD::SELECT: return LowerSELECT(Op, DAG);
14862 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
14863 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
14864 case ISD::VASTART: return LowerVASTART(Op, DAG);
14865 case ISD::VAARG: return LowerVAARG(Op, DAG);
14866 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
14867 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
14868 case ISD::INTRINSIC_VOID:
14869 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
14870 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
14871 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
14872 case ISD::FRAME_TO_ARGS_OFFSET:
14873 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
14874 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
14875 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
14876 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
14877 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
14878 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
14879 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
14880 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
14881 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
14882 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
14883 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
14884 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
14885 case ISD::UMUL_LOHI:
14886 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
14889 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
14895 case ISD::UMULO: return LowerXALUO(Op, DAG);
14896 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
14897 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
14901 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
14902 case ISD::ADD: return LowerADD(Op, DAG);
14903 case ISD::SUB: return LowerSUB(Op, DAG);
14904 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
14908 static void ReplaceATOMIC_LOAD(SDNode *Node,
14909 SmallVectorImpl<SDValue> &Results,
14910 SelectionDAG &DAG) {
14912 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14914 // Convert wide load -> cmpxchg8b/cmpxchg16b
14915 // FIXME: On 32-bit, load -> fild or movq would be more efficient
14916 // (The only way to get a 16-byte load is cmpxchg16b)
14917 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
14918 SDValue Zero = DAG.getConstant(0, VT);
14919 SDVTList VTs = DAG.getVTList(VT, MVT::i1, MVT::Other);
14921 DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, VT, VTs,
14922 Node->getOperand(0), Node->getOperand(1), Zero, Zero,
14923 cast<AtomicSDNode>(Node)->getMemOperand(),
14924 cast<AtomicSDNode>(Node)->getOrdering(),
14925 cast<AtomicSDNode>(Node)->getOrdering(),
14926 cast<AtomicSDNode>(Node)->getSynchScope());
14927 Results.push_back(Swap.getValue(0));
14928 Results.push_back(Swap.getValue(2));
14932 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
14933 SelectionDAG &DAG, unsigned NewOp) {
14935 assert (Node->getValueType(0) == MVT::i64 &&
14936 "Only know how to expand i64 atomics");
14938 SDValue Chain = Node->getOperand(0);
14939 SDValue In1 = Node->getOperand(1);
14940 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14941 Node->getOperand(2), DAG.getIntPtrConstant(0));
14942 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14943 Node->getOperand(2), DAG.getIntPtrConstant(1));
14944 SDValue Ops[] = { Chain, In1, In2L, In2H };
14945 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
14947 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, MVT::i64,
14948 cast<MemSDNode>(Node)->getMemOperand());
14949 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
14950 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF));
14951 Results.push_back(Result.getValue(2));
14954 /// ReplaceNodeResults - Replace a node with an illegal result type
14955 /// with a new node built out of custom code.
14956 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
14957 SmallVectorImpl<SDValue>&Results,
14958 SelectionDAG &DAG) const {
14960 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14961 switch (N->getOpcode()) {
14963 llvm_unreachable("Do not know how to custom type legalize this operation!");
14964 case ISD::SIGN_EXTEND_INREG:
14969 // We don't want to expand or promote these.
14976 case ISD::UDIVREM: {
14977 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
14978 Results.push_back(V);
14981 case ISD::FP_TO_SINT:
14982 case ISD::FP_TO_UINT: {
14983 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
14985 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
14988 std::pair<SDValue,SDValue> Vals =
14989 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
14990 SDValue FIST = Vals.first, StackSlot = Vals.second;
14991 if (FIST.getNode()) {
14992 EVT VT = N->getValueType(0);
14993 // Return a load from the stack slot.
14994 if (StackSlot.getNode())
14995 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
14996 MachinePointerInfo(),
14997 false, false, false, 0));
14999 Results.push_back(FIST);
15003 case ISD::UINT_TO_FP: {
15004 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
15005 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
15006 N->getValueType(0) != MVT::v2f32)
15008 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
15010 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
15012 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
15013 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
15014 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
15015 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
15016 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
15017 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
15020 case ISD::FP_ROUND: {
15021 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
15023 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
15024 Results.push_back(V);
15027 case ISD::INTRINSIC_W_CHAIN: {
15028 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
15030 default : llvm_unreachable("Do not know how to custom type "
15031 "legalize this intrinsic operation!");
15032 case Intrinsic::x86_rdtsc:
15033 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
15035 case Intrinsic::x86_rdtscp:
15036 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
15040 case ISD::READCYCLECOUNTER: {
15041 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
15044 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
15045 EVT T = N->getValueType(0);
15046 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
15047 bool Regs64bit = T == MVT::i128;
15048 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
15049 SDValue cpInL, cpInH;
15050 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
15051 DAG.getConstant(0, HalfT));
15052 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
15053 DAG.getConstant(1, HalfT));
15054 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
15055 Regs64bit ? X86::RAX : X86::EAX,
15057 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
15058 Regs64bit ? X86::RDX : X86::EDX,
15059 cpInH, cpInL.getValue(1));
15060 SDValue swapInL, swapInH;
15061 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
15062 DAG.getConstant(0, HalfT));
15063 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
15064 DAG.getConstant(1, HalfT));
15065 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
15066 Regs64bit ? X86::RBX : X86::EBX,
15067 swapInL, cpInH.getValue(1));
15068 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
15069 Regs64bit ? X86::RCX : X86::ECX,
15070 swapInH, swapInL.getValue(1));
15071 SDValue Ops[] = { swapInH.getValue(0),
15073 swapInH.getValue(1) };
15074 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15075 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
15076 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
15077 X86ISD::LCMPXCHG8_DAG;
15078 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
15079 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
15080 Regs64bit ? X86::RAX : X86::EAX,
15081 HalfT, Result.getValue(1));
15082 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
15083 Regs64bit ? X86::RDX : X86::EDX,
15084 HalfT, cpOutL.getValue(2));
15085 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
15087 SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
15088 MVT::i32, cpOutH.getValue(2));
15090 DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15091 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
15092 Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
15094 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
15095 Results.push_back(Success);
15096 Results.push_back(EFLAGS.getValue(1));
15099 case ISD::ATOMIC_LOAD_ADD:
15100 case ISD::ATOMIC_LOAD_AND:
15101 case ISD::ATOMIC_LOAD_NAND:
15102 case ISD::ATOMIC_LOAD_OR:
15103 case ISD::ATOMIC_LOAD_SUB:
15104 case ISD::ATOMIC_LOAD_XOR:
15105 case ISD::ATOMIC_LOAD_MAX:
15106 case ISD::ATOMIC_LOAD_MIN:
15107 case ISD::ATOMIC_LOAD_UMAX:
15108 case ISD::ATOMIC_LOAD_UMIN:
15109 case ISD::ATOMIC_SWAP: {
15111 switch (N->getOpcode()) {
15112 default: llvm_unreachable("Unexpected opcode");
15113 case ISD::ATOMIC_LOAD_ADD:
15114 Opc = X86ISD::ATOMADD64_DAG;
15116 case ISD::ATOMIC_LOAD_AND:
15117 Opc = X86ISD::ATOMAND64_DAG;
15119 case ISD::ATOMIC_LOAD_NAND:
15120 Opc = X86ISD::ATOMNAND64_DAG;
15122 case ISD::ATOMIC_LOAD_OR:
15123 Opc = X86ISD::ATOMOR64_DAG;
15125 case ISD::ATOMIC_LOAD_SUB:
15126 Opc = X86ISD::ATOMSUB64_DAG;
15128 case ISD::ATOMIC_LOAD_XOR:
15129 Opc = X86ISD::ATOMXOR64_DAG;
15131 case ISD::ATOMIC_LOAD_MAX:
15132 Opc = X86ISD::ATOMMAX64_DAG;
15134 case ISD::ATOMIC_LOAD_MIN:
15135 Opc = X86ISD::ATOMMIN64_DAG;
15137 case ISD::ATOMIC_LOAD_UMAX:
15138 Opc = X86ISD::ATOMUMAX64_DAG;
15140 case ISD::ATOMIC_LOAD_UMIN:
15141 Opc = X86ISD::ATOMUMIN64_DAG;
15143 case ISD::ATOMIC_SWAP:
15144 Opc = X86ISD::ATOMSWAP64_DAG;
15147 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
15150 case ISD::ATOMIC_LOAD: {
15151 ReplaceATOMIC_LOAD(N, Results, DAG);
15154 case ISD::BITCAST: {
15155 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
15156 EVT DstVT = N->getValueType(0);
15157 EVT SrcVT = N->getOperand(0)->getValueType(0);
15159 if (SrcVT != MVT::f64 ||
15160 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
15163 unsigned NumElts = DstVT.getVectorNumElements();
15164 EVT SVT = DstVT.getVectorElementType();
15165 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
15166 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
15167 MVT::v2f64, N->getOperand(0));
15168 SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
15170 SmallVector<SDValue, 8> Elts;
15171 for (unsigned i = 0, e = NumElts; i != e; ++i)
15172 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
15173 ToVecInt, DAG.getIntPtrConstant(i)));
15175 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
15180 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
15182 default: return nullptr;
15183 case X86ISD::BSF: return "X86ISD::BSF";
15184 case X86ISD::BSR: return "X86ISD::BSR";
15185 case X86ISD::SHLD: return "X86ISD::SHLD";
15186 case X86ISD::SHRD: return "X86ISD::SHRD";
15187 case X86ISD::FAND: return "X86ISD::FAND";
15188 case X86ISD::FANDN: return "X86ISD::FANDN";
15189 case X86ISD::FOR: return "X86ISD::FOR";
15190 case X86ISD::FXOR: return "X86ISD::FXOR";
15191 case X86ISD::FSRL: return "X86ISD::FSRL";
15192 case X86ISD::FILD: return "X86ISD::FILD";
15193 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
15194 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
15195 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
15196 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
15197 case X86ISD::FLD: return "X86ISD::FLD";
15198 case X86ISD::FST: return "X86ISD::FST";
15199 case X86ISD::CALL: return "X86ISD::CALL";
15200 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
15201 case X86ISD::RDTSCP_DAG: return "X86ISD::RDTSCP_DAG";
15202 case X86ISD::BT: return "X86ISD::BT";
15203 case X86ISD::CMP: return "X86ISD::CMP";
15204 case X86ISD::COMI: return "X86ISD::COMI";
15205 case X86ISD::UCOMI: return "X86ISD::UCOMI";
15206 case X86ISD::CMPM: return "X86ISD::CMPM";
15207 case X86ISD::CMPMU: return "X86ISD::CMPMU";
15208 case X86ISD::SETCC: return "X86ISD::SETCC";
15209 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
15210 case X86ISD::FSETCC: return "X86ISD::FSETCC";
15211 case X86ISD::CMOV: return "X86ISD::CMOV";
15212 case X86ISD::BRCOND: return "X86ISD::BRCOND";
15213 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
15214 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
15215 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
15216 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
15217 case X86ISD::Wrapper: return "X86ISD::Wrapper";
15218 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
15219 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
15220 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
15221 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
15222 case X86ISD::PINSRB: return "X86ISD::PINSRB";
15223 case X86ISD::PINSRW: return "X86ISD::PINSRW";
15224 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
15225 case X86ISD::ANDNP: return "X86ISD::ANDNP";
15226 case X86ISD::PSIGN: return "X86ISD::PSIGN";
15227 case X86ISD::BLENDV: return "X86ISD::BLENDV";
15228 case X86ISD::BLENDI: return "X86ISD::BLENDI";
15229 case X86ISD::SUBUS: return "X86ISD::SUBUS";
15230 case X86ISD::HADD: return "X86ISD::HADD";
15231 case X86ISD::HSUB: return "X86ISD::HSUB";
15232 case X86ISD::FHADD: return "X86ISD::FHADD";
15233 case X86ISD::FHSUB: return "X86ISD::FHSUB";
15234 case X86ISD::UMAX: return "X86ISD::UMAX";
15235 case X86ISD::UMIN: return "X86ISD::UMIN";
15236 case X86ISD::SMAX: return "X86ISD::SMAX";
15237 case X86ISD::SMIN: return "X86ISD::SMIN";
15238 case X86ISD::FMAX: return "X86ISD::FMAX";
15239 case X86ISD::FMIN: return "X86ISD::FMIN";
15240 case X86ISD::FMAXC: return "X86ISD::FMAXC";
15241 case X86ISD::FMINC: return "X86ISD::FMINC";
15242 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
15243 case X86ISD::FRCP: return "X86ISD::FRCP";
15244 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
15245 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
15246 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
15247 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
15248 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
15249 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
15250 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
15251 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
15252 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
15253 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
15254 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
15255 case X86ISD::LCMPXCHG16_DAG: return "X86ISD::LCMPXCHG16_DAG";
15256 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
15257 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
15258 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
15259 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
15260 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
15261 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
15262 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
15263 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
15264 case X86ISD::VZEXT: return "X86ISD::VZEXT";
15265 case X86ISD::VSEXT: return "X86ISD::VSEXT";
15266 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
15267 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
15268 case X86ISD::VINSERT: return "X86ISD::VINSERT";
15269 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
15270 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
15271 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
15272 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
15273 case X86ISD::VSHL: return "X86ISD::VSHL";
15274 case X86ISD::VSRL: return "X86ISD::VSRL";
15275 case X86ISD::VSRA: return "X86ISD::VSRA";
15276 case X86ISD::VSHLI: return "X86ISD::VSHLI";
15277 case X86ISD::VSRLI: return "X86ISD::VSRLI";
15278 case X86ISD::VSRAI: return "X86ISD::VSRAI";
15279 case X86ISD::CMPP: return "X86ISD::CMPP";
15280 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
15281 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
15282 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
15283 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
15284 case X86ISD::ADD: return "X86ISD::ADD";
15285 case X86ISD::SUB: return "X86ISD::SUB";
15286 case X86ISD::ADC: return "X86ISD::ADC";
15287 case X86ISD::SBB: return "X86ISD::SBB";
15288 case X86ISD::SMUL: return "X86ISD::SMUL";
15289 case X86ISD::UMUL: return "X86ISD::UMUL";
15290 case X86ISD::INC: return "X86ISD::INC";
15291 case X86ISD::DEC: return "X86ISD::DEC";
15292 case X86ISD::OR: return "X86ISD::OR";
15293 case X86ISD::XOR: return "X86ISD::XOR";
15294 case X86ISD::AND: return "X86ISD::AND";
15295 case X86ISD::BEXTR: return "X86ISD::BEXTR";
15296 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
15297 case X86ISD::PTEST: return "X86ISD::PTEST";
15298 case X86ISD::TESTP: return "X86ISD::TESTP";
15299 case X86ISD::TESTM: return "X86ISD::TESTM";
15300 case X86ISD::TESTNM: return "X86ISD::TESTNM";
15301 case X86ISD::KORTEST: return "X86ISD::KORTEST";
15302 case X86ISD::PACKSS: return "X86ISD::PACKSS";
15303 case X86ISD::PACKUS: return "X86ISD::PACKUS";
15304 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
15305 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
15306 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
15307 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
15308 case X86ISD::SHUFP: return "X86ISD::SHUFP";
15309 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
15310 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
15311 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
15312 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
15313 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
15314 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
15315 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
15316 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
15317 case X86ISD::MOVSD: return "X86ISD::MOVSD";
15318 case X86ISD::MOVSS: return "X86ISD::MOVSS";
15319 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
15320 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
15321 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
15322 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
15323 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
15324 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
15325 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
15326 case X86ISD::VPERMV: return "X86ISD::VPERMV";
15327 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
15328 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
15329 case X86ISD::VPERMI: return "X86ISD::VPERMI";
15330 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
15331 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
15332 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
15333 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
15334 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
15335 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
15336 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
15337 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
15338 case X86ISD::SAHF: return "X86ISD::SAHF";
15339 case X86ISD::RDRAND: return "X86ISD::RDRAND";
15340 case X86ISD::RDSEED: return "X86ISD::RDSEED";
15341 case X86ISD::FMADD: return "X86ISD::FMADD";
15342 case X86ISD::FMSUB: return "X86ISD::FMSUB";
15343 case X86ISD::FNMADD: return "X86ISD::FNMADD";
15344 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
15345 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
15346 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
15347 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
15348 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
15349 case X86ISD::XTEST: return "X86ISD::XTEST";
15353 // isLegalAddressingMode - Return true if the addressing mode represented
15354 // by AM is legal for this target, for a load/store of the specified type.
15355 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
15357 // X86 supports extremely general addressing modes.
15358 CodeModel::Model M = getTargetMachine().getCodeModel();
15359 Reloc::Model R = getTargetMachine().getRelocationModel();
15361 // X86 allows a sign-extended 32-bit immediate field as a displacement.
15362 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
15367 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
15369 // If a reference to this global requires an extra load, we can't fold it.
15370 if (isGlobalStubReference(GVFlags))
15373 // If BaseGV requires a register for the PIC base, we cannot also have a
15374 // BaseReg specified.
15375 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
15378 // If lower 4G is not available, then we must use rip-relative addressing.
15379 if ((M != CodeModel::Small || R != Reloc::Static) &&
15380 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
15384 switch (AM.Scale) {
15390 // These scales always work.
15395 // These scales are formed with basereg+scalereg. Only accept if there is
15400 default: // Other stuff never works.
15407 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
15408 unsigned Bits = Ty->getScalarSizeInBits();
15410 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
15411 // particularly cheaper than those without.
15415 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
15416 // variable shifts just as cheap as scalar ones.
15417 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
15420 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
15421 // fully general vector.
15425 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
15426 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15428 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
15429 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
15430 return NumBits1 > NumBits2;
15433 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
15434 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15437 if (!isTypeLegal(EVT::getEVT(Ty1)))
15440 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
15442 // Assuming the caller doesn't have a zeroext or signext return parameter,
15443 // truncation all the way down to i1 is valid.
15447 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
15448 return isInt<32>(Imm);
15451 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
15452 // Can also use sub to handle negated immediates.
15453 return isInt<32>(Imm);
15456 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
15457 if (!VT1.isInteger() || !VT2.isInteger())
15459 unsigned NumBits1 = VT1.getSizeInBits();
15460 unsigned NumBits2 = VT2.getSizeInBits();
15461 return NumBits1 > NumBits2;
15464 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
15465 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
15466 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
15469 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
15470 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
15471 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
15474 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
15475 EVT VT1 = Val.getValueType();
15476 if (isZExtFree(VT1, VT2))
15479 if (Val.getOpcode() != ISD::LOAD)
15482 if (!VT1.isSimple() || !VT1.isInteger() ||
15483 !VT2.isSimple() || !VT2.isInteger())
15486 switch (VT1.getSimpleVT().SimpleTy) {
15491 // X86 has 8, 16, and 32-bit zero-extending loads.
15499 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
15500 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
15503 VT = VT.getScalarType();
15505 if (!VT.isSimple())
15508 switch (VT.getSimpleVT().SimpleTy) {
15519 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
15520 // i16 instructions are longer (0x66 prefix) and potentially slower.
15521 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
15524 /// isShuffleMaskLegal - Targets can use this to indicate that they only
15525 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
15526 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
15527 /// are assumed to be legal.
15529 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
15531 if (!VT.isSimple())
15534 MVT SVT = VT.getSimpleVT();
15536 // Very little shuffling can be done for 64-bit vectors right now.
15537 if (VT.getSizeInBits() == 64)
15540 // If this is a single-input shuffle with no 128 bit lane crossings we can
15541 // lower it into pshufb.
15542 if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
15543 (SVT.is256BitVector() && Subtarget->hasInt256())) {
15544 bool isLegal = true;
15545 for (unsigned I = 0, E = M.size(); I != E; ++I) {
15546 if (M[I] >= (int)SVT.getVectorNumElements() ||
15547 ShuffleCrosses128bitLane(SVT, I, M[I])) {
15556 // FIXME: blends, shifts.
15557 return (SVT.getVectorNumElements() == 2 ||
15558 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
15559 isMOVLMask(M, SVT) ||
15560 isSHUFPMask(M, SVT) ||
15561 isPSHUFDMask(M, SVT) ||
15562 isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
15563 isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
15564 isPALIGNRMask(M, SVT, Subtarget) ||
15565 isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
15566 isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
15567 isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
15568 isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
15569 isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
15573 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
15575 if (!VT.isSimple())
15578 MVT SVT = VT.getSimpleVT();
15579 unsigned NumElts = SVT.getVectorNumElements();
15580 // FIXME: This collection of masks seems suspect.
15583 if (NumElts == 4 && SVT.is128BitVector()) {
15584 return (isMOVLMask(Mask, SVT) ||
15585 isCommutedMOVLMask(Mask, SVT, true) ||
15586 isSHUFPMask(Mask, SVT) ||
15587 isSHUFPMask(Mask, SVT, /* Commuted */ true));
15592 //===----------------------------------------------------------------------===//
15593 // X86 Scheduler Hooks
15594 //===----------------------------------------------------------------------===//
15596 /// Utility function to emit xbegin specifying the start of an RTM region.
15597 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
15598 const TargetInstrInfo *TII) {
15599 DebugLoc DL = MI->getDebugLoc();
15601 const BasicBlock *BB = MBB->getBasicBlock();
15602 MachineFunction::iterator I = MBB;
15605 // For the v = xbegin(), we generate
15616 MachineBasicBlock *thisMBB = MBB;
15617 MachineFunction *MF = MBB->getParent();
15618 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15619 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15620 MF->insert(I, mainMBB);
15621 MF->insert(I, sinkMBB);
15623 // Transfer the remainder of BB and its successor edges to sinkMBB.
15624 sinkMBB->splice(sinkMBB->begin(), MBB,
15625 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15626 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15630 // # fallthrough to mainMBB
15631 // # abortion to sinkMBB
15632 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
15633 thisMBB->addSuccessor(mainMBB);
15634 thisMBB->addSuccessor(sinkMBB);
15638 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
15639 mainMBB->addSuccessor(sinkMBB);
15642 // EAX is live into the sinkMBB
15643 sinkMBB->addLiveIn(X86::EAX);
15644 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15645 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15648 MI->eraseFromParent();
15652 // Get CMPXCHG opcode for the specified data type.
15653 static unsigned getCmpXChgOpcode(EVT VT) {
15654 switch (VT.getSimpleVT().SimpleTy) {
15655 case MVT::i8: return X86::LCMPXCHG8;
15656 case MVT::i16: return X86::LCMPXCHG16;
15657 case MVT::i32: return X86::LCMPXCHG32;
15658 case MVT::i64: return X86::LCMPXCHG64;
15662 llvm_unreachable("Invalid operand size!");
15665 // Get LOAD opcode for the specified data type.
15666 static unsigned getLoadOpcode(EVT VT) {
15667 switch (VT.getSimpleVT().SimpleTy) {
15668 case MVT::i8: return X86::MOV8rm;
15669 case MVT::i16: return X86::MOV16rm;
15670 case MVT::i32: return X86::MOV32rm;
15671 case MVT::i64: return X86::MOV64rm;
15675 llvm_unreachable("Invalid operand size!");
15678 // Get opcode of the non-atomic one from the specified atomic instruction.
15679 static unsigned getNonAtomicOpcode(unsigned Opc) {
15681 case X86::ATOMAND8: return X86::AND8rr;
15682 case X86::ATOMAND16: return X86::AND16rr;
15683 case X86::ATOMAND32: return X86::AND32rr;
15684 case X86::ATOMAND64: return X86::AND64rr;
15685 case X86::ATOMOR8: return X86::OR8rr;
15686 case X86::ATOMOR16: return X86::OR16rr;
15687 case X86::ATOMOR32: return X86::OR32rr;
15688 case X86::ATOMOR64: return X86::OR64rr;
15689 case X86::ATOMXOR8: return X86::XOR8rr;
15690 case X86::ATOMXOR16: return X86::XOR16rr;
15691 case X86::ATOMXOR32: return X86::XOR32rr;
15692 case X86::ATOMXOR64: return X86::XOR64rr;
15694 llvm_unreachable("Unhandled atomic-load-op opcode!");
15697 // Get opcode of the non-atomic one from the specified atomic instruction with
15699 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
15700 unsigned &ExtraOpc) {
15702 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr;
15703 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr;
15704 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr;
15705 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr;
15706 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr;
15707 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
15708 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
15709 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
15710 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr;
15711 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
15712 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
15713 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
15714 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr;
15715 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
15716 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
15717 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
15718 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr;
15719 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
15720 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
15721 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
15723 llvm_unreachable("Unhandled atomic-load-op opcode!");
15726 // Get opcode of the non-atomic one from the specified atomic instruction for
15727 // 64-bit data type on 32-bit target.
15728 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
15730 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr;
15731 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr;
15732 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr;
15733 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr;
15734 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr;
15735 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
15736 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr;
15737 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr;
15738 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr;
15739 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr;
15741 llvm_unreachable("Unhandled atomic-load-op opcode!");
15744 // Get opcode of the non-atomic one from the specified atomic instruction for
15745 // 64-bit data type on 32-bit target with extra opcode.
15746 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
15748 unsigned &ExtraOpc) {
15750 case X86::ATOMNAND6432:
15751 ExtraOpc = X86::NOT32r;
15752 HiOpc = X86::AND32rr;
15753 return X86::AND32rr;
15755 llvm_unreachable("Unhandled atomic-load-op opcode!");
15758 // Get pseudo CMOV opcode from the specified data type.
15759 static unsigned getPseudoCMOVOpc(EVT VT) {
15760 switch (VT.getSimpleVT().SimpleTy) {
15761 case MVT::i8: return X86::CMOV_GR8;
15762 case MVT::i16: return X86::CMOV_GR16;
15763 case MVT::i32: return X86::CMOV_GR32;
15767 llvm_unreachable("Unknown CMOV opcode!");
15770 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
15771 // They will be translated into a spin-loop or compare-exchange loop from
15774 // dst = atomic-fetch-op MI.addr, MI.val
15780 // t1 = LOAD MI.addr
15782 // t4 = phi(t1, t3 / loop)
15783 // t2 = OP MI.val, t4
15785 // LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
15791 MachineBasicBlock *
15792 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
15793 MachineBasicBlock *MBB) const {
15794 MachineFunction *MF = MBB->getParent();
15795 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
15796 DebugLoc DL = MI->getDebugLoc();
15798 MachineRegisterInfo &MRI = MF->getRegInfo();
15800 const BasicBlock *BB = MBB->getBasicBlock();
15801 MachineFunction::iterator I = MBB;
15804 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
15805 "Unexpected number of operands");
15807 assert(MI->hasOneMemOperand() &&
15808 "Expected atomic-load-op to have one memoperand");
15810 // Memory Reference
15811 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15812 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15814 unsigned DstReg, SrcReg;
15815 unsigned MemOpndSlot;
15817 unsigned CurOp = 0;
15819 DstReg = MI->getOperand(CurOp++).getReg();
15820 MemOpndSlot = CurOp;
15821 CurOp += X86::AddrNumOperands;
15822 SrcReg = MI->getOperand(CurOp++).getReg();
15824 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15825 MVT::SimpleValueType VT = *RC->vt_begin();
15826 unsigned t1 = MRI.createVirtualRegister(RC);
15827 unsigned t2 = MRI.createVirtualRegister(RC);
15828 unsigned t3 = MRI.createVirtualRegister(RC);
15829 unsigned t4 = MRI.createVirtualRegister(RC);
15830 unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
15832 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
15833 unsigned LOADOpc = getLoadOpcode(VT);
15835 // For the atomic load-arith operator, we generate
15838 // t1 = LOAD [MI.addr]
15840 // t4 = phi(t1 / thisMBB, t3 / mainMBB)
15841 // t1 = OP MI.val, EAX
15843 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
15849 MachineBasicBlock *thisMBB = MBB;
15850 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15851 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15852 MF->insert(I, mainMBB);
15853 MF->insert(I, sinkMBB);
15855 MachineInstrBuilder MIB;
15857 // Transfer the remainder of BB and its successor edges to sinkMBB.
15858 sinkMBB->splice(sinkMBB->begin(), MBB,
15859 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15860 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15863 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
15864 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15865 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15867 NewMO.setIsKill(false);
15868 MIB.addOperand(NewMO);
15870 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15871 unsigned flags = (*MMOI)->getFlags();
15872 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15873 MachineMemOperand *MMO =
15874 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15875 (*MMOI)->getSize(),
15876 (*MMOI)->getBaseAlignment(),
15877 (*MMOI)->getTBAAInfo(),
15878 (*MMOI)->getRanges());
15879 MIB.addMemOperand(MMO);
15882 thisMBB->addSuccessor(mainMBB);
15885 MachineBasicBlock *origMainMBB = mainMBB;
15888 MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
15889 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15891 unsigned Opc = MI->getOpcode();
15894 llvm_unreachable("Unhandled atomic-load-op opcode!");
15895 case X86::ATOMAND8:
15896 case X86::ATOMAND16:
15897 case X86::ATOMAND32:
15898 case X86::ATOMAND64:
15900 case X86::ATOMOR16:
15901 case X86::ATOMOR32:
15902 case X86::ATOMOR64:
15903 case X86::ATOMXOR8:
15904 case X86::ATOMXOR16:
15905 case X86::ATOMXOR32:
15906 case X86::ATOMXOR64: {
15907 unsigned ARITHOpc = getNonAtomicOpcode(Opc);
15908 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
15912 case X86::ATOMNAND8:
15913 case X86::ATOMNAND16:
15914 case X86::ATOMNAND32:
15915 case X86::ATOMNAND64: {
15916 unsigned Tmp = MRI.createVirtualRegister(RC);
15918 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
15919 BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
15921 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
15924 case X86::ATOMMAX8:
15925 case X86::ATOMMAX16:
15926 case X86::ATOMMAX32:
15927 case X86::ATOMMAX64:
15928 case X86::ATOMMIN8:
15929 case X86::ATOMMIN16:
15930 case X86::ATOMMIN32:
15931 case X86::ATOMMIN64:
15932 case X86::ATOMUMAX8:
15933 case X86::ATOMUMAX16:
15934 case X86::ATOMUMAX32:
15935 case X86::ATOMUMAX64:
15936 case X86::ATOMUMIN8:
15937 case X86::ATOMUMIN16:
15938 case X86::ATOMUMIN32:
15939 case X86::ATOMUMIN64: {
15941 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
15943 BuildMI(mainMBB, DL, TII->get(CMPOpc))
15947 if (Subtarget->hasCMov()) {
15948 if (VT != MVT::i8) {
15950 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
15954 // Promote i8 to i32 to use CMOV32
15955 const TargetRegisterInfo* TRI = MF->getTarget().getRegisterInfo();
15956 const TargetRegisterClass *RC32 =
15957 TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
15958 unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
15959 unsigned AccReg32 = MRI.createVirtualRegister(RC32);
15960 unsigned Tmp = MRI.createVirtualRegister(RC32);
15962 unsigned Undef = MRI.createVirtualRegister(RC32);
15963 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
15965 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
15968 .addImm(X86::sub_8bit);
15969 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
15972 .addImm(X86::sub_8bit);
15974 BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
15978 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
15979 .addReg(Tmp, 0, X86::sub_8bit);
15982 // Use pseudo select and lower them.
15983 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
15984 "Invalid atomic-load-op transformation!");
15985 unsigned SelOpc = getPseudoCMOVOpc(VT);
15986 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
15987 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
15988 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
15989 .addReg(SrcReg).addReg(t4)
15991 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15992 // Replace the original PHI node as mainMBB is changed after CMOV
15994 BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
15995 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15996 Phi->eraseFromParent();
16002 // Copy PhyReg back from virtual register.
16003 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
16006 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
16007 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16008 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
16010 NewMO.setIsKill(false);
16011 MIB.addOperand(NewMO);
16014 MIB.setMemRefs(MMOBegin, MMOEnd);
16016 // Copy PhyReg back to virtual register.
16017 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
16020 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
16022 mainMBB->addSuccessor(origMainMBB);
16023 mainMBB->addSuccessor(sinkMBB);
16026 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16027 TII->get(TargetOpcode::COPY), DstReg)
16030 MI->eraseFromParent();
16034 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
16035 // instructions. They will be translated into a spin-loop or compare-exchange
16039 // dst = atomic-fetch-op MI.addr, MI.val
16045 // t1L = LOAD [MI.addr + 0]
16046 // t1H = LOAD [MI.addr + 4]
16048 // t4L = phi(t1L, t3L / loop)
16049 // t4H = phi(t1H, t3H / loop)
16050 // t2L = OP MI.val.lo, t4L
16051 // t2H = OP MI.val.hi, t4H
16056 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
16064 MachineBasicBlock *
16065 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
16066 MachineBasicBlock *MBB) const {
16067 MachineFunction *MF = MBB->getParent();
16068 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
16069 DebugLoc DL = MI->getDebugLoc();
16071 MachineRegisterInfo &MRI = MF->getRegInfo();
16073 const BasicBlock *BB = MBB->getBasicBlock();
16074 MachineFunction::iterator I = MBB;
16077 assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
16078 "Unexpected number of operands");
16080 assert(MI->hasOneMemOperand() &&
16081 "Expected atomic-load-op32 to have one memoperand");
16083 // Memory Reference
16084 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16085 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16087 unsigned DstLoReg, DstHiReg;
16088 unsigned SrcLoReg, SrcHiReg;
16089 unsigned MemOpndSlot;
16091 unsigned CurOp = 0;
16093 DstLoReg = MI->getOperand(CurOp++).getReg();
16094 DstHiReg = MI->getOperand(CurOp++).getReg();
16095 MemOpndSlot = CurOp;
16096 CurOp += X86::AddrNumOperands;
16097 SrcLoReg = MI->getOperand(CurOp++).getReg();
16098 SrcHiReg = MI->getOperand(CurOp++).getReg();
16100 const TargetRegisterClass *RC = &X86::GR32RegClass;
16101 const TargetRegisterClass *RC8 = &X86::GR8RegClass;
16103 unsigned t1L = MRI.createVirtualRegister(RC);
16104 unsigned t1H = MRI.createVirtualRegister(RC);
16105 unsigned t2L = MRI.createVirtualRegister(RC);
16106 unsigned t2H = MRI.createVirtualRegister(RC);
16107 unsigned t3L = MRI.createVirtualRegister(RC);
16108 unsigned t3H = MRI.createVirtualRegister(RC);
16109 unsigned t4L = MRI.createVirtualRegister(RC);
16110 unsigned t4H = MRI.createVirtualRegister(RC);
16112 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
16113 unsigned LOADOpc = X86::MOV32rm;
16115 // For the atomic load-arith operator, we generate
16118 // t1L = LOAD [MI.addr + 0]
16119 // t1H = LOAD [MI.addr + 4]
16121 // t4L = phi(t1L / thisMBB, t3L / mainMBB)
16122 // t4H = phi(t1H / thisMBB, t3H / mainMBB)
16123 // t2L = OP MI.val.lo, t4L
16124 // t2H = OP MI.val.hi, t4H
16127 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
16135 MachineBasicBlock *thisMBB = MBB;
16136 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16137 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16138 MF->insert(I, mainMBB);
16139 MF->insert(I, sinkMBB);
16141 MachineInstrBuilder MIB;
16143 // Transfer the remainder of BB and its successor edges to sinkMBB.
16144 sinkMBB->splice(sinkMBB->begin(), MBB,
16145 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16146 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16150 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
16151 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16152 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
16154 NewMO.setIsKill(false);
16155 MIB.addOperand(NewMO);
16157 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
16158 unsigned flags = (*MMOI)->getFlags();
16159 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
16160 MachineMemOperand *MMO =
16161 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
16162 (*MMOI)->getSize(),
16163 (*MMOI)->getBaseAlignment(),
16164 (*MMOI)->getTBAAInfo(),
16165 (*MMOI)->getRanges());
16166 MIB.addMemOperand(MMO);
16168 MachineInstr *LowMI = MIB;
16171 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
16172 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16173 if (i == X86::AddrDisp) {
16174 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
16176 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
16178 NewMO.setIsKill(false);
16179 MIB.addOperand(NewMO);
16182 MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
16184 thisMBB->addSuccessor(mainMBB);
16187 MachineBasicBlock *origMainMBB = mainMBB;
16190 MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
16191 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
16192 MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
16193 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
16195 unsigned Opc = MI->getOpcode();
16198 llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
16199 case X86::ATOMAND6432:
16200 case X86::ATOMOR6432:
16201 case X86::ATOMXOR6432:
16202 case X86::ATOMADD6432:
16203 case X86::ATOMSUB6432: {
16205 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
16206 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
16208 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
16212 case X86::ATOMNAND6432: {
16213 unsigned HiOpc, NOTOpc;
16214 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
16215 unsigned TmpL = MRI.createVirtualRegister(RC);
16216 unsigned TmpH = MRI.createVirtualRegister(RC);
16217 BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
16219 BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
16221 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
16222 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
16225 case X86::ATOMMAX6432:
16226 case X86::ATOMMIN6432:
16227 case X86::ATOMUMAX6432:
16228 case X86::ATOMUMIN6432: {
16230 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
16231 unsigned cL = MRI.createVirtualRegister(RC8);
16232 unsigned cH = MRI.createVirtualRegister(RC8);
16233 unsigned cL32 = MRI.createVirtualRegister(RC);
16234 unsigned cH32 = MRI.createVirtualRegister(RC);
16235 unsigned cc = MRI.createVirtualRegister(RC);
16236 // cl := cmp src_lo, lo
16237 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
16238 .addReg(SrcLoReg).addReg(t4L);
16239 BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
16240 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
16241 // ch := cmp src_hi, hi
16242 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
16243 .addReg(SrcHiReg).addReg(t4H);
16244 BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
16245 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
16246 // cc := if (src_hi == hi) ? cl : ch;
16247 if (Subtarget->hasCMov()) {
16248 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
16249 .addReg(cH32).addReg(cL32);
16251 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
16252 .addReg(cH32).addReg(cL32)
16253 .addImm(X86::COND_E);
16254 mainMBB = EmitLoweredSelect(MIB, mainMBB);
16256 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
16257 if (Subtarget->hasCMov()) {
16258 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
16259 .addReg(SrcLoReg).addReg(t4L);
16260 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
16261 .addReg(SrcHiReg).addReg(t4H);
16263 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
16264 .addReg(SrcLoReg).addReg(t4L)
16265 .addImm(X86::COND_NE);
16266 mainMBB = EmitLoweredSelect(MIB, mainMBB);
16267 // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
16268 // 2nd CMOV lowering.
16269 mainMBB->addLiveIn(X86::EFLAGS);
16270 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
16271 .addReg(SrcHiReg).addReg(t4H)
16272 .addImm(X86::COND_NE);
16273 mainMBB = EmitLoweredSelect(MIB, mainMBB);
16274 // Replace the original PHI node as mainMBB is changed after CMOV
16276 BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
16277 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
16278 BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
16279 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
16280 PhiL->eraseFromParent();
16281 PhiH->eraseFromParent();
16285 case X86::ATOMSWAP6432: {
16287 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
16288 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
16289 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
16294 // Copy EDX:EAX back from HiReg:LoReg
16295 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
16296 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
16297 // Copy ECX:EBX from t1H:t1L
16298 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
16299 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
16301 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
16302 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16303 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
16305 NewMO.setIsKill(false);
16306 MIB.addOperand(NewMO);
16308 MIB.setMemRefs(MMOBegin, MMOEnd);
16310 // Copy EDX:EAX back to t3H:t3L
16311 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
16312 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
16314 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
16316 mainMBB->addSuccessor(origMainMBB);
16317 mainMBB->addSuccessor(sinkMBB);
16320 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16321 TII->get(TargetOpcode::COPY), DstLoReg)
16323 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16324 TII->get(TargetOpcode::COPY), DstHiReg)
16327 MI->eraseFromParent();
16331 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
16332 // or XMM0_V32I8 in AVX all of this code can be replaced with that
16333 // in the .td file.
16334 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
16335 const TargetInstrInfo *TII) {
16337 switch (MI->getOpcode()) {
16338 default: llvm_unreachable("illegal opcode!");
16339 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
16340 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
16341 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
16342 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
16343 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
16344 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
16345 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
16346 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
16349 DebugLoc dl = MI->getDebugLoc();
16350 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
16352 unsigned NumArgs = MI->getNumOperands();
16353 for (unsigned i = 1; i < NumArgs; ++i) {
16354 MachineOperand &Op = MI->getOperand(i);
16355 if (!(Op.isReg() && Op.isImplicit()))
16356 MIB.addOperand(Op);
16358 if (MI->hasOneMemOperand())
16359 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
16361 BuildMI(*BB, MI, dl,
16362 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16363 .addReg(X86::XMM0);
16365 MI->eraseFromParent();
16369 // FIXME: Custom handling because TableGen doesn't support multiple implicit
16370 // defs in an instruction pattern
16371 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
16372 const TargetInstrInfo *TII) {
16374 switch (MI->getOpcode()) {
16375 default: llvm_unreachable("illegal opcode!");
16376 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
16377 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
16378 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
16379 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
16380 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
16381 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
16382 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
16383 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
16386 DebugLoc dl = MI->getDebugLoc();
16387 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
16389 unsigned NumArgs = MI->getNumOperands(); // remove the results
16390 for (unsigned i = 1; i < NumArgs; ++i) {
16391 MachineOperand &Op = MI->getOperand(i);
16392 if (!(Op.isReg() && Op.isImplicit()))
16393 MIB.addOperand(Op);
16395 if (MI->hasOneMemOperand())
16396 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
16398 BuildMI(*BB, MI, dl,
16399 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16402 MI->eraseFromParent();
16406 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
16407 const TargetInstrInfo *TII,
16408 const X86Subtarget* Subtarget) {
16409 DebugLoc dl = MI->getDebugLoc();
16411 // Address into RAX/EAX, other two args into ECX, EDX.
16412 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
16413 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
16414 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
16415 for (int i = 0; i < X86::AddrNumOperands; ++i)
16416 MIB.addOperand(MI->getOperand(i));
16418 unsigned ValOps = X86::AddrNumOperands;
16419 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
16420 .addReg(MI->getOperand(ValOps).getReg());
16421 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
16422 .addReg(MI->getOperand(ValOps+1).getReg());
16424 // The instruction doesn't actually take any operands though.
16425 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
16427 MI->eraseFromParent(); // The pseudo is gone now.
16431 MachineBasicBlock *
16432 X86TargetLowering::EmitVAARG64WithCustomInserter(
16434 MachineBasicBlock *MBB) const {
16435 // Emit va_arg instruction on X86-64.
16437 // Operands to this pseudo-instruction:
16438 // 0 ) Output : destination address (reg)
16439 // 1-5) Input : va_list address (addr, i64mem)
16440 // 6 ) ArgSize : Size (in bytes) of vararg type
16441 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
16442 // 8 ) Align : Alignment of type
16443 // 9 ) EFLAGS (implicit-def)
16445 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
16446 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
16448 unsigned DestReg = MI->getOperand(0).getReg();
16449 MachineOperand &Base = MI->getOperand(1);
16450 MachineOperand &Scale = MI->getOperand(2);
16451 MachineOperand &Index = MI->getOperand(3);
16452 MachineOperand &Disp = MI->getOperand(4);
16453 MachineOperand &Segment = MI->getOperand(5);
16454 unsigned ArgSize = MI->getOperand(6).getImm();
16455 unsigned ArgMode = MI->getOperand(7).getImm();
16456 unsigned Align = MI->getOperand(8).getImm();
16458 // Memory Reference
16459 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
16460 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16461 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16463 // Machine Information
16464 const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
16465 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
16466 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
16467 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
16468 DebugLoc DL = MI->getDebugLoc();
16470 // struct va_list {
16473 // i64 overflow_area (address)
16474 // i64 reg_save_area (address)
16476 // sizeof(va_list) = 24
16477 // alignment(va_list) = 8
16479 unsigned TotalNumIntRegs = 6;
16480 unsigned TotalNumXMMRegs = 8;
16481 bool UseGPOffset = (ArgMode == 1);
16482 bool UseFPOffset = (ArgMode == 2);
16483 unsigned MaxOffset = TotalNumIntRegs * 8 +
16484 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
16486 /* Align ArgSize to a multiple of 8 */
16487 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
16488 bool NeedsAlign = (Align > 8);
16490 MachineBasicBlock *thisMBB = MBB;
16491 MachineBasicBlock *overflowMBB;
16492 MachineBasicBlock *offsetMBB;
16493 MachineBasicBlock *endMBB;
16495 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
16496 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
16497 unsigned OffsetReg = 0;
16499 if (!UseGPOffset && !UseFPOffset) {
16500 // If we only pull from the overflow region, we don't create a branch.
16501 // We don't need to alter control flow.
16502 OffsetDestReg = 0; // unused
16503 OverflowDestReg = DestReg;
16505 offsetMBB = nullptr;
16506 overflowMBB = thisMBB;
16509 // First emit code to check if gp_offset (or fp_offset) is below the bound.
16510 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
16511 // If not, pull from overflow_area. (branch to overflowMBB)
16516 // offsetMBB overflowMBB
16521 // Registers for the PHI in endMBB
16522 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
16523 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
16525 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
16526 MachineFunction *MF = MBB->getParent();
16527 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16528 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16529 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16531 MachineFunction::iterator MBBIter = MBB;
16534 // Insert the new basic blocks
16535 MF->insert(MBBIter, offsetMBB);
16536 MF->insert(MBBIter, overflowMBB);
16537 MF->insert(MBBIter, endMBB);
16539 // Transfer the remainder of MBB and its successor edges to endMBB.
16540 endMBB->splice(endMBB->begin(), thisMBB,
16541 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
16542 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
16544 // Make offsetMBB and overflowMBB successors of thisMBB
16545 thisMBB->addSuccessor(offsetMBB);
16546 thisMBB->addSuccessor(overflowMBB);
16548 // endMBB is a successor of both offsetMBB and overflowMBB
16549 offsetMBB->addSuccessor(endMBB);
16550 overflowMBB->addSuccessor(endMBB);
16552 // Load the offset value into a register
16553 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
16554 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
16558 .addDisp(Disp, UseFPOffset ? 4 : 0)
16559 .addOperand(Segment)
16560 .setMemRefs(MMOBegin, MMOEnd);
16562 // Check if there is enough room left to pull this argument.
16563 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
16565 .addImm(MaxOffset + 8 - ArgSizeA8);
16567 // Branch to "overflowMBB" if offset >= max
16568 // Fall through to "offsetMBB" otherwise
16569 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
16570 .addMBB(overflowMBB);
16573 // In offsetMBB, emit code to use the reg_save_area.
16575 assert(OffsetReg != 0);
16577 // Read the reg_save_area address.
16578 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
16579 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
16584 .addOperand(Segment)
16585 .setMemRefs(MMOBegin, MMOEnd);
16587 // Zero-extend the offset
16588 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
16589 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
16592 .addImm(X86::sub_32bit);
16594 // Add the offset to the reg_save_area to get the final address.
16595 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
16596 .addReg(OffsetReg64)
16597 .addReg(RegSaveReg);
16599 // Compute the offset for the next argument
16600 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
16601 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
16603 .addImm(UseFPOffset ? 16 : 8);
16605 // Store it back into the va_list.
16606 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
16610 .addDisp(Disp, UseFPOffset ? 4 : 0)
16611 .addOperand(Segment)
16612 .addReg(NextOffsetReg)
16613 .setMemRefs(MMOBegin, MMOEnd);
16616 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
16621 // Emit code to use overflow area
16624 // Load the overflow_area address into a register.
16625 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
16626 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
16631 .addOperand(Segment)
16632 .setMemRefs(MMOBegin, MMOEnd);
16634 // If we need to align it, do so. Otherwise, just copy the address
16635 // to OverflowDestReg.
16637 // Align the overflow address
16638 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
16639 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
16641 // aligned_addr = (addr + (align-1)) & ~(align-1)
16642 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
16643 .addReg(OverflowAddrReg)
16646 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
16648 .addImm(~(uint64_t)(Align-1));
16650 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
16651 .addReg(OverflowAddrReg);
16654 // Compute the next overflow address after this argument.
16655 // (the overflow address should be kept 8-byte aligned)
16656 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
16657 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
16658 .addReg(OverflowDestReg)
16659 .addImm(ArgSizeA8);
16661 // Store the new overflow address.
16662 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
16667 .addOperand(Segment)
16668 .addReg(NextAddrReg)
16669 .setMemRefs(MMOBegin, MMOEnd);
16671 // If we branched, emit the PHI to the front of endMBB.
16673 BuildMI(*endMBB, endMBB->begin(), DL,
16674 TII->get(X86::PHI), DestReg)
16675 .addReg(OffsetDestReg).addMBB(offsetMBB)
16676 .addReg(OverflowDestReg).addMBB(overflowMBB);
16679 // Erase the pseudo instruction
16680 MI->eraseFromParent();
16685 MachineBasicBlock *
16686 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
16688 MachineBasicBlock *MBB) const {
16689 // Emit code to save XMM registers to the stack. The ABI says that the
16690 // number of registers to save is given in %al, so it's theoretically
16691 // possible to do an indirect jump trick to avoid saving all of them,
16692 // however this code takes a simpler approach and just executes all
16693 // of the stores if %al is non-zero. It's less code, and it's probably
16694 // easier on the hardware branch predictor, and stores aren't all that
16695 // expensive anyway.
16697 // Create the new basic blocks. One block contains all the XMM stores,
16698 // and one block is the final destination regardless of whether any
16699 // stores were performed.
16700 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
16701 MachineFunction *F = MBB->getParent();
16702 MachineFunction::iterator MBBIter = MBB;
16704 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
16705 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
16706 F->insert(MBBIter, XMMSaveMBB);
16707 F->insert(MBBIter, EndMBB);
16709 // Transfer the remainder of MBB and its successor edges to EndMBB.
16710 EndMBB->splice(EndMBB->begin(), MBB,
16711 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16712 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
16714 // The original block will now fall through to the XMM save block.
16715 MBB->addSuccessor(XMMSaveMBB);
16716 // The XMMSaveMBB will fall through to the end block.
16717 XMMSaveMBB->addSuccessor(EndMBB);
16719 // Now add the instructions.
16720 const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
16721 DebugLoc DL = MI->getDebugLoc();
16723 unsigned CountReg = MI->getOperand(0).getReg();
16724 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
16725 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
16727 if (!Subtarget->isTargetWin64()) {
16728 // If %al is 0, branch around the XMM save block.
16729 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
16730 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
16731 MBB->addSuccessor(EndMBB);
16734 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
16735 // that was just emitted, but clearly shouldn't be "saved".
16736 assert((MI->getNumOperands() <= 3 ||
16737 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
16738 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
16739 && "Expected last argument to be EFLAGS");
16740 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
16741 // In the XMM save block, save all the XMM argument registers.
16742 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
16743 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
16744 MachineMemOperand *MMO =
16745 F->getMachineMemOperand(
16746 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
16747 MachineMemOperand::MOStore,
16748 /*Size=*/16, /*Align=*/16);
16749 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
16750 .addFrameIndex(RegSaveFrameIndex)
16751 .addImm(/*Scale=*/1)
16752 .addReg(/*IndexReg=*/0)
16753 .addImm(/*Disp=*/Offset)
16754 .addReg(/*Segment=*/0)
16755 .addReg(MI->getOperand(i).getReg())
16756 .addMemOperand(MMO);
16759 MI->eraseFromParent(); // The pseudo instruction is gone now.
16764 // The EFLAGS operand of SelectItr might be missing a kill marker
16765 // because there were multiple uses of EFLAGS, and ISel didn't know
16766 // which to mark. Figure out whether SelectItr should have had a
16767 // kill marker, and set it if it should. Returns the correct kill
16769 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
16770 MachineBasicBlock* BB,
16771 const TargetRegisterInfo* TRI) {
16772 // Scan forward through BB for a use/def of EFLAGS.
16773 MachineBasicBlock::iterator miI(std::next(SelectItr));
16774 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
16775 const MachineInstr& mi = *miI;
16776 if (mi.readsRegister(X86::EFLAGS))
16778 if (mi.definesRegister(X86::EFLAGS))
16779 break; // Should have kill-flag - update below.
16782 // If we hit the end of the block, check whether EFLAGS is live into a
16784 if (miI == BB->end()) {
16785 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
16786 sEnd = BB->succ_end();
16787 sItr != sEnd; ++sItr) {
16788 MachineBasicBlock* succ = *sItr;
16789 if (succ->isLiveIn(X86::EFLAGS))
16794 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
16795 // out. SelectMI should have a kill flag on EFLAGS.
16796 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
16800 MachineBasicBlock *
16801 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
16802 MachineBasicBlock *BB) const {
16803 const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
16804 DebugLoc DL = MI->getDebugLoc();
16806 // To "insert" a SELECT_CC instruction, we actually have to insert the
16807 // diamond control-flow pattern. The incoming instruction knows the
16808 // destination vreg to set, the condition code register to branch on, the
16809 // true/false values to select between, and a branch opcode to use.
16810 const BasicBlock *LLVM_BB = BB->getBasicBlock();
16811 MachineFunction::iterator It = BB;
16817 // cmpTY ccX, r1, r2
16819 // fallthrough --> copy0MBB
16820 MachineBasicBlock *thisMBB = BB;
16821 MachineFunction *F = BB->getParent();
16822 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
16823 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
16824 F->insert(It, copy0MBB);
16825 F->insert(It, sinkMBB);
16827 // If the EFLAGS register isn't dead in the terminator, then claim that it's
16828 // live into the sink and copy blocks.
16829 const TargetRegisterInfo* TRI = BB->getParent()->getTarget().getRegisterInfo();
16830 if (!MI->killsRegister(X86::EFLAGS) &&
16831 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
16832 copy0MBB->addLiveIn(X86::EFLAGS);
16833 sinkMBB->addLiveIn(X86::EFLAGS);
16836 // Transfer the remainder of BB and its successor edges to sinkMBB.
16837 sinkMBB->splice(sinkMBB->begin(), BB,
16838 std::next(MachineBasicBlock::iterator(MI)), BB->end());
16839 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
16841 // Add the true and fallthrough blocks as its successors.
16842 BB->addSuccessor(copy0MBB);
16843 BB->addSuccessor(sinkMBB);
16845 // Create the conditional branch instruction.
16847 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
16848 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
16851 // %FalseValue = ...
16852 // # fallthrough to sinkMBB
16853 copy0MBB->addSuccessor(sinkMBB);
16856 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
16858 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16859 TII->get(X86::PHI), MI->getOperand(0).getReg())
16860 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
16861 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
16863 MI->eraseFromParent(); // The pseudo instruction is gone now.
16867 MachineBasicBlock *
16868 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
16869 bool Is64Bit) const {
16870 MachineFunction *MF = BB->getParent();
16871 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
16872 DebugLoc DL = MI->getDebugLoc();
16873 const BasicBlock *LLVM_BB = BB->getBasicBlock();
16875 assert(MF->shouldSplitStack());
16877 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
16878 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
16881 // ... [Till the alloca]
16882 // If stacklet is not large enough, jump to mallocMBB
16885 // Allocate by subtracting from RSP
16886 // Jump to continueMBB
16889 // Allocate by call to runtime
16893 // [rest of original BB]
16896 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16897 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16898 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16900 MachineRegisterInfo &MRI = MF->getRegInfo();
16901 const TargetRegisterClass *AddrRegClass =
16902 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
16904 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16905 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16906 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
16907 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
16908 sizeVReg = MI->getOperand(1).getReg(),
16909 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
16911 MachineFunction::iterator MBBIter = BB;
16914 MF->insert(MBBIter, bumpMBB);
16915 MF->insert(MBBIter, mallocMBB);
16916 MF->insert(MBBIter, continueMBB);
16918 continueMBB->splice(continueMBB->begin(), BB,
16919 std::next(MachineBasicBlock::iterator(MI)), BB->end());
16920 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
16922 // Add code to the main basic block to check if the stack limit has been hit,
16923 // and if so, jump to mallocMBB otherwise to bumpMBB.
16924 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
16925 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
16926 .addReg(tmpSPVReg).addReg(sizeVReg);
16927 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
16928 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
16929 .addReg(SPLimitVReg);
16930 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
16932 // bumpMBB simply decreases the stack pointer, since we know the current
16933 // stacklet has enough space.
16934 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
16935 .addReg(SPLimitVReg);
16936 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
16937 .addReg(SPLimitVReg);
16938 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16940 // Calls into a routine in libgcc to allocate more space from the heap.
16941 const uint32_t *RegMask =
16942 MF->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16944 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
16946 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
16947 .addExternalSymbol("__morestack_allocate_stack_space")
16948 .addRegMask(RegMask)
16949 .addReg(X86::RDI, RegState::Implicit)
16950 .addReg(X86::RAX, RegState::ImplicitDefine);
16952 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
16954 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
16955 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
16956 .addExternalSymbol("__morestack_allocate_stack_space")
16957 .addRegMask(RegMask)
16958 .addReg(X86::EAX, RegState::ImplicitDefine);
16962 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
16965 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
16966 .addReg(Is64Bit ? X86::RAX : X86::EAX);
16967 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16969 // Set up the CFG correctly.
16970 BB->addSuccessor(bumpMBB);
16971 BB->addSuccessor(mallocMBB);
16972 mallocMBB->addSuccessor(continueMBB);
16973 bumpMBB->addSuccessor(continueMBB);
16975 // Take care of the PHI nodes.
16976 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
16977 MI->getOperand(0).getReg())
16978 .addReg(mallocPtrVReg).addMBB(mallocMBB)
16979 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
16981 // Delete the original pseudo instruction.
16982 MI->eraseFromParent();
16985 return continueMBB;
16988 MachineBasicBlock *
16989 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
16990 MachineBasicBlock *BB) const {
16991 const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
16992 DebugLoc DL = MI->getDebugLoc();
16994 assert(!Subtarget->isTargetMacho());
16996 // The lowering is pretty easy: we're just emitting the call to _alloca. The
16997 // non-trivial part is impdef of ESP.
16999 if (Subtarget->isTargetWin64()) {
17000 if (Subtarget->isTargetCygMing()) {
17001 // ___chkstk(Mingw64):
17002 // Clobbers R10, R11, RAX and EFLAGS.
17004 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
17005 .addExternalSymbol("___chkstk")
17006 .addReg(X86::RAX, RegState::Implicit)
17007 .addReg(X86::RSP, RegState::Implicit)
17008 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
17009 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
17010 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17012 // __chkstk(MSVCRT): does not update stack pointer.
17013 // Clobbers R10, R11 and EFLAGS.
17014 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
17015 .addExternalSymbol("__chkstk")
17016 .addReg(X86::RAX, RegState::Implicit)
17017 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17018 // RAX has the offset to be subtracted from RSP.
17019 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
17024 const char *StackProbeSymbol =
17025 Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
17027 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
17028 .addExternalSymbol(StackProbeSymbol)
17029 .addReg(X86::EAX, RegState::Implicit)
17030 .addReg(X86::ESP, RegState::Implicit)
17031 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
17032 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
17033 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17036 MI->eraseFromParent(); // The pseudo instruction is gone now.
17040 MachineBasicBlock *
17041 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
17042 MachineBasicBlock *BB) const {
17043 // This is pretty easy. We're taking the value that we received from
17044 // our load from the relocation, sticking it in either RDI (x86-64)
17045 // or EAX and doing an indirect call. The return value will then
17046 // be in the normal return register.
17047 MachineFunction *F = BB->getParent();
17048 const X86InstrInfo *TII
17049 = static_cast<const X86InstrInfo*>(F->getTarget().getInstrInfo());
17050 DebugLoc DL = MI->getDebugLoc();
17052 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
17053 assert(MI->getOperand(3).isGlobal() && "This should be a global");
17055 // Get a register mask for the lowered call.
17056 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
17057 // proper register mask.
17058 const uint32_t *RegMask =
17059 F->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
17060 if (Subtarget->is64Bit()) {
17061 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17062 TII->get(X86::MOV64rm), X86::RDI)
17064 .addImm(0).addReg(0)
17065 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17066 MI->getOperand(3).getTargetFlags())
17068 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
17069 addDirectMem(MIB, X86::RDI);
17070 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
17071 } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
17072 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17073 TII->get(X86::MOV32rm), X86::EAX)
17075 .addImm(0).addReg(0)
17076 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17077 MI->getOperand(3).getTargetFlags())
17079 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
17080 addDirectMem(MIB, X86::EAX);
17081 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
17083 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17084 TII->get(X86::MOV32rm), X86::EAX)
17085 .addReg(TII->getGlobalBaseReg(F))
17086 .addImm(0).addReg(0)
17087 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17088 MI->getOperand(3).getTargetFlags())
17090 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
17091 addDirectMem(MIB, X86::EAX);
17092 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
17095 MI->eraseFromParent(); // The pseudo instruction is gone now.
17099 MachineBasicBlock *
17100 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
17101 MachineBasicBlock *MBB) const {
17102 DebugLoc DL = MI->getDebugLoc();
17103 MachineFunction *MF = MBB->getParent();
17104 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17105 MachineRegisterInfo &MRI = MF->getRegInfo();
17107 const BasicBlock *BB = MBB->getBasicBlock();
17108 MachineFunction::iterator I = MBB;
17111 // Memory Reference
17112 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17113 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17116 unsigned MemOpndSlot = 0;
17118 unsigned CurOp = 0;
17120 DstReg = MI->getOperand(CurOp++).getReg();
17121 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
17122 assert(RC->hasType(MVT::i32) && "Invalid destination!");
17123 unsigned mainDstReg = MRI.createVirtualRegister(RC);
17124 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
17126 MemOpndSlot = CurOp;
17128 MVT PVT = getPointerTy();
17129 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
17130 "Invalid Pointer Size!");
17132 // For v = setjmp(buf), we generate
17135 // buf[LabelOffset] = restoreMBB
17136 // SjLjSetup restoreMBB
17142 // v = phi(main, restore)
17147 MachineBasicBlock *thisMBB = MBB;
17148 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17149 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17150 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
17151 MF->insert(I, mainMBB);
17152 MF->insert(I, sinkMBB);
17153 MF->push_back(restoreMBB);
17155 MachineInstrBuilder MIB;
17157 // Transfer the remainder of BB and its successor edges to sinkMBB.
17158 sinkMBB->splice(sinkMBB->begin(), MBB,
17159 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17160 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17163 unsigned PtrStoreOpc = 0;
17164 unsigned LabelReg = 0;
17165 const int64_t LabelOffset = 1 * PVT.getStoreSize();
17166 Reloc::Model RM = MF->getTarget().getRelocationModel();
17167 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
17168 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
17170 // Prepare IP either in reg or imm.
17171 if (!UseImmLabel) {
17172 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
17173 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
17174 LabelReg = MRI.createVirtualRegister(PtrRC);
17175 if (Subtarget->is64Bit()) {
17176 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
17180 .addMBB(restoreMBB)
17183 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
17184 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
17185 .addReg(XII->getGlobalBaseReg(MF))
17188 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
17192 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
17194 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
17195 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17196 if (i == X86::AddrDisp)
17197 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
17199 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
17202 MIB.addReg(LabelReg);
17204 MIB.addMBB(restoreMBB);
17205 MIB.setMemRefs(MMOBegin, MMOEnd);
17207 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
17208 .addMBB(restoreMBB);
17210 const X86RegisterInfo *RegInfo =
17211 static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
17212 MIB.addRegMask(RegInfo->getNoPreservedMask());
17213 thisMBB->addSuccessor(mainMBB);
17214 thisMBB->addSuccessor(restoreMBB);
17218 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
17219 mainMBB->addSuccessor(sinkMBB);
17222 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17223 TII->get(X86::PHI), DstReg)
17224 .addReg(mainDstReg).addMBB(mainMBB)
17225 .addReg(restoreDstReg).addMBB(restoreMBB);
17228 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
17229 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
17230 restoreMBB->addSuccessor(sinkMBB);
17232 MI->eraseFromParent();
17236 MachineBasicBlock *
17237 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
17238 MachineBasicBlock *MBB) const {
17239 DebugLoc DL = MI->getDebugLoc();
17240 MachineFunction *MF = MBB->getParent();
17241 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17242 MachineRegisterInfo &MRI = MF->getRegInfo();
17244 // Memory Reference
17245 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17246 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17248 MVT PVT = getPointerTy();
17249 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
17250 "Invalid Pointer Size!");
17252 const TargetRegisterClass *RC =
17253 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
17254 unsigned Tmp = MRI.createVirtualRegister(RC);
17255 // Since FP is only updated here but NOT referenced, it's treated as GPR.
17256 const X86RegisterInfo *RegInfo =
17257 static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
17258 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
17259 unsigned SP = RegInfo->getStackRegister();
17261 MachineInstrBuilder MIB;
17263 const int64_t LabelOffset = 1 * PVT.getStoreSize();
17264 const int64_t SPOffset = 2 * PVT.getStoreSize();
17266 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
17267 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
17270 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
17271 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
17272 MIB.addOperand(MI->getOperand(i));
17273 MIB.setMemRefs(MMOBegin, MMOEnd);
17275 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
17276 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17277 if (i == X86::AddrDisp)
17278 MIB.addDisp(MI->getOperand(i), LabelOffset);
17280 MIB.addOperand(MI->getOperand(i));
17282 MIB.setMemRefs(MMOBegin, MMOEnd);
17284 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
17285 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17286 if (i == X86::AddrDisp)
17287 MIB.addDisp(MI->getOperand(i), SPOffset);
17289 MIB.addOperand(MI->getOperand(i));
17291 MIB.setMemRefs(MMOBegin, MMOEnd);
17293 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
17295 MI->eraseFromParent();
17299 // Replace 213-type (isel default) FMA3 instructions with 231-type for
17300 // accumulator loops. Writing back to the accumulator allows the coalescer
17301 // to remove extra copies in the loop.
17302 MachineBasicBlock *
17303 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
17304 MachineBasicBlock *MBB) const {
17305 MachineOperand &AddendOp = MI->getOperand(3);
17307 // Bail out early if the addend isn't a register - we can't switch these.
17308 if (!AddendOp.isReg())
17311 MachineFunction &MF = *MBB->getParent();
17312 MachineRegisterInfo &MRI = MF.getRegInfo();
17314 // Check whether the addend is defined by a PHI:
17315 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
17316 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
17317 if (!AddendDef.isPHI())
17320 // Look for the following pattern:
17322 // %addend = phi [%entry, 0], [%loop, %result]
17324 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
17328 // %addend = phi [%entry, 0], [%loop, %result]
17330 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
17332 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
17333 assert(AddendDef.getOperand(i).isReg());
17334 MachineOperand PHISrcOp = AddendDef.getOperand(i);
17335 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
17336 if (&PHISrcInst == MI) {
17337 // Found a matching instruction.
17338 unsigned NewFMAOpc = 0;
17339 switch (MI->getOpcode()) {
17340 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
17341 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
17342 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
17343 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
17344 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
17345 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
17346 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
17347 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
17348 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
17349 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
17350 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
17351 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
17352 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
17353 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
17354 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
17355 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
17356 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
17357 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
17358 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
17359 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
17360 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
17361 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
17362 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
17363 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
17364 default: llvm_unreachable("Unrecognized FMA variant.");
17367 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
17368 MachineInstrBuilder MIB =
17369 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
17370 .addOperand(MI->getOperand(0))
17371 .addOperand(MI->getOperand(3))
17372 .addOperand(MI->getOperand(2))
17373 .addOperand(MI->getOperand(1));
17374 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
17375 MI->eraseFromParent();
17382 MachineBasicBlock *
17383 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
17384 MachineBasicBlock *BB) const {
17385 switch (MI->getOpcode()) {
17386 default: llvm_unreachable("Unexpected instr type to insert");
17387 case X86::TAILJMPd64:
17388 case X86::TAILJMPr64:
17389 case X86::TAILJMPm64:
17390 llvm_unreachable("TAILJMP64 would not be touched here.");
17391 case X86::TCRETURNdi64:
17392 case X86::TCRETURNri64:
17393 case X86::TCRETURNmi64:
17395 case X86::WIN_ALLOCA:
17396 return EmitLoweredWinAlloca(MI, BB);
17397 case X86::SEG_ALLOCA_32:
17398 return EmitLoweredSegAlloca(MI, BB, false);
17399 case X86::SEG_ALLOCA_64:
17400 return EmitLoweredSegAlloca(MI, BB, true);
17401 case X86::TLSCall_32:
17402 case X86::TLSCall_64:
17403 return EmitLoweredTLSCall(MI, BB);
17404 case X86::CMOV_GR8:
17405 case X86::CMOV_FR32:
17406 case X86::CMOV_FR64:
17407 case X86::CMOV_V4F32:
17408 case X86::CMOV_V2F64:
17409 case X86::CMOV_V2I64:
17410 case X86::CMOV_V8F32:
17411 case X86::CMOV_V4F64:
17412 case X86::CMOV_V4I64:
17413 case X86::CMOV_V16F32:
17414 case X86::CMOV_V8F64:
17415 case X86::CMOV_V8I64:
17416 case X86::CMOV_GR16:
17417 case X86::CMOV_GR32:
17418 case X86::CMOV_RFP32:
17419 case X86::CMOV_RFP64:
17420 case X86::CMOV_RFP80:
17421 return EmitLoweredSelect(MI, BB);
17423 case X86::FP32_TO_INT16_IN_MEM:
17424 case X86::FP32_TO_INT32_IN_MEM:
17425 case X86::FP32_TO_INT64_IN_MEM:
17426 case X86::FP64_TO_INT16_IN_MEM:
17427 case X86::FP64_TO_INT32_IN_MEM:
17428 case X86::FP64_TO_INT64_IN_MEM:
17429 case X86::FP80_TO_INT16_IN_MEM:
17430 case X86::FP80_TO_INT32_IN_MEM:
17431 case X86::FP80_TO_INT64_IN_MEM: {
17432 MachineFunction *F = BB->getParent();
17433 const TargetInstrInfo *TII = F->getTarget().getInstrInfo();
17434 DebugLoc DL = MI->getDebugLoc();
17436 // Change the floating point control register to use "round towards zero"
17437 // mode when truncating to an integer value.
17438 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
17439 addFrameReference(BuildMI(*BB, MI, DL,
17440 TII->get(X86::FNSTCW16m)), CWFrameIdx);
17442 // Load the old value of the high byte of the control word...
17444 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
17445 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
17448 // Set the high part to be round to zero...
17449 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
17452 // Reload the modified control word now...
17453 addFrameReference(BuildMI(*BB, MI, DL,
17454 TII->get(X86::FLDCW16m)), CWFrameIdx);
17456 // Restore the memory image of control word to original value
17457 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
17460 // Get the X86 opcode to use.
17462 switch (MI->getOpcode()) {
17463 default: llvm_unreachable("illegal opcode!");
17464 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
17465 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
17466 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
17467 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
17468 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
17469 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
17470 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
17471 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
17472 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
17476 MachineOperand &Op = MI->getOperand(0);
17478 AM.BaseType = X86AddressMode::RegBase;
17479 AM.Base.Reg = Op.getReg();
17481 AM.BaseType = X86AddressMode::FrameIndexBase;
17482 AM.Base.FrameIndex = Op.getIndex();
17484 Op = MI->getOperand(1);
17486 AM.Scale = Op.getImm();
17487 Op = MI->getOperand(2);
17489 AM.IndexReg = Op.getImm();
17490 Op = MI->getOperand(3);
17491 if (Op.isGlobal()) {
17492 AM.GV = Op.getGlobal();
17494 AM.Disp = Op.getImm();
17496 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
17497 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
17499 // Reload the original control word now.
17500 addFrameReference(BuildMI(*BB, MI, DL,
17501 TII->get(X86::FLDCW16m)), CWFrameIdx);
17503 MI->eraseFromParent(); // The pseudo instruction is gone now.
17506 // String/text processing lowering.
17507 case X86::PCMPISTRM128REG:
17508 case X86::VPCMPISTRM128REG:
17509 case X86::PCMPISTRM128MEM:
17510 case X86::VPCMPISTRM128MEM:
17511 case X86::PCMPESTRM128REG:
17512 case X86::VPCMPESTRM128REG:
17513 case X86::PCMPESTRM128MEM:
17514 case X86::VPCMPESTRM128MEM:
17515 assert(Subtarget->hasSSE42() &&
17516 "Target must have SSE4.2 or AVX features enabled");
17517 return EmitPCMPSTRM(MI, BB, BB->getParent()->getTarget().getInstrInfo());
17519 // String/text processing lowering.
17520 case X86::PCMPISTRIREG:
17521 case X86::VPCMPISTRIREG:
17522 case X86::PCMPISTRIMEM:
17523 case X86::VPCMPISTRIMEM:
17524 case X86::PCMPESTRIREG:
17525 case X86::VPCMPESTRIREG:
17526 case X86::PCMPESTRIMEM:
17527 case X86::VPCMPESTRIMEM:
17528 assert(Subtarget->hasSSE42() &&
17529 "Target must have SSE4.2 or AVX features enabled");
17530 return EmitPCMPSTRI(MI, BB, BB->getParent()->getTarget().getInstrInfo());
17532 // Thread synchronization.
17534 return EmitMonitor(MI, BB, BB->getParent()->getTarget().getInstrInfo(), Subtarget);
17538 return EmitXBegin(MI, BB, BB->getParent()->getTarget().getInstrInfo());
17540 // Atomic Lowering.
17541 case X86::ATOMAND8:
17542 case X86::ATOMAND16:
17543 case X86::ATOMAND32:
17544 case X86::ATOMAND64:
17547 case X86::ATOMOR16:
17548 case X86::ATOMOR32:
17549 case X86::ATOMOR64:
17551 case X86::ATOMXOR16:
17552 case X86::ATOMXOR8:
17553 case X86::ATOMXOR32:
17554 case X86::ATOMXOR64:
17556 case X86::ATOMNAND8:
17557 case X86::ATOMNAND16:
17558 case X86::ATOMNAND32:
17559 case X86::ATOMNAND64:
17561 case X86::ATOMMAX8:
17562 case X86::ATOMMAX16:
17563 case X86::ATOMMAX32:
17564 case X86::ATOMMAX64:
17566 case X86::ATOMMIN8:
17567 case X86::ATOMMIN16:
17568 case X86::ATOMMIN32:
17569 case X86::ATOMMIN64:
17571 case X86::ATOMUMAX8:
17572 case X86::ATOMUMAX16:
17573 case X86::ATOMUMAX32:
17574 case X86::ATOMUMAX64:
17576 case X86::ATOMUMIN8:
17577 case X86::ATOMUMIN16:
17578 case X86::ATOMUMIN32:
17579 case X86::ATOMUMIN64:
17580 return EmitAtomicLoadArith(MI, BB);
17582 // This group does 64-bit operations on a 32-bit host.
17583 case X86::ATOMAND6432:
17584 case X86::ATOMOR6432:
17585 case X86::ATOMXOR6432:
17586 case X86::ATOMNAND6432:
17587 case X86::ATOMADD6432:
17588 case X86::ATOMSUB6432:
17589 case X86::ATOMMAX6432:
17590 case X86::ATOMMIN6432:
17591 case X86::ATOMUMAX6432:
17592 case X86::ATOMUMIN6432:
17593 case X86::ATOMSWAP6432:
17594 return EmitAtomicLoadArith6432(MI, BB);
17596 case X86::VASTART_SAVE_XMM_REGS:
17597 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
17599 case X86::VAARG_64:
17600 return EmitVAARG64WithCustomInserter(MI, BB);
17602 case X86::EH_SjLj_SetJmp32:
17603 case X86::EH_SjLj_SetJmp64:
17604 return emitEHSjLjSetJmp(MI, BB);
17606 case X86::EH_SjLj_LongJmp32:
17607 case X86::EH_SjLj_LongJmp64:
17608 return emitEHSjLjLongJmp(MI, BB);
17610 case TargetOpcode::STACKMAP:
17611 case TargetOpcode::PATCHPOINT:
17612 return emitPatchPoint(MI, BB);
17614 case X86::VFMADDPDr213r:
17615 case X86::VFMADDPSr213r:
17616 case X86::VFMADDSDr213r:
17617 case X86::VFMADDSSr213r:
17618 case X86::VFMSUBPDr213r:
17619 case X86::VFMSUBPSr213r:
17620 case X86::VFMSUBSDr213r:
17621 case X86::VFMSUBSSr213r:
17622 case X86::VFNMADDPDr213r:
17623 case X86::VFNMADDPSr213r:
17624 case X86::VFNMADDSDr213r:
17625 case X86::VFNMADDSSr213r:
17626 case X86::VFNMSUBPDr213r:
17627 case X86::VFNMSUBPSr213r:
17628 case X86::VFNMSUBSDr213r:
17629 case X86::VFNMSUBSSr213r:
17630 case X86::VFMADDPDr213rY:
17631 case X86::VFMADDPSr213rY:
17632 case X86::VFMSUBPDr213rY:
17633 case X86::VFMSUBPSr213rY:
17634 case X86::VFNMADDPDr213rY:
17635 case X86::VFNMADDPSr213rY:
17636 case X86::VFNMSUBPDr213rY:
17637 case X86::VFNMSUBPSr213rY:
17638 return emitFMA3Instr(MI, BB);
17642 //===----------------------------------------------------------------------===//
17643 // X86 Optimization Hooks
17644 //===----------------------------------------------------------------------===//
17646 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
17649 const SelectionDAG &DAG,
17650 unsigned Depth) const {
17651 unsigned BitWidth = KnownZero.getBitWidth();
17652 unsigned Opc = Op.getOpcode();
17653 assert((Opc >= ISD::BUILTIN_OP_END ||
17654 Opc == ISD::INTRINSIC_WO_CHAIN ||
17655 Opc == ISD::INTRINSIC_W_CHAIN ||
17656 Opc == ISD::INTRINSIC_VOID) &&
17657 "Should use MaskedValueIsZero if you don't know whether Op"
17658 " is a target node!");
17660 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
17674 // These nodes' second result is a boolean.
17675 if (Op.getResNo() == 0)
17678 case X86ISD::SETCC:
17679 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
17681 case ISD::INTRINSIC_WO_CHAIN: {
17682 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17683 unsigned NumLoBits = 0;
17686 case Intrinsic::x86_sse_movmsk_ps:
17687 case Intrinsic::x86_avx_movmsk_ps_256:
17688 case Intrinsic::x86_sse2_movmsk_pd:
17689 case Intrinsic::x86_avx_movmsk_pd_256:
17690 case Intrinsic::x86_mmx_pmovmskb:
17691 case Intrinsic::x86_sse2_pmovmskb_128:
17692 case Intrinsic::x86_avx2_pmovmskb: {
17693 // High bits of movmskp{s|d}, pmovmskb are known zero.
17695 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
17696 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
17697 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
17698 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
17699 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
17700 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
17701 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
17702 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
17704 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
17713 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
17715 const SelectionDAG &,
17716 unsigned Depth) const {
17717 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
17718 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
17719 return Op.getValueType().getScalarType().getSizeInBits();
17725 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
17726 /// node is a GlobalAddress + offset.
17727 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
17728 const GlobalValue* &GA,
17729 int64_t &Offset) const {
17730 if (N->getOpcode() == X86ISD::Wrapper) {
17731 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
17732 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
17733 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
17737 return TargetLowering::isGAPlusOffset(N, GA, Offset);
17740 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
17741 /// same as extracting the high 128-bit part of 256-bit vector and then
17742 /// inserting the result into the low part of a new 256-bit vector
17743 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
17744 EVT VT = SVOp->getValueType(0);
17745 unsigned NumElems = VT.getVectorNumElements();
17747 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17748 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
17749 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17750 SVOp->getMaskElt(j) >= 0)
17756 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
17757 /// same as extracting the low 128-bit part of 256-bit vector and then
17758 /// inserting the result into the high part of a new 256-bit vector
17759 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
17760 EVT VT = SVOp->getValueType(0);
17761 unsigned NumElems = VT.getVectorNumElements();
17763 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17764 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
17765 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17766 SVOp->getMaskElt(j) >= 0)
17772 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
17773 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
17774 TargetLowering::DAGCombinerInfo &DCI,
17775 const X86Subtarget* Subtarget) {
17777 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17778 SDValue V1 = SVOp->getOperand(0);
17779 SDValue V2 = SVOp->getOperand(1);
17780 EVT VT = SVOp->getValueType(0);
17781 unsigned NumElems = VT.getVectorNumElements();
17783 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
17784 V2.getOpcode() == ISD::CONCAT_VECTORS) {
17788 // V UNDEF BUILD_VECTOR UNDEF
17790 // CONCAT_VECTOR CONCAT_VECTOR
17793 // RESULT: V + zero extended
17795 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
17796 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
17797 V1.getOperand(1).getOpcode() != ISD::UNDEF)
17800 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
17803 // To match the shuffle mask, the first half of the mask should
17804 // be exactly the first vector, and all the rest a splat with the
17805 // first element of the second one.
17806 for (unsigned i = 0; i != NumElems/2; ++i)
17807 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
17808 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
17811 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
17812 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
17813 if (Ld->hasNUsesOfValue(1, 0)) {
17814 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
17815 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
17817 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
17819 Ld->getPointerInfo(),
17820 Ld->getAlignment(),
17821 false/*isVolatile*/, true/*ReadMem*/,
17822 false/*WriteMem*/);
17824 // Make sure the newly-created LOAD is in the same position as Ld in
17825 // terms of dependency. We create a TokenFactor for Ld and ResNode,
17826 // and update uses of Ld's output chain to use the TokenFactor.
17827 if (Ld->hasAnyUseOfValue(1)) {
17828 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17829 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
17830 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
17831 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
17832 SDValue(ResNode.getNode(), 1));
17835 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
17839 // Emit a zeroed vector and insert the desired subvector on its
17841 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17842 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
17843 return DCI.CombineTo(N, InsV);
17846 //===--------------------------------------------------------------------===//
17847 // Combine some shuffles into subvector extracts and inserts:
17850 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17851 if (isShuffleHigh128VectorInsertLow(SVOp)) {
17852 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
17853 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
17854 return DCI.CombineTo(N, InsV);
17857 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17858 if (isShuffleLow128VectorInsertHigh(SVOp)) {
17859 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
17860 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
17861 return DCI.CombineTo(N, InsV);
17867 /// PerformShuffleCombine - Performs several different shuffle combines.
17868 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
17869 TargetLowering::DAGCombinerInfo &DCI,
17870 const X86Subtarget *Subtarget) {
17872 SDValue N0 = N->getOperand(0);
17873 SDValue N1 = N->getOperand(1);
17874 EVT VT = N->getValueType(0);
17876 // Don't create instructions with illegal types after legalize types has run.
17877 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17878 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
17881 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
17882 if (Subtarget->hasFp256() && VT.is256BitVector() &&
17883 N->getOpcode() == ISD::VECTOR_SHUFFLE)
17884 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
17886 // During Type Legalization, when promoting illegal vector types,
17887 // the backend might introduce new shuffle dag nodes and bitcasts.
17889 // This code performs the following transformation:
17890 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
17891 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
17893 // We do this only if both the bitcast and the BINOP dag nodes have
17894 // one use. Also, perform this transformation only if the new binary
17895 // operation is legal. This is to avoid introducing dag nodes that
17896 // potentially need to be further expanded (or custom lowered) into a
17897 // less optimal sequence of dag nodes.
17898 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
17899 N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
17900 N0.getOpcode() == ISD::BITCAST) {
17901 SDValue BC0 = N0.getOperand(0);
17902 EVT SVT = BC0.getValueType();
17903 unsigned Opcode = BC0.getOpcode();
17904 unsigned NumElts = VT.getVectorNumElements();
17906 if (BC0.hasOneUse() && SVT.isVector() &&
17907 SVT.getVectorNumElements() * 2 == NumElts &&
17908 TLI.isOperationLegal(Opcode, VT)) {
17909 bool CanFold = false;
17921 unsigned SVTNumElts = SVT.getVectorNumElements();
17922 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17923 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
17924 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
17925 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
17926 CanFold = SVOp->getMaskElt(i) < 0;
17929 SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
17930 SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
17931 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
17932 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
17937 // Only handle 128 wide vector from here on.
17938 if (!VT.is128BitVector())
17941 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
17942 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
17943 // consecutive, non-overlapping, and in the right order.
17944 SmallVector<SDValue, 16> Elts;
17945 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
17946 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
17948 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
17951 /// PerformTruncateCombine - Converts truncate operation to
17952 /// a sequence of vector shuffle operations.
17953 /// It is possible when we truncate 256-bit vector to 128-bit vector
17954 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
17955 TargetLowering::DAGCombinerInfo &DCI,
17956 const X86Subtarget *Subtarget) {
17960 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
17961 /// specific shuffle of a load can be folded into a single element load.
17962 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
17963 /// shuffles have been customed lowered so we need to handle those here.
17964 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
17965 TargetLowering::DAGCombinerInfo &DCI) {
17966 if (DCI.isBeforeLegalizeOps())
17969 SDValue InVec = N->getOperand(0);
17970 SDValue EltNo = N->getOperand(1);
17972 if (!isa<ConstantSDNode>(EltNo))
17975 EVT VT = InVec.getValueType();
17977 bool HasShuffleIntoBitcast = false;
17978 if (InVec.getOpcode() == ISD::BITCAST) {
17979 // Don't duplicate a load with other uses.
17980 if (!InVec.hasOneUse())
17982 EVT BCVT = InVec.getOperand(0).getValueType();
17983 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
17985 InVec = InVec.getOperand(0);
17986 HasShuffleIntoBitcast = true;
17989 if (!isTargetShuffle(InVec.getOpcode()))
17992 // Don't duplicate a load with other uses.
17993 if (!InVec.hasOneUse())
17996 SmallVector<int, 16> ShuffleMask;
17998 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
18002 // Select the input vector, guarding against out of range extract vector.
18003 unsigned NumElems = VT.getVectorNumElements();
18004 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
18005 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
18006 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
18007 : InVec.getOperand(1);
18009 // If inputs to shuffle are the same for both ops, then allow 2 uses
18010 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
18012 if (LdNode.getOpcode() == ISD::BITCAST) {
18013 // Don't duplicate a load with other uses.
18014 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
18017 AllowedUses = 1; // only allow 1 load use if we have a bitcast
18018 LdNode = LdNode.getOperand(0);
18021 if (!ISD::isNormalLoad(LdNode.getNode()))
18024 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
18026 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
18029 if (HasShuffleIntoBitcast) {
18030 // If there's a bitcast before the shuffle, check if the load type and
18031 // alignment is valid.
18032 unsigned Align = LN0->getAlignment();
18033 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18034 unsigned NewAlign = TLI.getDataLayout()->
18035 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
18037 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
18041 // All checks match so transform back to vector_shuffle so that DAG combiner
18042 // can finish the job
18045 // Create shuffle node taking into account the case that its a unary shuffle
18046 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
18047 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
18048 InVec.getOperand(0), Shuffle,
18050 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
18051 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
18055 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
18056 /// generation and convert it from being a bunch of shuffles and extracts
18057 /// to a simple store and scalar loads to extract the elements.
18058 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
18059 TargetLowering::DAGCombinerInfo &DCI) {
18060 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
18061 if (NewOp.getNode())
18064 SDValue InputVector = N->getOperand(0);
18066 // Detect whether we are trying to convert from mmx to i32 and the bitcast
18067 // from mmx to v2i32 has a single usage.
18068 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
18069 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
18070 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
18071 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
18072 N->getValueType(0),
18073 InputVector.getNode()->getOperand(0));
18075 // Only operate on vectors of 4 elements, where the alternative shuffling
18076 // gets to be more expensive.
18077 if (InputVector.getValueType() != MVT::v4i32)
18080 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
18081 // single use which is a sign-extend or zero-extend, and all elements are
18083 SmallVector<SDNode *, 4> Uses;
18084 unsigned ExtractedElements = 0;
18085 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
18086 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
18087 if (UI.getUse().getResNo() != InputVector.getResNo())
18090 SDNode *Extract = *UI;
18091 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
18094 if (Extract->getValueType(0) != MVT::i32)
18096 if (!Extract->hasOneUse())
18098 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
18099 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
18101 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
18104 // Record which element was extracted.
18105 ExtractedElements |=
18106 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
18108 Uses.push_back(Extract);
18111 // If not all the elements were used, this may not be worthwhile.
18112 if (ExtractedElements != 15)
18115 // Ok, we've now decided to do the transformation.
18116 SDLoc dl(InputVector);
18118 // Store the value to a temporary stack slot.
18119 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
18120 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
18121 MachinePointerInfo(), false, false, 0);
18123 // Replace each use (extract) with a load of the appropriate element.
18124 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
18125 UE = Uses.end(); UI != UE; ++UI) {
18126 SDNode *Extract = *UI;
18128 // cOMpute the element's address.
18129 SDValue Idx = Extract->getOperand(1);
18131 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
18132 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
18133 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18134 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
18136 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
18137 StackPtr, OffsetVal);
18139 // Load the scalar.
18140 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
18141 ScalarAddr, MachinePointerInfo(),
18142 false, false, false, 0);
18144 // Replace the exact with the load.
18145 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
18148 // The replacement was made in place; don't return anything.
18152 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
18153 static std::pair<unsigned, bool>
18154 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
18155 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
18156 if (!VT.isVector())
18157 return std::make_pair(0, false);
18159 bool NeedSplit = false;
18160 switch (VT.getSimpleVT().SimpleTy) {
18161 default: return std::make_pair(0, false);
18165 if (!Subtarget->hasAVX2())
18167 if (!Subtarget->hasAVX())
18168 return std::make_pair(0, false);
18173 if (!Subtarget->hasSSE2())
18174 return std::make_pair(0, false);
18177 // SSE2 has only a small subset of the operations.
18178 bool hasUnsigned = Subtarget->hasSSE41() ||
18179 (Subtarget->hasSSE2() && VT == MVT::v16i8);
18180 bool hasSigned = Subtarget->hasSSE41() ||
18181 (Subtarget->hasSSE2() && VT == MVT::v8i16);
18183 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18186 // Check for x CC y ? x : y.
18187 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
18188 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
18193 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
18196 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
18199 Opc = hasSigned ? X86ISD::SMIN : 0; break;
18202 Opc = hasSigned ? X86ISD::SMAX : 0; break;
18204 // Check for x CC y ? y : x -- a min/max with reversed arms.
18205 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
18206 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
18211 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
18214 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
18217 Opc = hasSigned ? X86ISD::SMAX : 0; break;
18220 Opc = hasSigned ? X86ISD::SMIN : 0; break;
18224 return std::make_pair(Opc, NeedSplit);
18228 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
18229 const X86Subtarget *Subtarget) {
18231 SDValue Cond = N->getOperand(0);
18232 SDValue LHS = N->getOperand(1);
18233 SDValue RHS = N->getOperand(2);
18235 if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
18236 SDValue CondSrc = Cond->getOperand(0);
18237 if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
18238 Cond = CondSrc->getOperand(0);
18241 MVT VT = N->getSimpleValueType(0);
18242 MVT EltVT = VT.getVectorElementType();
18243 unsigned NumElems = VT.getVectorNumElements();
18244 // There is no blend with immediate in AVX-512.
18245 if (VT.is512BitVector())
18248 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
18250 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
18253 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
18256 unsigned MaskValue = 0;
18257 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
18260 SmallVector<int, 8> ShuffleMask(NumElems, -1);
18261 for (unsigned i = 0; i < NumElems; ++i) {
18262 // Be sure we emit undef where we can.
18263 if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
18264 ShuffleMask[i] = -1;
18266 ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
18269 return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
18272 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
18274 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
18275 TargetLowering::DAGCombinerInfo &DCI,
18276 const X86Subtarget *Subtarget) {
18278 SDValue Cond = N->getOperand(0);
18279 // Get the LHS/RHS of the select.
18280 SDValue LHS = N->getOperand(1);
18281 SDValue RHS = N->getOperand(2);
18282 EVT VT = LHS.getValueType();
18283 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18285 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
18286 // instructions match the semantics of the common C idiom x<y?x:y but not
18287 // x<=y?x:y, because of how they handle negative zero (which can be
18288 // ignored in unsafe-math mode).
18289 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
18290 VT != MVT::f80 && TLI.isTypeLegal(VT) &&
18291 (Subtarget->hasSSE2() ||
18292 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
18293 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18295 unsigned Opcode = 0;
18296 // Check for x CC y ? x : y.
18297 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
18298 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
18302 // Converting this to a min would handle NaNs incorrectly, and swapping
18303 // the operands would cause it to handle comparisons between positive
18304 // and negative zero incorrectly.
18305 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
18306 if (!DAG.getTarget().Options.UnsafeFPMath &&
18307 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
18309 std::swap(LHS, RHS);
18311 Opcode = X86ISD::FMIN;
18314 // Converting this to a min would handle comparisons between positive
18315 // and negative zero incorrectly.
18316 if (!DAG.getTarget().Options.UnsafeFPMath &&
18317 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
18319 Opcode = X86ISD::FMIN;
18322 // Converting this to a min would handle both negative zeros and NaNs
18323 // incorrectly, but we can swap the operands to fix both.
18324 std::swap(LHS, RHS);
18328 Opcode = X86ISD::FMIN;
18332 // Converting this to a max would handle comparisons between positive
18333 // and negative zero incorrectly.
18334 if (!DAG.getTarget().Options.UnsafeFPMath &&
18335 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
18337 Opcode = X86ISD::FMAX;
18340 // Converting this to a max would handle NaNs incorrectly, and swapping
18341 // the operands would cause it to handle comparisons between positive
18342 // and negative zero incorrectly.
18343 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
18344 if (!DAG.getTarget().Options.UnsafeFPMath &&
18345 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
18347 std::swap(LHS, RHS);
18349 Opcode = X86ISD::FMAX;
18352 // Converting this to a max would handle both negative zeros and NaNs
18353 // incorrectly, but we can swap the operands to fix both.
18354 std::swap(LHS, RHS);
18358 Opcode = X86ISD::FMAX;
18361 // Check for x CC y ? y : x -- a min/max with reversed arms.
18362 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
18363 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
18367 // Converting this to a min would handle comparisons between positive
18368 // and negative zero incorrectly, and swapping the operands would
18369 // cause it to handle NaNs incorrectly.
18370 if (!DAG.getTarget().Options.UnsafeFPMath &&
18371 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
18372 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
18374 std::swap(LHS, RHS);
18376 Opcode = X86ISD::FMIN;
18379 // Converting this to a min would handle NaNs incorrectly.
18380 if (!DAG.getTarget().Options.UnsafeFPMath &&
18381 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
18383 Opcode = X86ISD::FMIN;
18386 // Converting this to a min would handle both negative zeros and NaNs
18387 // incorrectly, but we can swap the operands to fix both.
18388 std::swap(LHS, RHS);
18392 Opcode = X86ISD::FMIN;
18396 // Converting this to a max would handle NaNs incorrectly.
18397 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
18399 Opcode = X86ISD::FMAX;
18402 // Converting this to a max would handle comparisons between positive
18403 // and negative zero incorrectly, and swapping the operands would
18404 // cause it to handle NaNs incorrectly.
18405 if (!DAG.getTarget().Options.UnsafeFPMath &&
18406 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
18407 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
18409 std::swap(LHS, RHS);
18411 Opcode = X86ISD::FMAX;
18414 // Converting this to a max would handle both negative zeros and NaNs
18415 // incorrectly, but we can swap the operands to fix both.
18416 std::swap(LHS, RHS);
18420 Opcode = X86ISD::FMAX;
18426 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
18429 EVT CondVT = Cond.getValueType();
18430 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
18431 CondVT.getVectorElementType() == MVT::i1) {
18432 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
18433 // lowering on AVX-512. In this case we convert it to
18434 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
18435 // The same situation for all 128 and 256-bit vectors of i8 and i16
18436 EVT OpVT = LHS.getValueType();
18437 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
18438 (OpVT.getVectorElementType() == MVT::i8 ||
18439 OpVT.getVectorElementType() == MVT::i16)) {
18440 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
18441 DCI.AddToWorklist(Cond.getNode());
18442 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
18445 // If this is a select between two integer constants, try to do some
18447 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
18448 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
18449 // Don't do this for crazy integer types.
18450 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
18451 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
18452 // so that TrueC (the true value) is larger than FalseC.
18453 bool NeedsCondInvert = false;
18455 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
18456 // Efficiently invertible.
18457 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
18458 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
18459 isa<ConstantSDNode>(Cond.getOperand(1))))) {
18460 NeedsCondInvert = true;
18461 std::swap(TrueC, FalseC);
18464 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
18465 if (FalseC->getAPIntValue() == 0 &&
18466 TrueC->getAPIntValue().isPowerOf2()) {
18467 if (NeedsCondInvert) // Invert the condition if needed.
18468 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18469 DAG.getConstant(1, Cond.getValueType()));
18471 // Zero extend the condition if needed.
18472 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
18474 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18475 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
18476 DAG.getConstant(ShAmt, MVT::i8));
18479 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
18480 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18481 if (NeedsCondInvert) // Invert the condition if needed.
18482 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18483 DAG.getConstant(1, Cond.getValueType()));
18485 // Zero extend the condition if needed.
18486 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18487 FalseC->getValueType(0), Cond);
18488 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18489 SDValue(FalseC, 0));
18492 // Optimize cases that will turn into an LEA instruction. This requires
18493 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18494 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18495 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18496 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18498 bool isFastMultiplier = false;
18500 switch ((unsigned char)Diff) {
18502 case 1: // result = add base, cond
18503 case 2: // result = lea base( , cond*2)
18504 case 3: // result = lea base(cond, cond*2)
18505 case 4: // result = lea base( , cond*4)
18506 case 5: // result = lea base(cond, cond*4)
18507 case 8: // result = lea base( , cond*8)
18508 case 9: // result = lea base(cond, cond*8)
18509 isFastMultiplier = true;
18514 if (isFastMultiplier) {
18515 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18516 if (NeedsCondInvert) // Invert the condition if needed.
18517 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18518 DAG.getConstant(1, Cond.getValueType()));
18520 // Zero extend the condition if needed.
18521 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18523 // Scale the condition by the difference.
18525 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18526 DAG.getConstant(Diff, Cond.getValueType()));
18528 // Add the base if non-zero.
18529 if (FalseC->getAPIntValue() != 0)
18530 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18531 SDValue(FalseC, 0));
18538 // Canonicalize max and min:
18539 // (x > y) ? x : y -> (x >= y) ? x : y
18540 // (x < y) ? x : y -> (x <= y) ? x : y
18541 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
18542 // the need for an extra compare
18543 // against zero. e.g.
18544 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
18546 // testl %edi, %edi
18548 // cmovgl %edi, %eax
18552 // cmovsl %eax, %edi
18553 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
18554 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
18555 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
18556 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18561 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
18562 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
18563 Cond.getOperand(0), Cond.getOperand(1), NewCC);
18564 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
18569 // Early exit check
18570 if (!TLI.isTypeLegal(VT))
18573 // Match VSELECTs into subs with unsigned saturation.
18574 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
18575 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
18576 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
18577 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
18578 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18580 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
18581 // left side invert the predicate to simplify logic below.
18583 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
18585 CC = ISD::getSetCCInverse(CC, true);
18586 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
18590 if (Other.getNode() && Other->getNumOperands() == 2 &&
18591 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
18592 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
18593 SDValue CondRHS = Cond->getOperand(1);
18595 // Look for a general sub with unsigned saturation first.
18596 // x >= y ? x-y : 0 --> subus x, y
18597 // x > y ? x-y : 0 --> subus x, y
18598 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
18599 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
18600 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
18602 // If the RHS is a constant we have to reverse the const canonicalization.
18603 // x > C-1 ? x+-C : 0 --> subus x, C
18604 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
18605 isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
18606 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
18607 if (CondRHS.getConstantOperandVal(0) == -A-1)
18608 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
18609 DAG.getConstant(-A, VT));
18612 // Another special case: If C was a sign bit, the sub has been
18613 // canonicalized into a xor.
18614 // FIXME: Would it be better to use computeKnownBits to determine whether
18615 // it's safe to decanonicalize the xor?
18616 // x s< 0 ? x^C : 0 --> subus x, C
18617 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
18618 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
18619 isSplatVector(OpRHS.getNode())) {
18620 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
18622 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
18627 // Try to match a min/max vector operation.
18628 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
18629 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
18630 unsigned Opc = ret.first;
18631 bool NeedSplit = ret.second;
18633 if (Opc && NeedSplit) {
18634 unsigned NumElems = VT.getVectorNumElements();
18635 // Extract the LHS vectors
18636 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
18637 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
18639 // Extract the RHS vectors
18640 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
18641 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
18643 // Create min/max for each subvector
18644 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
18645 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
18647 // Merge the result
18648 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
18650 return DAG.getNode(Opc, DL, VT, LHS, RHS);
18653 // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
18654 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
18655 // Check if SETCC has already been promoted
18656 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
18657 // Check that condition value type matches vselect operand type
18660 assert(Cond.getValueType().isVector() &&
18661 "vector select expects a vector selector!");
18663 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
18664 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
18666 if (!TValIsAllOnes && !FValIsAllZeros) {
18667 // Try invert the condition if true value is not all 1s and false value
18669 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
18670 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
18672 if (TValIsAllZeros || FValIsAllOnes) {
18673 SDValue CC = Cond.getOperand(2);
18674 ISD::CondCode NewCC =
18675 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
18676 Cond.getOperand(0).getValueType().isInteger());
18677 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
18678 std::swap(LHS, RHS);
18679 TValIsAllOnes = FValIsAllOnes;
18680 FValIsAllZeros = TValIsAllZeros;
18684 if (TValIsAllOnes || FValIsAllZeros) {
18687 if (TValIsAllOnes && FValIsAllZeros)
18689 else if (TValIsAllOnes)
18690 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
18691 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
18692 else if (FValIsAllZeros)
18693 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
18694 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
18696 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
18700 // Try to fold this VSELECT into a MOVSS/MOVSD
18701 if (N->getOpcode() == ISD::VSELECT &&
18702 Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
18703 if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
18704 (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
18705 bool CanFold = false;
18706 unsigned NumElems = Cond.getNumOperands();
18710 if (isZero(Cond.getOperand(0))) {
18713 // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
18714 // fold (vselect <0,-1> -> (movsd A, B)
18715 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
18716 CanFold = isAllOnes(Cond.getOperand(i));
18717 } else if (isAllOnes(Cond.getOperand(0))) {
18721 // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
18722 // fold (vselect <-1,0> -> (movsd B, A)
18723 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
18724 CanFold = isZero(Cond.getOperand(i));
18728 if (VT == MVT::v4i32 || VT == MVT::v4f32)
18729 return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
18730 return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
18733 if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
18734 // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
18735 // (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
18736 // (v2i64 (bitcast B)))))
18738 // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
18739 // (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
18740 // (v2f64 (bitcast B)))))
18742 // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
18743 // (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
18744 // (v2i64 (bitcast A)))))
18746 // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
18747 // (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
18748 // (v2f64 (bitcast A)))))
18750 CanFold = (isZero(Cond.getOperand(0)) &&
18751 isZero(Cond.getOperand(1)) &&
18752 isAllOnes(Cond.getOperand(2)) &&
18753 isAllOnes(Cond.getOperand(3)));
18755 if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
18756 isAllOnes(Cond.getOperand(1)) &&
18757 isZero(Cond.getOperand(2)) &&
18758 isZero(Cond.getOperand(3))) {
18760 std::swap(LHS, RHS);
18764 EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
18765 SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
18766 SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
18767 SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
18769 return DAG.getNode(ISD::BITCAST, DL, VT, Select);
18775 // If we know that this node is legal then we know that it is going to be
18776 // matched by one of the SSE/AVX BLEND instructions. These instructions only
18777 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
18778 // to simplify previous instructions.
18779 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
18780 !DCI.isBeforeLegalize() &&
18781 // We explicitly check against v8i16 and v16i16 because, although
18782 // they're marked as Custom, they might only be legal when Cond is a
18783 // build_vector of constants. This will be taken care in a later
18785 (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
18786 VT != MVT::v8i16)) {
18787 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
18789 // Don't optimize vector selects that map to mask-registers.
18793 // Check all uses of that condition operand to check whether it will be
18794 // consumed by non-BLEND instructions, which may depend on all bits are set
18796 for (SDNode::use_iterator I = Cond->use_begin(),
18797 E = Cond->use_end(); I != E; ++I)
18798 if (I->getOpcode() != ISD::VSELECT)
18799 // TODO: Add other opcodes eventually lowered into BLEND.
18802 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
18803 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
18805 APInt KnownZero, KnownOne;
18806 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
18807 DCI.isBeforeLegalizeOps());
18808 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
18809 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
18810 DCI.CommitTargetLoweringOpt(TLO);
18813 // We should generate an X86ISD::BLENDI from a vselect if its argument
18814 // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
18815 // constants. This specific pattern gets generated when we split a
18816 // selector for a 512 bit vector in a machine without AVX512 (but with
18817 // 256-bit vectors), during legalization:
18819 // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
18821 // Iff we find this pattern and the build_vectors are built from
18822 // constants, we translate the vselect into a shuffle_vector that we
18823 // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
18824 if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
18825 SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
18826 if (Shuffle.getNode())
18833 // Check whether a boolean test is testing a boolean value generated by
18834 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
18837 // Simplify the following patterns:
18838 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
18839 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
18840 // to (Op EFLAGS Cond)
18842 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
18843 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
18844 // to (Op EFLAGS !Cond)
18846 // where Op could be BRCOND or CMOV.
18848 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
18849 // Quit if not CMP and SUB with its value result used.
18850 if (Cmp.getOpcode() != X86ISD::CMP &&
18851 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
18854 // Quit if not used as a boolean value.
18855 if (CC != X86::COND_E && CC != X86::COND_NE)
18858 // Check CMP operands. One of them should be 0 or 1 and the other should be
18859 // an SetCC or extended from it.
18860 SDValue Op1 = Cmp.getOperand(0);
18861 SDValue Op2 = Cmp.getOperand(1);
18864 const ConstantSDNode* C = nullptr;
18865 bool needOppositeCond = (CC == X86::COND_E);
18866 bool checkAgainstTrue = false; // Is it a comparison against 1?
18868 if ((C = dyn_cast<ConstantSDNode>(Op1)))
18870 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
18872 else // Quit if all operands are not constants.
18875 if (C->getZExtValue() == 1) {
18876 needOppositeCond = !needOppositeCond;
18877 checkAgainstTrue = true;
18878 } else if (C->getZExtValue() != 0)
18879 // Quit if the constant is neither 0 or 1.
18882 bool truncatedToBoolWithAnd = false;
18883 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
18884 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
18885 SetCC.getOpcode() == ISD::TRUNCATE ||
18886 SetCC.getOpcode() == ISD::AND) {
18887 if (SetCC.getOpcode() == ISD::AND) {
18889 ConstantSDNode *CS;
18890 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
18891 CS->getZExtValue() == 1)
18893 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
18894 CS->getZExtValue() == 1)
18898 SetCC = SetCC.getOperand(OpIdx);
18899 truncatedToBoolWithAnd = true;
18901 SetCC = SetCC.getOperand(0);
18904 switch (SetCC.getOpcode()) {
18905 case X86ISD::SETCC_CARRY:
18906 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
18907 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
18908 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
18909 // truncated to i1 using 'and'.
18910 if (checkAgainstTrue && !truncatedToBoolWithAnd)
18912 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
18913 "Invalid use of SETCC_CARRY!");
18915 case X86ISD::SETCC:
18916 // Set the condition code or opposite one if necessary.
18917 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
18918 if (needOppositeCond)
18919 CC = X86::GetOppositeBranchCondition(CC);
18920 return SetCC.getOperand(1);
18921 case X86ISD::CMOV: {
18922 // Check whether false/true value has canonical one, i.e. 0 or 1.
18923 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
18924 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
18925 // Quit if true value is not a constant.
18928 // Quit if false value is not a constant.
18930 SDValue Op = SetCC.getOperand(0);
18931 // Skip 'zext' or 'trunc' node.
18932 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
18933 Op.getOpcode() == ISD::TRUNCATE)
18934 Op = Op.getOperand(0);
18935 // A special case for rdrand/rdseed, where 0 is set if false cond is
18937 if ((Op.getOpcode() != X86ISD::RDRAND &&
18938 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
18941 // Quit if false value is not the constant 0 or 1.
18942 bool FValIsFalse = true;
18943 if (FVal && FVal->getZExtValue() != 0) {
18944 if (FVal->getZExtValue() != 1)
18946 // If FVal is 1, opposite cond is needed.
18947 needOppositeCond = !needOppositeCond;
18948 FValIsFalse = false;
18950 // Quit if TVal is not the constant opposite of FVal.
18951 if (FValIsFalse && TVal->getZExtValue() != 1)
18953 if (!FValIsFalse && TVal->getZExtValue() != 0)
18955 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
18956 if (needOppositeCond)
18957 CC = X86::GetOppositeBranchCondition(CC);
18958 return SetCC.getOperand(3);
18965 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
18966 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
18967 TargetLowering::DAGCombinerInfo &DCI,
18968 const X86Subtarget *Subtarget) {
18971 // If the flag operand isn't dead, don't touch this CMOV.
18972 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
18975 SDValue FalseOp = N->getOperand(0);
18976 SDValue TrueOp = N->getOperand(1);
18977 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
18978 SDValue Cond = N->getOperand(3);
18980 if (CC == X86::COND_E || CC == X86::COND_NE) {
18981 switch (Cond.getOpcode()) {
18985 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
18986 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
18987 return (CC == X86::COND_E) ? FalseOp : TrueOp;
18993 Flags = checkBoolTestSetCCCombine(Cond, CC);
18994 if (Flags.getNode() &&
18995 // Extra check as FCMOV only supports a subset of X86 cond.
18996 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
18997 SDValue Ops[] = { FalseOp, TrueOp,
18998 DAG.getConstant(CC, MVT::i8), Flags };
18999 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
19002 // If this is a select between two integer constants, try to do some
19003 // optimizations. Note that the operands are ordered the opposite of SELECT
19005 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
19006 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
19007 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
19008 // larger than FalseC (the false value).
19009 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
19010 CC = X86::GetOppositeBranchCondition(CC);
19011 std::swap(TrueC, FalseC);
19012 std::swap(TrueOp, FalseOp);
19015 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
19016 // This is efficient for any integer data type (including i8/i16) and
19018 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
19019 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
19020 DAG.getConstant(CC, MVT::i8), Cond);
19022 // Zero extend the condition if needed.
19023 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
19025 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
19026 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
19027 DAG.getConstant(ShAmt, MVT::i8));
19028 if (N->getNumValues() == 2) // Dead flag value?
19029 return DCI.CombineTo(N, Cond, SDValue());
19033 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
19034 // for any integer data type, including i8/i16.
19035 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
19036 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
19037 DAG.getConstant(CC, MVT::i8), Cond);
19039 // Zero extend the condition if needed.
19040 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
19041 FalseC->getValueType(0), Cond);
19042 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19043 SDValue(FalseC, 0));
19045 if (N->getNumValues() == 2) // Dead flag value?
19046 return DCI.CombineTo(N, Cond, SDValue());
19050 // Optimize cases that will turn into an LEA instruction. This requires
19051 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
19052 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
19053 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
19054 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
19056 bool isFastMultiplier = false;
19058 switch ((unsigned char)Diff) {
19060 case 1: // result = add base, cond
19061 case 2: // result = lea base( , cond*2)
19062 case 3: // result = lea base(cond, cond*2)
19063 case 4: // result = lea base( , cond*4)
19064 case 5: // result = lea base(cond, cond*4)
19065 case 8: // result = lea base( , cond*8)
19066 case 9: // result = lea base(cond, cond*8)
19067 isFastMultiplier = true;
19072 if (isFastMultiplier) {
19073 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
19074 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
19075 DAG.getConstant(CC, MVT::i8), Cond);
19076 // Zero extend the condition if needed.
19077 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
19079 // Scale the condition by the difference.
19081 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
19082 DAG.getConstant(Diff, Cond.getValueType()));
19084 // Add the base if non-zero.
19085 if (FalseC->getAPIntValue() != 0)
19086 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19087 SDValue(FalseC, 0));
19088 if (N->getNumValues() == 2) // Dead flag value?
19089 return DCI.CombineTo(N, Cond, SDValue());
19096 // Handle these cases:
19097 // (select (x != c), e, c) -> select (x != c), e, x),
19098 // (select (x == c), c, e) -> select (x == c), x, e)
19099 // where the c is an integer constant, and the "select" is the combination
19100 // of CMOV and CMP.
19102 // The rationale for this change is that the conditional-move from a constant
19103 // needs two instructions, however, conditional-move from a register needs
19104 // only one instruction.
19106 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
19107 // some instruction-combining opportunities. This opt needs to be
19108 // postponed as late as possible.
19110 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
19111 // the DCI.xxxx conditions are provided to postpone the optimization as
19112 // late as possible.
19114 ConstantSDNode *CmpAgainst = nullptr;
19115 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
19116 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
19117 !isa<ConstantSDNode>(Cond.getOperand(0))) {
19119 if (CC == X86::COND_NE &&
19120 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
19121 CC = X86::GetOppositeBranchCondition(CC);
19122 std::swap(TrueOp, FalseOp);
19125 if (CC == X86::COND_E &&
19126 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
19127 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
19128 DAG.getConstant(CC, MVT::i8), Cond };
19129 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
19137 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
19138 const X86Subtarget *Subtarget) {
19139 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
19141 default: return SDValue();
19142 // SSE/AVX/AVX2 blend intrinsics.
19143 case Intrinsic::x86_avx2_pblendvb:
19144 case Intrinsic::x86_avx2_pblendw:
19145 case Intrinsic::x86_avx2_pblendd_128:
19146 case Intrinsic::x86_avx2_pblendd_256:
19147 // Don't try to simplify this intrinsic if we don't have AVX2.
19148 if (!Subtarget->hasAVX2())
19151 case Intrinsic::x86_avx_blend_pd_256:
19152 case Intrinsic::x86_avx_blend_ps_256:
19153 case Intrinsic::x86_avx_blendv_pd_256:
19154 case Intrinsic::x86_avx_blendv_ps_256:
19155 // Don't try to simplify this intrinsic if we don't have AVX.
19156 if (!Subtarget->hasAVX())
19159 case Intrinsic::x86_sse41_pblendw:
19160 case Intrinsic::x86_sse41_blendpd:
19161 case Intrinsic::x86_sse41_blendps:
19162 case Intrinsic::x86_sse41_blendvps:
19163 case Intrinsic::x86_sse41_blendvpd:
19164 case Intrinsic::x86_sse41_pblendvb: {
19165 SDValue Op0 = N->getOperand(1);
19166 SDValue Op1 = N->getOperand(2);
19167 SDValue Mask = N->getOperand(3);
19169 // Don't try to simplify this intrinsic if we don't have SSE4.1.
19170 if (!Subtarget->hasSSE41())
19173 // fold (blend A, A, Mask) -> A
19176 // fold (blend A, B, allZeros) -> A
19177 if (ISD::isBuildVectorAllZeros(Mask.getNode()))
19179 // fold (blend A, B, allOnes) -> B
19180 if (ISD::isBuildVectorAllOnes(Mask.getNode()))
19183 // Simplify the case where the mask is a constant i32 value.
19184 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
19185 if (C->isNullValue())
19187 if (C->isAllOnesValue())
19192 // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
19193 case Intrinsic::x86_sse2_psrai_w:
19194 case Intrinsic::x86_sse2_psrai_d:
19195 case Intrinsic::x86_avx2_psrai_w:
19196 case Intrinsic::x86_avx2_psrai_d:
19197 case Intrinsic::x86_sse2_psra_w:
19198 case Intrinsic::x86_sse2_psra_d:
19199 case Intrinsic::x86_avx2_psra_w:
19200 case Intrinsic::x86_avx2_psra_d: {
19201 SDValue Op0 = N->getOperand(1);
19202 SDValue Op1 = N->getOperand(2);
19203 EVT VT = Op0.getValueType();
19204 assert(VT.isVector() && "Expected a vector type!");
19206 if (isa<BuildVectorSDNode>(Op1))
19207 Op1 = Op1.getOperand(0);
19209 if (!isa<ConstantSDNode>(Op1))
19212 EVT SVT = VT.getVectorElementType();
19213 unsigned SVTBits = SVT.getSizeInBits();
19215 ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
19216 const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
19217 uint64_t ShAmt = C.getZExtValue();
19219 // Don't try to convert this shift into a ISD::SRA if the shift
19220 // count is bigger than or equal to the element size.
19221 if (ShAmt >= SVTBits)
19224 // Trivial case: if the shift count is zero, then fold this
19225 // into the first operand.
19229 // Replace this packed shift intrinsic with a target independent
19231 SDValue Splat = DAG.getConstant(C, VT);
19232 return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
19237 /// PerformMulCombine - Optimize a single multiply with constant into two
19238 /// in order to implement it with two cheaper instructions, e.g.
19239 /// LEA + SHL, LEA + LEA.
19240 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
19241 TargetLowering::DAGCombinerInfo &DCI) {
19242 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
19245 EVT VT = N->getValueType(0);
19246 if (VT != MVT::i64)
19249 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
19252 uint64_t MulAmt = C->getZExtValue();
19253 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
19256 uint64_t MulAmt1 = 0;
19257 uint64_t MulAmt2 = 0;
19258 if ((MulAmt % 9) == 0) {
19260 MulAmt2 = MulAmt / 9;
19261 } else if ((MulAmt % 5) == 0) {
19263 MulAmt2 = MulAmt / 5;
19264 } else if ((MulAmt % 3) == 0) {
19266 MulAmt2 = MulAmt / 3;
19269 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
19272 if (isPowerOf2_64(MulAmt2) &&
19273 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
19274 // If second multiplifer is pow2, issue it first. We want the multiply by
19275 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
19277 std::swap(MulAmt1, MulAmt2);
19280 if (isPowerOf2_64(MulAmt1))
19281 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
19282 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
19284 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
19285 DAG.getConstant(MulAmt1, VT));
19287 if (isPowerOf2_64(MulAmt2))
19288 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
19289 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
19291 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
19292 DAG.getConstant(MulAmt2, VT));
19294 // Do not add new nodes to DAG combiner worklist.
19295 DCI.CombineTo(N, NewMul, false);
19300 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
19301 SDValue N0 = N->getOperand(0);
19302 SDValue N1 = N->getOperand(1);
19303 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
19304 EVT VT = N0.getValueType();
19306 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
19307 // since the result of setcc_c is all zero's or all ones.
19308 if (VT.isInteger() && !VT.isVector() &&
19309 N1C && N0.getOpcode() == ISD::AND &&
19310 N0.getOperand(1).getOpcode() == ISD::Constant) {
19311 SDValue N00 = N0.getOperand(0);
19312 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
19313 ((N00.getOpcode() == ISD::ANY_EXTEND ||
19314 N00.getOpcode() == ISD::ZERO_EXTEND) &&
19315 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
19316 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
19317 APInt ShAmt = N1C->getAPIntValue();
19318 Mask = Mask.shl(ShAmt);
19320 return DAG.getNode(ISD::AND, SDLoc(N), VT,
19321 N00, DAG.getConstant(Mask, VT));
19325 // Hardware support for vector shifts is sparse which makes us scalarize the
19326 // vector operations in many cases. Also, on sandybridge ADD is faster than
19328 // (shl V, 1) -> add V,V
19329 if (isSplatVector(N1.getNode())) {
19330 assert(N0.getValueType().isVector() && "Invalid vector shift type");
19331 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
19332 // We shift all of the values by one. In many cases we do not have
19333 // hardware support for this operation. This is better expressed as an ADD
19335 if (N1C && (1 == N1C->getZExtValue())) {
19336 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
19343 /// \brief Returns a vector of 0s if the node in input is a vector logical
19344 /// shift by a constant amount which is known to be bigger than or equal
19345 /// to the vector element size in bits.
19346 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
19347 const X86Subtarget *Subtarget) {
19348 EVT VT = N->getValueType(0);
19350 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
19351 (!Subtarget->hasInt256() ||
19352 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
19355 SDValue Amt = N->getOperand(1);
19357 if (isSplatVector(Amt.getNode())) {
19358 SDValue SclrAmt = Amt->getOperand(0);
19359 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
19360 APInt ShiftAmt = C->getAPIntValue();
19361 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
19363 // SSE2/AVX2 logical shifts always return a vector of 0s
19364 // if the shift amount is bigger than or equal to
19365 // the element size. The constant shift amount will be
19366 // encoded as a 8-bit immediate.
19367 if (ShiftAmt.trunc(8).uge(MaxAmount))
19368 return getZeroVector(VT, Subtarget, DAG, DL);
19375 /// PerformShiftCombine - Combine shifts.
19376 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
19377 TargetLowering::DAGCombinerInfo &DCI,
19378 const X86Subtarget *Subtarget) {
19379 if (N->getOpcode() == ISD::SHL) {
19380 SDValue V = PerformSHLCombine(N, DAG);
19381 if (V.getNode()) return V;
19384 if (N->getOpcode() != ISD::SRA) {
19385 // Try to fold this logical shift into a zero vector.
19386 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
19387 if (V.getNode()) return V;
19393 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
19394 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
19395 // and friends. Likewise for OR -> CMPNEQSS.
19396 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
19397 TargetLowering::DAGCombinerInfo &DCI,
19398 const X86Subtarget *Subtarget) {
19401 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
19402 // we're requiring SSE2 for both.
19403 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
19404 SDValue N0 = N->getOperand(0);
19405 SDValue N1 = N->getOperand(1);
19406 SDValue CMP0 = N0->getOperand(1);
19407 SDValue CMP1 = N1->getOperand(1);
19410 // The SETCCs should both refer to the same CMP.
19411 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
19414 SDValue CMP00 = CMP0->getOperand(0);
19415 SDValue CMP01 = CMP0->getOperand(1);
19416 EVT VT = CMP00.getValueType();
19418 if (VT == MVT::f32 || VT == MVT::f64) {
19419 bool ExpectingFlags = false;
19420 // Check for any users that want flags:
19421 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
19422 !ExpectingFlags && UI != UE; ++UI)
19423 switch (UI->getOpcode()) {
19428 ExpectingFlags = true;
19430 case ISD::CopyToReg:
19431 case ISD::SIGN_EXTEND:
19432 case ISD::ZERO_EXTEND:
19433 case ISD::ANY_EXTEND:
19437 if (!ExpectingFlags) {
19438 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
19439 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
19441 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
19442 X86::CondCode tmp = cc0;
19447 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
19448 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
19449 // FIXME: need symbolic constants for these magic numbers.
19450 // See X86ATTInstPrinter.cpp:printSSECC().
19451 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
19452 if (Subtarget->hasAVX512()) {
19453 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
19454 CMP01, DAG.getConstant(x86cc, MVT::i8));
19455 if (N->getValueType(0) != MVT::i1)
19456 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
19460 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
19461 CMP00.getValueType(), CMP00, CMP01,
19462 DAG.getConstant(x86cc, MVT::i8));
19464 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
19465 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
19467 if (is64BitFP && !Subtarget->is64Bit()) {
19468 // On a 32-bit target, we cannot bitcast the 64-bit float to a
19469 // 64-bit integer, since that's not a legal type. Since
19470 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
19471 // bits, but can do this little dance to extract the lowest 32 bits
19472 // and work with those going forward.
19473 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
19475 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
19477 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
19478 Vector32, DAG.getIntPtrConstant(0));
19482 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
19483 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
19484 DAG.getConstant(1, IntVT));
19485 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
19486 return OneBitOfTruth;
19494 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
19495 /// so it can be folded inside ANDNP.
19496 static bool CanFoldXORWithAllOnes(const SDNode *N) {
19497 EVT VT = N->getValueType(0);
19499 // Match direct AllOnes for 128 and 256-bit vectors
19500 if (ISD::isBuildVectorAllOnes(N))
19503 // Look through a bit convert.
19504 if (N->getOpcode() == ISD::BITCAST)
19505 N = N->getOperand(0).getNode();
19507 // Sometimes the operand may come from a insert_subvector building a 256-bit
19509 if (VT.is256BitVector() &&
19510 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
19511 SDValue V1 = N->getOperand(0);
19512 SDValue V2 = N->getOperand(1);
19514 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
19515 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
19516 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
19517 ISD::isBuildVectorAllOnes(V2.getNode()))
19524 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
19525 // register. In most cases we actually compare or select YMM-sized registers
19526 // and mixing the two types creates horrible code. This method optimizes
19527 // some of the transition sequences.
19528 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
19529 TargetLowering::DAGCombinerInfo &DCI,
19530 const X86Subtarget *Subtarget) {
19531 EVT VT = N->getValueType(0);
19532 if (!VT.is256BitVector())
19535 assert((N->getOpcode() == ISD::ANY_EXTEND ||
19536 N->getOpcode() == ISD::ZERO_EXTEND ||
19537 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
19539 SDValue Narrow = N->getOperand(0);
19540 EVT NarrowVT = Narrow->getValueType(0);
19541 if (!NarrowVT.is128BitVector())
19544 if (Narrow->getOpcode() != ISD::XOR &&
19545 Narrow->getOpcode() != ISD::AND &&
19546 Narrow->getOpcode() != ISD::OR)
19549 SDValue N0 = Narrow->getOperand(0);
19550 SDValue N1 = Narrow->getOperand(1);
19553 // The Left side has to be a trunc.
19554 if (N0.getOpcode() != ISD::TRUNCATE)
19557 // The type of the truncated inputs.
19558 EVT WideVT = N0->getOperand(0)->getValueType(0);
19562 // The right side has to be a 'trunc' or a constant vector.
19563 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
19564 bool RHSConst = (isSplatVector(N1.getNode()) &&
19565 isa<ConstantSDNode>(N1->getOperand(0)));
19566 if (!RHSTrunc && !RHSConst)
19569 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19571 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
19574 // Set N0 and N1 to hold the inputs to the new wide operation.
19575 N0 = N0->getOperand(0);
19577 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
19578 N1->getOperand(0));
19579 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
19580 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
19581 } else if (RHSTrunc) {
19582 N1 = N1->getOperand(0);
19585 // Generate the wide operation.
19586 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
19587 unsigned Opcode = N->getOpcode();
19589 case ISD::ANY_EXTEND:
19591 case ISD::ZERO_EXTEND: {
19592 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
19593 APInt Mask = APInt::getAllOnesValue(InBits);
19594 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
19595 return DAG.getNode(ISD::AND, DL, VT,
19596 Op, DAG.getConstant(Mask, VT));
19598 case ISD::SIGN_EXTEND:
19599 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
19600 Op, DAG.getValueType(NarrowVT));
19602 llvm_unreachable("Unexpected opcode");
19606 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
19607 TargetLowering::DAGCombinerInfo &DCI,
19608 const X86Subtarget *Subtarget) {
19609 EVT VT = N->getValueType(0);
19610 if (DCI.isBeforeLegalizeOps())
19613 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
19617 // Create BEXTR instructions
19618 // BEXTR is ((X >> imm) & (2**size-1))
19619 if (VT == MVT::i32 || VT == MVT::i64) {
19620 SDValue N0 = N->getOperand(0);
19621 SDValue N1 = N->getOperand(1);
19624 // Check for BEXTR.
19625 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
19626 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
19627 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
19628 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19629 if (MaskNode && ShiftNode) {
19630 uint64_t Mask = MaskNode->getZExtValue();
19631 uint64_t Shift = ShiftNode->getZExtValue();
19632 if (isMask_64(Mask)) {
19633 uint64_t MaskSize = CountPopulation_64(Mask);
19634 if (Shift + MaskSize <= VT.getSizeInBits())
19635 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
19636 DAG.getConstant(Shift | (MaskSize << 8), VT));
19644 // Want to form ANDNP nodes:
19645 // 1) In the hopes of then easily combining them with OR and AND nodes
19646 // to form PBLEND/PSIGN.
19647 // 2) To match ANDN packed intrinsics
19648 if (VT != MVT::v2i64 && VT != MVT::v4i64)
19651 SDValue N0 = N->getOperand(0);
19652 SDValue N1 = N->getOperand(1);
19655 // Check LHS for vnot
19656 if (N0.getOpcode() == ISD::XOR &&
19657 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
19658 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
19659 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
19661 // Check RHS for vnot
19662 if (N1.getOpcode() == ISD::XOR &&
19663 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
19664 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
19665 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
19670 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
19671 TargetLowering::DAGCombinerInfo &DCI,
19672 const X86Subtarget *Subtarget) {
19673 if (DCI.isBeforeLegalizeOps())
19676 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
19680 SDValue N0 = N->getOperand(0);
19681 SDValue N1 = N->getOperand(1);
19682 EVT VT = N->getValueType(0);
19684 // look for psign/blend
19685 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
19686 if (!Subtarget->hasSSSE3() ||
19687 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
19690 // Canonicalize pandn to RHS
19691 if (N0.getOpcode() == X86ISD::ANDNP)
19693 // or (and (m, y), (pandn m, x))
19694 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
19695 SDValue Mask = N1.getOperand(0);
19696 SDValue X = N1.getOperand(1);
19698 if (N0.getOperand(0) == Mask)
19699 Y = N0.getOperand(1);
19700 if (N0.getOperand(1) == Mask)
19701 Y = N0.getOperand(0);
19703 // Check to see if the mask appeared in both the AND and ANDNP and
19707 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
19708 // Look through mask bitcast.
19709 if (Mask.getOpcode() == ISD::BITCAST)
19710 Mask = Mask.getOperand(0);
19711 if (X.getOpcode() == ISD::BITCAST)
19712 X = X.getOperand(0);
19713 if (Y.getOpcode() == ISD::BITCAST)
19714 Y = Y.getOperand(0);
19716 EVT MaskVT = Mask.getValueType();
19718 // Validate that the Mask operand is a vector sra node.
19719 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
19720 // there is no psrai.b
19721 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
19722 unsigned SraAmt = ~0;
19723 if (Mask.getOpcode() == ISD::SRA) {
19724 SDValue Amt = Mask.getOperand(1);
19725 if (isSplatVector(Amt.getNode())) {
19726 SDValue SclrAmt = Amt->getOperand(0);
19727 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
19728 SraAmt = C->getZExtValue();
19730 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
19731 SDValue SraC = Mask.getOperand(1);
19732 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
19734 if ((SraAmt + 1) != EltBits)
19739 // Now we know we at least have a plendvb with the mask val. See if
19740 // we can form a psignb/w/d.
19741 // psign = x.type == y.type == mask.type && y = sub(0, x);
19742 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
19743 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
19744 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
19745 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
19746 "Unsupported VT for PSIGN");
19747 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
19748 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
19750 // PBLENDVB only available on SSE 4.1
19751 if (!Subtarget->hasSSE41())
19754 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
19756 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
19757 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
19758 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
19759 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
19760 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
19764 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
19767 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
19768 MachineFunction &MF = DAG.getMachineFunction();
19769 bool OptForSize = MF.getFunction()->getAttributes().
19770 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
19772 // SHLD/SHRD instructions have lower register pressure, but on some
19773 // platforms they have higher latency than the equivalent
19774 // series of shifts/or that would otherwise be generated.
19775 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
19776 // have higher latencies and we are not optimizing for size.
19777 if (!OptForSize && Subtarget->isSHLDSlow())
19780 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
19782 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
19784 if (!N0.hasOneUse() || !N1.hasOneUse())
19787 SDValue ShAmt0 = N0.getOperand(1);
19788 if (ShAmt0.getValueType() != MVT::i8)
19790 SDValue ShAmt1 = N1.getOperand(1);
19791 if (ShAmt1.getValueType() != MVT::i8)
19793 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
19794 ShAmt0 = ShAmt0.getOperand(0);
19795 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
19796 ShAmt1 = ShAmt1.getOperand(0);
19799 unsigned Opc = X86ISD::SHLD;
19800 SDValue Op0 = N0.getOperand(0);
19801 SDValue Op1 = N1.getOperand(0);
19802 if (ShAmt0.getOpcode() == ISD::SUB) {
19803 Opc = X86ISD::SHRD;
19804 std::swap(Op0, Op1);
19805 std::swap(ShAmt0, ShAmt1);
19808 unsigned Bits = VT.getSizeInBits();
19809 if (ShAmt1.getOpcode() == ISD::SUB) {
19810 SDValue Sum = ShAmt1.getOperand(0);
19811 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
19812 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
19813 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
19814 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
19815 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
19816 return DAG.getNode(Opc, DL, VT,
19818 DAG.getNode(ISD::TRUNCATE, DL,
19821 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
19822 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
19824 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
19825 return DAG.getNode(Opc, DL, VT,
19826 N0.getOperand(0), N1.getOperand(0),
19827 DAG.getNode(ISD::TRUNCATE, DL,
19834 // Generate NEG and CMOV for integer abs.
19835 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
19836 EVT VT = N->getValueType(0);
19838 // Since X86 does not have CMOV for 8-bit integer, we don't convert
19839 // 8-bit integer abs to NEG and CMOV.
19840 if (VT.isInteger() && VT.getSizeInBits() == 8)
19843 SDValue N0 = N->getOperand(0);
19844 SDValue N1 = N->getOperand(1);
19847 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
19848 // and change it to SUB and CMOV.
19849 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
19850 N0.getOpcode() == ISD::ADD &&
19851 N0.getOperand(1) == N1 &&
19852 N1.getOpcode() == ISD::SRA &&
19853 N1.getOperand(0) == N0.getOperand(0))
19854 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
19855 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
19856 // Generate SUB & CMOV.
19857 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
19858 DAG.getConstant(0, VT), N0.getOperand(0));
19860 SDValue Ops[] = { N0.getOperand(0), Neg,
19861 DAG.getConstant(X86::COND_GE, MVT::i8),
19862 SDValue(Neg.getNode(), 1) };
19863 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
19868 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
19869 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
19870 TargetLowering::DAGCombinerInfo &DCI,
19871 const X86Subtarget *Subtarget) {
19872 if (DCI.isBeforeLegalizeOps())
19875 if (Subtarget->hasCMov()) {
19876 SDValue RV = performIntegerAbsCombine(N, DAG);
19884 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
19885 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
19886 TargetLowering::DAGCombinerInfo &DCI,
19887 const X86Subtarget *Subtarget) {
19888 LoadSDNode *Ld = cast<LoadSDNode>(N);
19889 EVT RegVT = Ld->getValueType(0);
19890 EVT MemVT = Ld->getMemoryVT();
19892 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19893 unsigned RegSz = RegVT.getSizeInBits();
19895 // On Sandybridge unaligned 256bit loads are inefficient.
19896 ISD::LoadExtType Ext = Ld->getExtensionType();
19897 unsigned Alignment = Ld->getAlignment();
19898 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
19899 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
19900 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
19901 unsigned NumElems = RegVT.getVectorNumElements();
19905 SDValue Ptr = Ld->getBasePtr();
19906 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
19908 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19910 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
19911 Ld->getPointerInfo(), Ld->isVolatile(),
19912 Ld->isNonTemporal(), Ld->isInvariant(),
19914 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19915 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
19916 Ld->getPointerInfo(), Ld->isVolatile(),
19917 Ld->isNonTemporal(), Ld->isInvariant(),
19918 std::min(16U, Alignment));
19919 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19921 Load2.getValue(1));
19923 SDValue NewVec = DAG.getUNDEF(RegVT);
19924 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
19925 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
19926 return DCI.CombineTo(N, NewVec, TF, true);
19929 // If this is a vector EXT Load then attempt to optimize it using a
19930 // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
19931 // expansion is still better than scalar code.
19932 // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
19933 // emit a shuffle and a arithmetic shift.
19934 // TODO: It is possible to support ZExt by zeroing the undef values
19935 // during the shuffle phase or after the shuffle.
19936 if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
19937 (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
19938 assert(MemVT != RegVT && "Cannot extend to the same type");
19939 assert(MemVT.isVector() && "Must load a vector from memory");
19941 unsigned NumElems = RegVT.getVectorNumElements();
19942 unsigned MemSz = MemVT.getSizeInBits();
19943 assert(RegSz > MemSz && "Register size must be greater than the mem size");
19945 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
19948 // All sizes must be a power of two.
19949 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
19952 // Attempt to load the original value using scalar loads.
19953 // Find the largest scalar type that divides the total loaded size.
19954 MVT SclrLoadTy = MVT::i8;
19955 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19956 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19957 MVT Tp = (MVT::SimpleValueType)tp;
19958 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
19963 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19964 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
19966 SclrLoadTy = MVT::f64;
19968 // Calculate the number of scalar loads that we need to perform
19969 // in order to load our vector from memory.
19970 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
19971 if (Ext == ISD::SEXTLOAD && NumLoads > 1)
19974 unsigned loadRegZize = RegSz;
19975 if (Ext == ISD::SEXTLOAD && RegSz == 256)
19978 // Represent our vector as a sequence of elements which are the
19979 // largest scalar that we can load.
19980 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
19981 loadRegZize/SclrLoadTy.getSizeInBits());
19983 // Represent the data using the same element type that is stored in
19984 // memory. In practice, we ''widen'' MemVT.
19986 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19987 loadRegZize/MemVT.getScalarType().getSizeInBits());
19989 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
19990 "Invalid vector type");
19992 // We can't shuffle using an illegal type.
19993 if (!TLI.isTypeLegal(WideVecVT))
19996 SmallVector<SDValue, 8> Chains;
19997 SDValue Ptr = Ld->getBasePtr();
19998 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
19999 TLI.getPointerTy());
20000 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
20002 for (unsigned i = 0; i < NumLoads; ++i) {
20003 // Perform a single load.
20004 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
20005 Ptr, Ld->getPointerInfo(),
20006 Ld->isVolatile(), Ld->isNonTemporal(),
20007 Ld->isInvariant(), Ld->getAlignment());
20008 Chains.push_back(ScalarLoad.getValue(1));
20009 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
20010 // another round of DAGCombining.
20012 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
20014 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
20015 ScalarLoad, DAG.getIntPtrConstant(i));
20017 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
20020 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
20022 // Bitcast the loaded value to a vector of the original element type, in
20023 // the size of the target vector type.
20024 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
20025 unsigned SizeRatio = RegSz/MemSz;
20027 if (Ext == ISD::SEXTLOAD) {
20028 // If we have SSE4.1 we can directly emit a VSEXT node.
20029 if (Subtarget->hasSSE41()) {
20030 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
20031 return DCI.CombineTo(N, Sext, TF, true);
20034 // Otherwise we'll shuffle the small elements in the high bits of the
20035 // larger type and perform an arithmetic shift. If the shift is not legal
20036 // it's better to scalarize.
20037 if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
20040 // Redistribute the loaded elements into the different locations.
20041 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
20042 for (unsigned i = 0; i != NumElems; ++i)
20043 ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
20045 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
20046 DAG.getUNDEF(WideVecVT),
20049 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
20051 // Build the arithmetic shift.
20052 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
20053 MemVT.getVectorElementType().getSizeInBits();
20054 Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
20055 DAG.getConstant(Amt, RegVT));
20057 return DCI.CombineTo(N, Shuff, TF, true);
20060 // Redistribute the loaded elements into the different locations.
20061 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
20062 for (unsigned i = 0; i != NumElems; ++i)
20063 ShuffleVec[i*SizeRatio] = i;
20065 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
20066 DAG.getUNDEF(WideVecVT),
20069 // Bitcast to the requested type.
20070 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
20071 // Replace the original load with the new sequence
20072 // and return the new chain.
20073 return DCI.CombineTo(N, Shuff, TF, true);
20079 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
20080 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
20081 const X86Subtarget *Subtarget) {
20082 StoreSDNode *St = cast<StoreSDNode>(N);
20083 EVT VT = St->getValue().getValueType();
20084 EVT StVT = St->getMemoryVT();
20086 SDValue StoredVal = St->getOperand(1);
20087 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20089 // If we are saving a concatenation of two XMM registers, perform two stores.
20090 // On Sandy Bridge, 256-bit memory operations are executed by two
20091 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
20092 // memory operation.
20093 unsigned Alignment = St->getAlignment();
20094 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
20095 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
20096 StVT == VT && !IsAligned) {
20097 unsigned NumElems = VT.getVectorNumElements();
20101 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
20102 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
20104 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
20105 SDValue Ptr0 = St->getBasePtr();
20106 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
20108 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
20109 St->getPointerInfo(), St->isVolatile(),
20110 St->isNonTemporal(), Alignment);
20111 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
20112 St->getPointerInfo(), St->isVolatile(),
20113 St->isNonTemporal(),
20114 std::min(16U, Alignment));
20115 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
20118 // Optimize trunc store (of multiple scalars) to shuffle and store.
20119 // First, pack all of the elements in one place. Next, store to memory
20120 // in fewer chunks.
20121 if (St->isTruncatingStore() && VT.isVector()) {
20122 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20123 unsigned NumElems = VT.getVectorNumElements();
20124 assert(StVT != VT && "Cannot truncate to the same type");
20125 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
20126 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
20128 // From, To sizes and ElemCount must be pow of two
20129 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
20130 // We are going to use the original vector elt for storing.
20131 // Accumulated smaller vector elements must be a multiple of the store size.
20132 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
20134 unsigned SizeRatio = FromSz / ToSz;
20136 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
20138 // Create a type on which we perform the shuffle
20139 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
20140 StVT.getScalarType(), NumElems*SizeRatio);
20142 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
20144 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
20145 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
20146 for (unsigned i = 0; i != NumElems; ++i)
20147 ShuffleVec[i] = i * SizeRatio;
20149 // Can't shuffle using an illegal type.
20150 if (!TLI.isTypeLegal(WideVecVT))
20153 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
20154 DAG.getUNDEF(WideVecVT),
20156 // At this point all of the data is stored at the bottom of the
20157 // register. We now need to save it to mem.
20159 // Find the largest store unit
20160 MVT StoreType = MVT::i8;
20161 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
20162 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
20163 MVT Tp = (MVT::SimpleValueType)tp;
20164 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
20168 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
20169 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
20170 (64 <= NumElems * ToSz))
20171 StoreType = MVT::f64;
20173 // Bitcast the original vector into a vector of store-size units
20174 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
20175 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
20176 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
20177 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
20178 SmallVector<SDValue, 8> Chains;
20179 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
20180 TLI.getPointerTy());
20181 SDValue Ptr = St->getBasePtr();
20183 // Perform one or more big stores into memory.
20184 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
20185 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
20186 StoreType, ShuffWide,
20187 DAG.getIntPtrConstant(i));
20188 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
20189 St->getPointerInfo(), St->isVolatile(),
20190 St->isNonTemporal(), St->getAlignment());
20191 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
20192 Chains.push_back(Ch);
20195 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
20198 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
20199 // the FP state in cases where an emms may be missing.
20200 // A preferable solution to the general problem is to figure out the right
20201 // places to insert EMMS. This qualifies as a quick hack.
20203 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
20204 if (VT.getSizeInBits() != 64)
20207 const Function *F = DAG.getMachineFunction().getFunction();
20208 bool NoImplicitFloatOps = F->getAttributes().
20209 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
20210 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
20211 && Subtarget->hasSSE2();
20212 if ((VT.isVector() ||
20213 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
20214 isa<LoadSDNode>(St->getValue()) &&
20215 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
20216 St->getChain().hasOneUse() && !St->isVolatile()) {
20217 SDNode* LdVal = St->getValue().getNode();
20218 LoadSDNode *Ld = nullptr;
20219 int TokenFactorIndex = -1;
20220 SmallVector<SDValue, 8> Ops;
20221 SDNode* ChainVal = St->getChain().getNode();
20222 // Must be a store of a load. We currently handle two cases: the load
20223 // is a direct child, and it's under an intervening TokenFactor. It is
20224 // possible to dig deeper under nested TokenFactors.
20225 if (ChainVal == LdVal)
20226 Ld = cast<LoadSDNode>(St->getChain());
20227 else if (St->getValue().hasOneUse() &&
20228 ChainVal->getOpcode() == ISD::TokenFactor) {
20229 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
20230 if (ChainVal->getOperand(i).getNode() == LdVal) {
20231 TokenFactorIndex = i;
20232 Ld = cast<LoadSDNode>(St->getValue());
20234 Ops.push_back(ChainVal->getOperand(i));
20238 if (!Ld || !ISD::isNormalLoad(Ld))
20241 // If this is not the MMX case, i.e. we are just turning i64 load/store
20242 // into f64 load/store, avoid the transformation if there are multiple
20243 // uses of the loaded value.
20244 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
20249 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
20250 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
20252 if (Subtarget->is64Bit() || F64IsLegal) {
20253 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
20254 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
20255 Ld->getPointerInfo(), Ld->isVolatile(),
20256 Ld->isNonTemporal(), Ld->isInvariant(),
20257 Ld->getAlignment());
20258 SDValue NewChain = NewLd.getValue(1);
20259 if (TokenFactorIndex != -1) {
20260 Ops.push_back(NewChain);
20261 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
20263 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
20264 St->getPointerInfo(),
20265 St->isVolatile(), St->isNonTemporal(),
20266 St->getAlignment());
20269 // Otherwise, lower to two pairs of 32-bit loads / stores.
20270 SDValue LoAddr = Ld->getBasePtr();
20271 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
20272 DAG.getConstant(4, MVT::i32));
20274 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
20275 Ld->getPointerInfo(),
20276 Ld->isVolatile(), Ld->isNonTemporal(),
20277 Ld->isInvariant(), Ld->getAlignment());
20278 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
20279 Ld->getPointerInfo().getWithOffset(4),
20280 Ld->isVolatile(), Ld->isNonTemporal(),
20282 MinAlign(Ld->getAlignment(), 4));
20284 SDValue NewChain = LoLd.getValue(1);
20285 if (TokenFactorIndex != -1) {
20286 Ops.push_back(LoLd);
20287 Ops.push_back(HiLd);
20288 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
20291 LoAddr = St->getBasePtr();
20292 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
20293 DAG.getConstant(4, MVT::i32));
20295 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
20296 St->getPointerInfo(),
20297 St->isVolatile(), St->isNonTemporal(),
20298 St->getAlignment());
20299 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
20300 St->getPointerInfo().getWithOffset(4),
20302 St->isNonTemporal(),
20303 MinAlign(St->getAlignment(), 4));
20304 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
20309 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
20310 /// and return the operands for the horizontal operation in LHS and RHS. A
20311 /// horizontal operation performs the binary operation on successive elements
20312 /// of its first operand, then on successive elements of its second operand,
20313 /// returning the resulting values in a vector. For example, if
20314 /// A = < float a0, float a1, float a2, float a3 >
20316 /// B = < float b0, float b1, float b2, float b3 >
20317 /// then the result of doing a horizontal operation on A and B is
20318 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
20319 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
20320 /// A horizontal-op B, for some already available A and B, and if so then LHS is
20321 /// set to A, RHS to B, and the routine returns 'true'.
20322 /// Note that the binary operation should have the property that if one of the
20323 /// operands is UNDEF then the result is UNDEF.
20324 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
20325 // Look for the following pattern: if
20326 // A = < float a0, float a1, float a2, float a3 >
20327 // B = < float b0, float b1, float b2, float b3 >
20329 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
20330 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
20331 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
20332 // which is A horizontal-op B.
20334 // At least one of the operands should be a vector shuffle.
20335 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
20336 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
20339 MVT VT = LHS.getSimpleValueType();
20341 assert((VT.is128BitVector() || VT.is256BitVector()) &&
20342 "Unsupported vector type for horizontal add/sub");
20344 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
20345 // operate independently on 128-bit lanes.
20346 unsigned NumElts = VT.getVectorNumElements();
20347 unsigned NumLanes = VT.getSizeInBits()/128;
20348 unsigned NumLaneElts = NumElts / NumLanes;
20349 assert((NumLaneElts % 2 == 0) &&
20350 "Vector type should have an even number of elements in each lane");
20351 unsigned HalfLaneElts = NumLaneElts/2;
20353 // View LHS in the form
20354 // LHS = VECTOR_SHUFFLE A, B, LMask
20355 // If LHS is not a shuffle then pretend it is the shuffle
20356 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
20357 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
20360 SmallVector<int, 16> LMask(NumElts);
20361 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
20362 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
20363 A = LHS.getOperand(0);
20364 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
20365 B = LHS.getOperand(1);
20366 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
20367 std::copy(Mask.begin(), Mask.end(), LMask.begin());
20369 if (LHS.getOpcode() != ISD::UNDEF)
20371 for (unsigned i = 0; i != NumElts; ++i)
20375 // Likewise, view RHS in the form
20376 // RHS = VECTOR_SHUFFLE C, D, RMask
20378 SmallVector<int, 16> RMask(NumElts);
20379 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
20380 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
20381 C = RHS.getOperand(0);
20382 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
20383 D = RHS.getOperand(1);
20384 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
20385 std::copy(Mask.begin(), Mask.end(), RMask.begin());
20387 if (RHS.getOpcode() != ISD::UNDEF)
20389 for (unsigned i = 0; i != NumElts; ++i)
20393 // Check that the shuffles are both shuffling the same vectors.
20394 if (!(A == C && B == D) && !(A == D && B == C))
20397 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
20398 if (!A.getNode() && !B.getNode())
20401 // If A and B occur in reverse order in RHS, then "swap" them (which means
20402 // rewriting the mask).
20404 CommuteVectorShuffleMask(RMask, NumElts);
20406 // At this point LHS and RHS are equivalent to
20407 // LHS = VECTOR_SHUFFLE A, B, LMask
20408 // RHS = VECTOR_SHUFFLE A, B, RMask
20409 // Check that the masks correspond to performing a horizontal operation.
20410 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
20411 for (unsigned i = 0; i != NumLaneElts; ++i) {
20412 int LIdx = LMask[i+l], RIdx = RMask[i+l];
20414 // Ignore any UNDEF components.
20415 if (LIdx < 0 || RIdx < 0 ||
20416 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
20417 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
20420 // Check that successive elements are being operated on. If not, this is
20421 // not a horizontal operation.
20422 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
20423 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
20424 if (!(LIdx == Index && RIdx == Index + 1) &&
20425 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
20430 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
20431 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
20435 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
20436 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
20437 const X86Subtarget *Subtarget) {
20438 EVT VT = N->getValueType(0);
20439 SDValue LHS = N->getOperand(0);
20440 SDValue RHS = N->getOperand(1);
20442 // Try to synthesize horizontal adds from adds of shuffles.
20443 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
20444 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
20445 isHorizontalBinOp(LHS, RHS, true))
20446 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
20450 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
20451 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
20452 const X86Subtarget *Subtarget) {
20453 EVT VT = N->getValueType(0);
20454 SDValue LHS = N->getOperand(0);
20455 SDValue RHS = N->getOperand(1);
20457 // Try to synthesize horizontal subs from subs of shuffles.
20458 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
20459 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
20460 isHorizontalBinOp(LHS, RHS, false))
20461 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
20465 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
20466 /// X86ISD::FXOR nodes.
20467 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
20468 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
20469 // F[X]OR(0.0, x) -> x
20470 // F[X]OR(x, 0.0) -> x
20471 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20472 if (C->getValueAPF().isPosZero())
20473 return N->getOperand(1);
20474 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20475 if (C->getValueAPF().isPosZero())
20476 return N->getOperand(0);
20480 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
20481 /// X86ISD::FMAX nodes.
20482 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
20483 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
20485 // Only perform optimizations if UnsafeMath is used.
20486 if (!DAG.getTarget().Options.UnsafeFPMath)
20489 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
20490 // into FMINC and FMAXC, which are Commutative operations.
20491 unsigned NewOp = 0;
20492 switch (N->getOpcode()) {
20493 default: llvm_unreachable("unknown opcode");
20494 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
20495 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
20498 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
20499 N->getOperand(0), N->getOperand(1));
20502 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
20503 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
20504 // FAND(0.0, x) -> 0.0
20505 // FAND(x, 0.0) -> 0.0
20506 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20507 if (C->getValueAPF().isPosZero())
20508 return N->getOperand(0);
20509 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20510 if (C->getValueAPF().isPosZero())
20511 return N->getOperand(1);
20515 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
20516 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
20517 // FANDN(x, 0.0) -> 0.0
20518 // FANDN(0.0, x) -> x
20519 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20520 if (C->getValueAPF().isPosZero())
20521 return N->getOperand(1);
20522 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20523 if (C->getValueAPF().isPosZero())
20524 return N->getOperand(1);
20528 static SDValue PerformBTCombine(SDNode *N,
20530 TargetLowering::DAGCombinerInfo &DCI) {
20531 // BT ignores high bits in the bit index operand.
20532 SDValue Op1 = N->getOperand(1);
20533 if (Op1.hasOneUse()) {
20534 unsigned BitWidth = Op1.getValueSizeInBits();
20535 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
20536 APInt KnownZero, KnownOne;
20537 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
20538 !DCI.isBeforeLegalizeOps());
20539 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20540 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
20541 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
20542 DCI.CommitTargetLoweringOpt(TLO);
20547 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
20548 SDValue Op = N->getOperand(0);
20549 if (Op.getOpcode() == ISD::BITCAST)
20550 Op = Op.getOperand(0);
20551 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
20552 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
20553 VT.getVectorElementType().getSizeInBits() ==
20554 OpVT.getVectorElementType().getSizeInBits()) {
20555 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
20560 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
20561 const X86Subtarget *Subtarget) {
20562 EVT VT = N->getValueType(0);
20563 if (!VT.isVector())
20566 SDValue N0 = N->getOperand(0);
20567 SDValue N1 = N->getOperand(1);
20568 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
20571 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
20572 // both SSE and AVX2 since there is no sign-extended shift right
20573 // operation on a vector with 64-bit elements.
20574 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
20575 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
20576 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
20577 N0.getOpcode() == ISD::SIGN_EXTEND)) {
20578 SDValue N00 = N0.getOperand(0);
20580 // EXTLOAD has a better solution on AVX2,
20581 // it may be replaced with X86ISD::VSEXT node.
20582 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
20583 if (!ISD::isNormalLoad(N00.getNode()))
20586 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
20587 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
20589 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
20595 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
20596 TargetLowering::DAGCombinerInfo &DCI,
20597 const X86Subtarget *Subtarget) {
20598 if (!DCI.isBeforeLegalizeOps())
20601 if (!Subtarget->hasFp256())
20604 EVT VT = N->getValueType(0);
20605 if (VT.isVector() && VT.getSizeInBits() == 256) {
20606 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
20614 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
20615 const X86Subtarget* Subtarget) {
20617 EVT VT = N->getValueType(0);
20619 // Let legalize expand this if it isn't a legal type yet.
20620 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
20623 EVT ScalarVT = VT.getScalarType();
20624 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
20625 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
20628 SDValue A = N->getOperand(0);
20629 SDValue B = N->getOperand(1);
20630 SDValue C = N->getOperand(2);
20632 bool NegA = (A.getOpcode() == ISD::FNEG);
20633 bool NegB = (B.getOpcode() == ISD::FNEG);
20634 bool NegC = (C.getOpcode() == ISD::FNEG);
20636 // Negative multiplication when NegA xor NegB
20637 bool NegMul = (NegA != NegB);
20639 A = A.getOperand(0);
20641 B = B.getOperand(0);
20643 C = C.getOperand(0);
20647 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
20649 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
20651 return DAG.getNode(Opcode, dl, VT, A, B, C);
20654 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
20655 TargetLowering::DAGCombinerInfo &DCI,
20656 const X86Subtarget *Subtarget) {
20657 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
20658 // (and (i32 x86isd::setcc_carry), 1)
20659 // This eliminates the zext. This transformation is necessary because
20660 // ISD::SETCC is always legalized to i8.
20662 SDValue N0 = N->getOperand(0);
20663 EVT VT = N->getValueType(0);
20665 if (N0.getOpcode() == ISD::AND &&
20667 N0.getOperand(0).hasOneUse()) {
20668 SDValue N00 = N0.getOperand(0);
20669 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
20670 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
20671 if (!C || C->getZExtValue() != 1)
20673 return DAG.getNode(ISD::AND, dl, VT,
20674 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
20675 N00.getOperand(0), N00.getOperand(1)),
20676 DAG.getConstant(1, VT));
20680 if (N0.getOpcode() == ISD::TRUNCATE &&
20682 N0.getOperand(0).hasOneUse()) {
20683 SDValue N00 = N0.getOperand(0);
20684 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
20685 return DAG.getNode(ISD::AND, dl, VT,
20686 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
20687 N00.getOperand(0), N00.getOperand(1)),
20688 DAG.getConstant(1, VT));
20691 if (VT.is256BitVector()) {
20692 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
20700 // Optimize x == -y --> x+y == 0
20701 // x != -y --> x+y != 0
20702 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
20703 const X86Subtarget* Subtarget) {
20704 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
20705 SDValue LHS = N->getOperand(0);
20706 SDValue RHS = N->getOperand(1);
20707 EVT VT = N->getValueType(0);
20710 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
20711 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
20712 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
20713 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
20714 LHS.getValueType(), RHS, LHS.getOperand(1));
20715 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
20716 addV, DAG.getConstant(0, addV.getValueType()), CC);
20718 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
20719 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
20720 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
20721 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
20722 RHS.getValueType(), LHS, RHS.getOperand(1));
20723 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
20724 addV, DAG.getConstant(0, addV.getValueType()), CC);
20727 if (VT.getScalarType() == MVT::i1) {
20728 bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
20729 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
20730 bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
20731 if (!IsSEXT0 && !IsVZero0)
20733 bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
20734 (RHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
20735 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
20737 if (!IsSEXT1 && !IsVZero1)
20740 if (IsSEXT0 && IsVZero1) {
20741 assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
20742 if (CC == ISD::SETEQ)
20743 return DAG.getNOT(DL, LHS.getOperand(0), VT);
20744 return LHS.getOperand(0);
20746 if (IsSEXT1 && IsVZero0) {
20747 assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
20748 if (CC == ISD::SETEQ)
20749 return DAG.getNOT(DL, RHS.getOperand(0), VT);
20750 return RHS.getOperand(0);
20757 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
20758 const X86Subtarget *Subtarget) {
20760 MVT VT = N->getOperand(1)->getSimpleValueType(0);
20761 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
20762 "X86insertps is only defined for v4x32");
20764 SDValue Ld = N->getOperand(1);
20765 if (MayFoldLoad(Ld)) {
20766 // Extract the countS bits from the immediate so we can get the proper
20767 // address when narrowing the vector load to a specific element.
20768 // When the second source op is a memory address, interps doesn't use
20769 // countS and just gets an f32 from that address.
20770 unsigned DestIndex =
20771 cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
20772 Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
20776 // Create this as a scalar to vector to match the instruction pattern.
20777 SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
20778 // countS bits are ignored when loading from memory on insertps, which
20779 // means we don't need to explicitly set them to 0.
20780 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
20781 LoadScalarToVector, N->getOperand(2));
20784 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
20785 // as "sbb reg,reg", since it can be extended without zext and produces
20786 // an all-ones bit which is more useful than 0/1 in some cases.
20787 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
20790 return DAG.getNode(ISD::AND, DL, VT,
20791 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
20792 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
20793 DAG.getConstant(1, VT));
20794 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
20795 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
20796 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
20797 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
20800 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
20801 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
20802 TargetLowering::DAGCombinerInfo &DCI,
20803 const X86Subtarget *Subtarget) {
20805 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
20806 SDValue EFLAGS = N->getOperand(1);
20808 if (CC == X86::COND_A) {
20809 // Try to convert COND_A into COND_B in an attempt to facilitate
20810 // materializing "setb reg".
20812 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
20813 // cannot take an immediate as its first operand.
20815 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
20816 EFLAGS.getValueType().isInteger() &&
20817 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
20818 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
20819 EFLAGS.getNode()->getVTList(),
20820 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
20821 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
20822 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
20826 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
20827 // a zext and produces an all-ones bit which is more useful than 0/1 in some
20829 if (CC == X86::COND_B)
20830 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
20834 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
20835 if (Flags.getNode()) {
20836 SDValue Cond = DAG.getConstant(CC, MVT::i8);
20837 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
20843 // Optimize branch condition evaluation.
20845 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
20846 TargetLowering::DAGCombinerInfo &DCI,
20847 const X86Subtarget *Subtarget) {
20849 SDValue Chain = N->getOperand(0);
20850 SDValue Dest = N->getOperand(1);
20851 SDValue EFLAGS = N->getOperand(3);
20852 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
20856 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
20857 if (Flags.getNode()) {
20858 SDValue Cond = DAG.getConstant(CC, MVT::i8);
20859 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
20866 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
20867 const X86TargetLowering *XTLI) {
20868 SDValue Op0 = N->getOperand(0);
20869 EVT InVT = Op0->getValueType(0);
20871 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
20872 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
20874 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
20875 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
20876 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
20879 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
20880 // a 32-bit target where SSE doesn't support i64->FP operations.
20881 if (Op0.getOpcode() == ISD::LOAD) {
20882 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
20883 EVT VT = Ld->getValueType(0);
20884 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
20885 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
20886 !XTLI->getSubtarget()->is64Bit() &&
20888 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
20889 Ld->getChain(), Op0, DAG);
20890 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
20897 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
20898 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
20899 X86TargetLowering::DAGCombinerInfo &DCI) {
20900 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
20901 // the result is either zero or one (depending on the input carry bit).
20902 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
20903 if (X86::isZeroNode(N->getOperand(0)) &&
20904 X86::isZeroNode(N->getOperand(1)) &&
20905 // We don't have a good way to replace an EFLAGS use, so only do this when
20907 SDValue(N, 1).use_empty()) {
20909 EVT VT = N->getValueType(0);
20910 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
20911 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
20912 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
20913 DAG.getConstant(X86::COND_B,MVT::i8),
20915 DAG.getConstant(1, VT));
20916 return DCI.CombineTo(N, Res1, CarryOut);
20922 // fold (add Y, (sete X, 0)) -> adc 0, Y
20923 // (add Y, (setne X, 0)) -> sbb -1, Y
20924 // (sub (sete X, 0), Y) -> sbb 0, Y
20925 // (sub (setne X, 0), Y) -> adc -1, Y
20926 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
20929 // Look through ZExts.
20930 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
20931 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
20934 SDValue SetCC = Ext.getOperand(0);
20935 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
20938 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
20939 if (CC != X86::COND_E && CC != X86::COND_NE)
20942 SDValue Cmp = SetCC.getOperand(1);
20943 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
20944 !X86::isZeroNode(Cmp.getOperand(1)) ||
20945 !Cmp.getOperand(0).getValueType().isInteger())
20948 SDValue CmpOp0 = Cmp.getOperand(0);
20949 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
20950 DAG.getConstant(1, CmpOp0.getValueType()));
20952 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
20953 if (CC == X86::COND_NE)
20954 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
20955 DL, OtherVal.getValueType(), OtherVal,
20956 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
20957 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
20958 DL, OtherVal.getValueType(), OtherVal,
20959 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
20962 /// PerformADDCombine - Do target-specific dag combines on integer adds.
20963 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
20964 const X86Subtarget *Subtarget) {
20965 EVT VT = N->getValueType(0);
20966 SDValue Op0 = N->getOperand(0);
20967 SDValue Op1 = N->getOperand(1);
20969 // Try to synthesize horizontal adds from adds of shuffles.
20970 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20971 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20972 isHorizontalBinOp(Op0, Op1, true))
20973 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
20975 return OptimizeConditionalInDecrement(N, DAG);
20978 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
20979 const X86Subtarget *Subtarget) {
20980 SDValue Op0 = N->getOperand(0);
20981 SDValue Op1 = N->getOperand(1);
20983 // X86 can't encode an immediate LHS of a sub. See if we can push the
20984 // negation into a preceding instruction.
20985 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
20986 // If the RHS of the sub is a XOR with one use and a constant, invert the
20987 // immediate. Then add one to the LHS of the sub so we can turn
20988 // X-Y -> X+~Y+1, saving one register.
20989 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
20990 isa<ConstantSDNode>(Op1.getOperand(1))) {
20991 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
20992 EVT VT = Op0.getValueType();
20993 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
20995 DAG.getConstant(~XorC, VT));
20996 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
20997 DAG.getConstant(C->getAPIntValue()+1, VT));
21001 // Try to synthesize horizontal adds from adds of shuffles.
21002 EVT VT = N->getValueType(0);
21003 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
21004 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
21005 isHorizontalBinOp(Op0, Op1, true))
21006 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
21008 return OptimizeConditionalInDecrement(N, DAG);
21011 /// performVZEXTCombine - Performs build vector combines
21012 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
21013 TargetLowering::DAGCombinerInfo &DCI,
21014 const X86Subtarget *Subtarget) {
21015 // (vzext (bitcast (vzext (x)) -> (vzext x)
21016 SDValue In = N->getOperand(0);
21017 while (In.getOpcode() == ISD::BITCAST)
21018 In = In.getOperand(0);
21020 if (In.getOpcode() != X86ISD::VZEXT)
21023 return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
21027 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
21028 DAGCombinerInfo &DCI) const {
21029 SelectionDAG &DAG = DCI.DAG;
21030 switch (N->getOpcode()) {
21032 case ISD::EXTRACT_VECTOR_ELT:
21033 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
21035 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
21036 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
21037 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
21038 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
21039 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
21040 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
21043 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
21044 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
21045 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
21046 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
21047 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
21048 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
21049 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
21050 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
21051 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
21053 case X86ISD::FOR: return PerformFORCombine(N, DAG);
21055 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
21056 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
21057 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
21058 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
21059 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
21060 case ISD::ANY_EXTEND:
21061 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
21062 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
21063 case ISD::SIGN_EXTEND_INREG:
21064 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
21065 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
21066 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
21067 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
21068 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
21069 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
21070 case X86ISD::SHUFP: // Handle all target specific shuffles
21071 case X86ISD::PALIGNR:
21072 case X86ISD::UNPCKH:
21073 case X86ISD::UNPCKL:
21074 case X86ISD::MOVHLPS:
21075 case X86ISD::MOVLHPS:
21076 case X86ISD::PSHUFD:
21077 case X86ISD::PSHUFHW:
21078 case X86ISD::PSHUFLW:
21079 case X86ISD::MOVSS:
21080 case X86ISD::MOVSD:
21081 case X86ISD::VPERMILP:
21082 case X86ISD::VPERM2X128:
21083 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
21084 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
21085 case ISD::INTRINSIC_WO_CHAIN:
21086 return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
21087 case X86ISD::INSERTPS:
21088 return PerformINSERTPSCombine(N, DAG, Subtarget);
21089 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
21095 /// isTypeDesirableForOp - Return true if the target has native support for
21096 /// the specified value type and it is 'desirable' to use the type for the
21097 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
21098 /// instruction encodings are longer and some i16 instructions are slow.
21099 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
21100 if (!isTypeLegal(VT))
21102 if (VT != MVT::i16)
21109 case ISD::SIGN_EXTEND:
21110 case ISD::ZERO_EXTEND:
21111 case ISD::ANY_EXTEND:
21124 /// IsDesirableToPromoteOp - This method query the target whether it is
21125 /// beneficial for dag combiner to promote the specified node. If true, it
21126 /// should return the desired promotion type by reference.
21127 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
21128 EVT VT = Op.getValueType();
21129 if (VT != MVT::i16)
21132 bool Promote = false;
21133 bool Commute = false;
21134 switch (Op.getOpcode()) {
21137 LoadSDNode *LD = cast<LoadSDNode>(Op);
21138 // If the non-extending load has a single use and it's not live out, then it
21139 // might be folded.
21140 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
21141 Op.hasOneUse()*/) {
21142 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
21143 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
21144 // The only case where we'd want to promote LOAD (rather then it being
21145 // promoted as an operand is when it's only use is liveout.
21146 if (UI->getOpcode() != ISD::CopyToReg)
21153 case ISD::SIGN_EXTEND:
21154 case ISD::ZERO_EXTEND:
21155 case ISD::ANY_EXTEND:
21160 SDValue N0 = Op.getOperand(0);
21161 // Look out for (store (shl (load), x)).
21162 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
21175 SDValue N0 = Op.getOperand(0);
21176 SDValue N1 = Op.getOperand(1);
21177 if (!Commute && MayFoldLoad(N1))
21179 // Avoid disabling potential load folding opportunities.
21180 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
21182 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
21192 //===----------------------------------------------------------------------===//
21193 // X86 Inline Assembly Support
21194 //===----------------------------------------------------------------------===//
21197 // Helper to match a string separated by whitespace.
21198 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
21199 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
21201 for (unsigned i = 0, e = args.size(); i != e; ++i) {
21202 StringRef piece(*args[i]);
21203 if (!s.startswith(piece)) // Check if the piece matches.
21206 s = s.substr(piece.size());
21207 StringRef::size_type pos = s.find_first_not_of(" \t");
21208 if (pos == 0) // We matched a prefix.
21216 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
21219 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
21221 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
21222 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
21223 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
21224 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
21226 if (AsmPieces.size() == 3)
21228 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
21235 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
21236 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
21238 std::string AsmStr = IA->getAsmString();
21240 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
21241 if (!Ty || Ty->getBitWidth() % 16 != 0)
21244 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
21245 SmallVector<StringRef, 4> AsmPieces;
21246 SplitString(AsmStr, AsmPieces, ";\n");
21248 switch (AsmPieces.size()) {
21249 default: return false;
21251 // FIXME: this should verify that we are targeting a 486 or better. If not,
21252 // we will turn this bswap into something that will be lowered to logical
21253 // ops instead of emitting the bswap asm. For now, we don't support 486 or
21254 // lower so don't worry about this.
21256 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
21257 matchAsm(AsmPieces[0], "bswapl", "$0") ||
21258 matchAsm(AsmPieces[0], "bswapq", "$0") ||
21259 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
21260 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
21261 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
21262 // No need to check constraints, nothing other than the equivalent of
21263 // "=r,0" would be valid here.
21264 return IntrinsicLowering::LowerToByteSwap(CI);
21267 // rorw $$8, ${0:w} --> llvm.bswap.i16
21268 if (CI->getType()->isIntegerTy(16) &&
21269 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
21270 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
21271 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
21273 const std::string &ConstraintsStr = IA->getConstraintString();
21274 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
21275 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
21276 if (clobbersFlagRegisters(AsmPieces))
21277 return IntrinsicLowering::LowerToByteSwap(CI);
21281 if (CI->getType()->isIntegerTy(32) &&
21282 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
21283 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
21284 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
21285 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
21287 const std::string &ConstraintsStr = IA->getConstraintString();
21288 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
21289 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
21290 if (clobbersFlagRegisters(AsmPieces))
21291 return IntrinsicLowering::LowerToByteSwap(CI);
21294 if (CI->getType()->isIntegerTy(64)) {
21295 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
21296 if (Constraints.size() >= 2 &&
21297 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
21298 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
21299 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
21300 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
21301 matchAsm(AsmPieces[1], "bswap", "%edx") &&
21302 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
21303 return IntrinsicLowering::LowerToByteSwap(CI);
21311 /// getConstraintType - Given a constraint letter, return the type of
21312 /// constraint it is for this target.
21313 X86TargetLowering::ConstraintType
21314 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
21315 if (Constraint.size() == 1) {
21316 switch (Constraint[0]) {
21327 return C_RegisterClass;
21351 return TargetLowering::getConstraintType(Constraint);
21354 /// Examine constraint type and operand type and determine a weight value.
21355 /// This object must already have been set up with the operand type
21356 /// and the current alternative constraint selected.
21357 TargetLowering::ConstraintWeight
21358 X86TargetLowering::getSingleConstraintMatchWeight(
21359 AsmOperandInfo &info, const char *constraint) const {
21360 ConstraintWeight weight = CW_Invalid;
21361 Value *CallOperandVal = info.CallOperandVal;
21362 // If we don't have a value, we can't do a match,
21363 // but allow it at the lowest weight.
21364 if (!CallOperandVal)
21366 Type *type = CallOperandVal->getType();
21367 // Look at the constraint type.
21368 switch (*constraint) {
21370 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
21381 if (CallOperandVal->getType()->isIntegerTy())
21382 weight = CW_SpecificReg;
21387 if (type->isFloatingPointTy())
21388 weight = CW_SpecificReg;
21391 if (type->isX86_MMXTy() && Subtarget->hasMMX())
21392 weight = CW_SpecificReg;
21396 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
21397 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
21398 weight = CW_Register;
21401 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
21402 if (C->getZExtValue() <= 31)
21403 weight = CW_Constant;
21407 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21408 if (C->getZExtValue() <= 63)
21409 weight = CW_Constant;
21413 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21414 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
21415 weight = CW_Constant;
21419 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21420 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
21421 weight = CW_Constant;
21425 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21426 if (C->getZExtValue() <= 3)
21427 weight = CW_Constant;
21431 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21432 if (C->getZExtValue() <= 0xff)
21433 weight = CW_Constant;
21438 if (dyn_cast<ConstantFP>(CallOperandVal)) {
21439 weight = CW_Constant;
21443 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21444 if ((C->getSExtValue() >= -0x80000000LL) &&
21445 (C->getSExtValue() <= 0x7fffffffLL))
21446 weight = CW_Constant;
21450 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21451 if (C->getZExtValue() <= 0xffffffff)
21452 weight = CW_Constant;
21459 /// LowerXConstraint - try to replace an X constraint, which matches anything,
21460 /// with another that has more specific requirements based on the type of the
21461 /// corresponding operand.
21462 const char *X86TargetLowering::
21463 LowerXConstraint(EVT ConstraintVT) const {
21464 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
21465 // 'f' like normal targets.
21466 if (ConstraintVT.isFloatingPoint()) {
21467 if (Subtarget->hasSSE2())
21469 if (Subtarget->hasSSE1())
21473 return TargetLowering::LowerXConstraint(ConstraintVT);
21476 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
21477 /// vector. If it is invalid, don't add anything to Ops.
21478 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
21479 std::string &Constraint,
21480 std::vector<SDValue>&Ops,
21481 SelectionDAG &DAG) const {
21484 // Only support length 1 constraints for now.
21485 if (Constraint.length() > 1) return;
21487 char ConstraintLetter = Constraint[0];
21488 switch (ConstraintLetter) {
21491 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21492 if (C->getZExtValue() <= 31) {
21493 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21499 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21500 if (C->getZExtValue() <= 63) {
21501 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21507 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21508 if (isInt<8>(C->getSExtValue())) {
21509 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21515 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21516 if (C->getZExtValue() <= 255) {
21517 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21523 // 32-bit signed value
21524 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21525 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
21526 C->getSExtValue())) {
21527 // Widen to 64 bits here to get it sign extended.
21528 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
21531 // FIXME gcc accepts some relocatable values here too, but only in certain
21532 // memory models; it's complicated.
21537 // 32-bit unsigned value
21538 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21539 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
21540 C->getZExtValue())) {
21541 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21545 // FIXME gcc accepts some relocatable values here too, but only in certain
21546 // memory models; it's complicated.
21550 // Literal immediates are always ok.
21551 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
21552 // Widen to 64 bits here to get it sign extended.
21553 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
21557 // In any sort of PIC mode addresses need to be computed at runtime by
21558 // adding in a register or some sort of table lookup. These can't
21559 // be used as immediates.
21560 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
21563 // If we are in non-pic codegen mode, we allow the address of a global (with
21564 // an optional displacement) to be used with 'i'.
21565 GlobalAddressSDNode *GA = nullptr;
21566 int64_t Offset = 0;
21568 // Match either (GA), (GA+C), (GA+C1+C2), etc.
21570 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
21571 Offset += GA->getOffset();
21573 } else if (Op.getOpcode() == ISD::ADD) {
21574 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
21575 Offset += C->getZExtValue();
21576 Op = Op.getOperand(0);
21579 } else if (Op.getOpcode() == ISD::SUB) {
21580 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
21581 Offset += -C->getZExtValue();
21582 Op = Op.getOperand(0);
21587 // Otherwise, this isn't something we can handle, reject it.
21591 const GlobalValue *GV = GA->getGlobal();
21592 // If we require an extra load to get this address, as in PIC mode, we
21593 // can't accept it.
21594 if (isGlobalStubReference(
21595 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
21598 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
21599 GA->getValueType(0), Offset);
21604 if (Result.getNode()) {
21605 Ops.push_back(Result);
21608 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
21611 std::pair<unsigned, const TargetRegisterClass*>
21612 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
21614 // First, see if this is a constraint that directly corresponds to an LLVM
21616 if (Constraint.size() == 1) {
21617 // GCC Constraint Letters
21618 switch (Constraint[0]) {
21620 // TODO: Slight differences here in allocation order and leaving
21621 // RIP in the class. Do they matter any more here than they do
21622 // in the normal allocation?
21623 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
21624 if (Subtarget->is64Bit()) {
21625 if (VT == MVT::i32 || VT == MVT::f32)
21626 return std::make_pair(0U, &X86::GR32RegClass);
21627 if (VT == MVT::i16)
21628 return std::make_pair(0U, &X86::GR16RegClass);
21629 if (VT == MVT::i8 || VT == MVT::i1)
21630 return std::make_pair(0U, &X86::GR8RegClass);
21631 if (VT == MVT::i64 || VT == MVT::f64)
21632 return std::make_pair(0U, &X86::GR64RegClass);
21635 // 32-bit fallthrough
21636 case 'Q': // Q_REGS
21637 if (VT == MVT::i32 || VT == MVT::f32)
21638 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
21639 if (VT == MVT::i16)
21640 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
21641 if (VT == MVT::i8 || VT == MVT::i1)
21642 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
21643 if (VT == MVT::i64)
21644 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
21646 case 'r': // GENERAL_REGS
21647 case 'l': // INDEX_REGS
21648 if (VT == MVT::i8 || VT == MVT::i1)
21649 return std::make_pair(0U, &X86::GR8RegClass);
21650 if (VT == MVT::i16)
21651 return std::make_pair(0U, &X86::GR16RegClass);
21652 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
21653 return std::make_pair(0U, &X86::GR32RegClass);
21654 return std::make_pair(0U, &X86::GR64RegClass);
21655 case 'R': // LEGACY_REGS
21656 if (VT == MVT::i8 || VT == MVT::i1)
21657 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
21658 if (VT == MVT::i16)
21659 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
21660 if (VT == MVT::i32 || !Subtarget->is64Bit())
21661 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
21662 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
21663 case 'f': // FP Stack registers.
21664 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
21665 // value to the correct fpstack register class.
21666 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
21667 return std::make_pair(0U, &X86::RFP32RegClass);
21668 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
21669 return std::make_pair(0U, &X86::RFP64RegClass);
21670 return std::make_pair(0U, &X86::RFP80RegClass);
21671 case 'y': // MMX_REGS if MMX allowed.
21672 if (!Subtarget->hasMMX()) break;
21673 return std::make_pair(0U, &X86::VR64RegClass);
21674 case 'Y': // SSE_REGS if SSE2 allowed
21675 if (!Subtarget->hasSSE2()) break;
21677 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
21678 if (!Subtarget->hasSSE1()) break;
21680 switch (VT.SimpleTy) {
21682 // Scalar SSE types.
21685 return std::make_pair(0U, &X86::FR32RegClass);
21688 return std::make_pair(0U, &X86::FR64RegClass);
21696 return std::make_pair(0U, &X86::VR128RegClass);
21704 return std::make_pair(0U, &X86::VR256RegClass);
21709 return std::make_pair(0U, &X86::VR512RegClass);
21715 // Use the default implementation in TargetLowering to convert the register
21716 // constraint into a member of a register class.
21717 std::pair<unsigned, const TargetRegisterClass*> Res;
21718 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
21720 // Not found as a standard register?
21722 // Map st(0) -> st(7) -> ST0
21723 if (Constraint.size() == 7 && Constraint[0] == '{' &&
21724 tolower(Constraint[1]) == 's' &&
21725 tolower(Constraint[2]) == 't' &&
21726 Constraint[3] == '(' &&
21727 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
21728 Constraint[5] == ')' &&
21729 Constraint[6] == '}') {
21731 Res.first = X86::ST0+Constraint[4]-'0';
21732 Res.second = &X86::RFP80RegClass;
21736 // GCC allows "st(0)" to be called just plain "st".
21737 if (StringRef("{st}").equals_lower(Constraint)) {
21738 Res.first = X86::ST0;
21739 Res.second = &X86::RFP80RegClass;
21744 if (StringRef("{flags}").equals_lower(Constraint)) {
21745 Res.first = X86::EFLAGS;
21746 Res.second = &X86::CCRRegClass;
21750 // 'A' means EAX + EDX.
21751 if (Constraint == "A") {
21752 Res.first = X86::EAX;
21753 Res.second = &X86::GR32_ADRegClass;
21759 // Otherwise, check to see if this is a register class of the wrong value
21760 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
21761 // turn into {ax},{dx}.
21762 if (Res.second->hasType(VT))
21763 return Res; // Correct type already, nothing to do.
21765 // All of the single-register GCC register classes map their values onto
21766 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
21767 // really want an 8-bit or 32-bit register, map to the appropriate register
21768 // class and return the appropriate register.
21769 if (Res.second == &X86::GR16RegClass) {
21770 if (VT == MVT::i8 || VT == MVT::i1) {
21771 unsigned DestReg = 0;
21772 switch (Res.first) {
21774 case X86::AX: DestReg = X86::AL; break;
21775 case X86::DX: DestReg = X86::DL; break;
21776 case X86::CX: DestReg = X86::CL; break;
21777 case X86::BX: DestReg = X86::BL; break;
21780 Res.first = DestReg;
21781 Res.second = &X86::GR8RegClass;
21783 } else if (VT == MVT::i32 || VT == MVT::f32) {
21784 unsigned DestReg = 0;
21785 switch (Res.first) {
21787 case X86::AX: DestReg = X86::EAX; break;
21788 case X86::DX: DestReg = X86::EDX; break;
21789 case X86::CX: DestReg = X86::ECX; break;
21790 case X86::BX: DestReg = X86::EBX; break;
21791 case X86::SI: DestReg = X86::ESI; break;
21792 case X86::DI: DestReg = X86::EDI; break;
21793 case X86::BP: DestReg = X86::EBP; break;
21794 case X86::SP: DestReg = X86::ESP; break;
21797 Res.first = DestReg;
21798 Res.second = &X86::GR32RegClass;
21800 } else if (VT == MVT::i64 || VT == MVT::f64) {
21801 unsigned DestReg = 0;
21802 switch (Res.first) {
21804 case X86::AX: DestReg = X86::RAX; break;
21805 case X86::DX: DestReg = X86::RDX; break;
21806 case X86::CX: DestReg = X86::RCX; break;
21807 case X86::BX: DestReg = X86::RBX; break;
21808 case X86::SI: DestReg = X86::RSI; break;
21809 case X86::DI: DestReg = X86::RDI; break;
21810 case X86::BP: DestReg = X86::RBP; break;
21811 case X86::SP: DestReg = X86::RSP; break;
21814 Res.first = DestReg;
21815 Res.second = &X86::GR64RegClass;
21818 } else if (Res.second == &X86::FR32RegClass ||
21819 Res.second == &X86::FR64RegClass ||
21820 Res.second == &X86::VR128RegClass ||
21821 Res.second == &X86::VR256RegClass ||
21822 Res.second == &X86::FR32XRegClass ||
21823 Res.second == &X86::FR64XRegClass ||
21824 Res.second == &X86::VR128XRegClass ||
21825 Res.second == &X86::VR256XRegClass ||
21826 Res.second == &X86::VR512RegClass) {
21827 // Handle references to XMM physical registers that got mapped into the
21828 // wrong class. This can happen with constraints like {xmm0} where the
21829 // target independent register mapper will just pick the first match it can
21830 // find, ignoring the required type.
21832 if (VT == MVT::f32 || VT == MVT::i32)
21833 Res.second = &X86::FR32RegClass;
21834 else if (VT == MVT::f64 || VT == MVT::i64)
21835 Res.second = &X86::FR64RegClass;
21836 else if (X86::VR128RegClass.hasType(VT))
21837 Res.second = &X86::VR128RegClass;
21838 else if (X86::VR256RegClass.hasType(VT))
21839 Res.second = &X86::VR256RegClass;
21840 else if (X86::VR512RegClass.hasType(VT))
21841 Res.second = &X86::VR512RegClass;
21847 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
21849 // Scaling factors are not free at all.
21850 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
21851 // will take 2 allocations in the out of order engine instead of 1
21852 // for plain addressing mode, i.e. inst (reg1).
21854 // vaddps (%rsi,%drx), %ymm0, %ymm1
21855 // Requires two allocations (one for the load, one for the computation)
21857 // vaddps (%rsi), %ymm0, %ymm1
21858 // Requires just 1 allocation, i.e., freeing allocations for other operations
21859 // and having less micro operations to execute.
21861 // For some X86 architectures, this is even worse because for instance for
21862 // stores, the complex addressing mode forces the instruction to use the
21863 // "load" ports instead of the dedicated "store" port.
21864 // E.g., on Haswell:
21865 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
21866 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
21867 if (isLegalAddressingMode(AM, Ty))
21868 // Scale represents reg2 * scale, thus account for 1
21869 // as soon as we use a second register.
21870 return AM.Scale != 0;
21874 bool X86TargetLowering::isTargetFTOL() const {
21875 return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();