1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86InstrBuilder.h"
19 #include "X86MachineFunctionInfo.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/StringSwitch.h"
26 #include "llvm/ADT/VariadicFunction.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineJumpTableInfo.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/IR/CallSite.h"
35 #include "llvm/IR/CallingConv.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/DerivedTypes.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/GlobalAlias.h"
40 #include "llvm/IR/GlobalVariable.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/Intrinsics.h"
43 #include "llvm/MC/MCAsmInfo.h"
44 #include "llvm/MC/MCContext.h"
45 #include "llvm/MC/MCExpr.h"
46 #include "llvm/MC/MCSymbol.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Target/TargetOptions.h"
55 #define DEBUG_TYPE "x86-isel"
57 STATISTIC(NumTailCalls, "Number of tail calls");
59 // Forward declarations.
60 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
63 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
64 SelectionDAG &DAG, SDLoc dl,
65 unsigned vectorWidth) {
66 assert((vectorWidth == 128 || vectorWidth == 256) &&
67 "Unsupported vector width");
68 EVT VT = Vec.getValueType();
69 EVT ElVT = VT.getVectorElementType();
70 unsigned Factor = VT.getSizeInBits()/vectorWidth;
71 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
72 VT.getVectorNumElements()/Factor);
74 // Extract from UNDEF is UNDEF.
75 if (Vec.getOpcode() == ISD::UNDEF)
76 return DAG.getUNDEF(ResultVT);
78 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
79 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
81 // This is the index of the first element of the vectorWidth-bit chunk
83 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
86 // If the input is a buildvector just emit a smaller one.
87 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
88 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
89 makeArrayRef(Vec->op_begin()+NormalizedIdxVal,
92 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
93 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
99 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
100 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
101 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
102 /// instructions or a simple subregister reference. Idx is an index in the
103 /// 128 bits we want. It need not be aligned to a 128-bit bounday. That makes
104 /// lowering EXTRACT_VECTOR_ELT operations easier.
105 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
106 SelectionDAG &DAG, SDLoc dl) {
107 assert((Vec.getValueType().is256BitVector() ||
108 Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
109 return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
112 /// Generate a DAG to grab 256-bits from a 512-bit vector.
113 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
114 SelectionDAG &DAG, SDLoc dl) {
115 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
116 return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
119 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
120 unsigned IdxVal, SelectionDAG &DAG,
121 SDLoc dl, unsigned vectorWidth) {
122 assert((vectorWidth == 128 || vectorWidth == 256) &&
123 "Unsupported vector width");
124 // Inserting UNDEF is Result
125 if (Vec.getOpcode() == ISD::UNDEF)
127 EVT VT = Vec.getValueType();
128 EVT ElVT = VT.getVectorElementType();
129 EVT ResultVT = Result.getValueType();
131 // Insert the relevant vectorWidth bits.
132 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
134 // This is the index of the first element of the vectorWidth-bit chunk
136 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
139 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
140 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
143 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
144 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
145 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
146 /// simple superregister reference. Idx is an index in the 128 bits
147 /// we want. It need not be aligned to a 128-bit bounday. That makes
148 /// lowering INSERT_VECTOR_ELT operations easier.
149 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
150 unsigned IdxVal, SelectionDAG &DAG,
152 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
153 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
156 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
157 unsigned IdxVal, SelectionDAG &DAG,
159 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
160 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
163 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
164 /// instructions. This is used because creating CONCAT_VECTOR nodes of
165 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
166 /// large BUILD_VECTORS.
167 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
168 unsigned NumElems, SelectionDAG &DAG,
170 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
171 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
174 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
175 unsigned NumElems, SelectionDAG &DAG,
177 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
178 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
181 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
182 if (TT.isOSBinFormatMachO()) {
183 if (TT.getArch() == Triple::x86_64)
184 return new X86_64MachoTargetObjectFile();
185 return new TargetLoweringObjectFileMachO();
189 return new X86LinuxTargetObjectFile();
190 if (TT.isOSBinFormatELF())
191 return new TargetLoweringObjectFileELF();
192 if (TT.isKnownWindowsMSVCEnvironment())
193 return new X86WindowsTargetObjectFile();
194 if (TT.isOSBinFormatCOFF())
195 return new TargetLoweringObjectFileCOFF();
196 llvm_unreachable("unknown subtarget type");
199 // FIXME: This should stop caching the target machine as soon as
200 // we can remove resetOperationActions et al.
201 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
202 : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
203 Subtarget = &TM.getSubtarget<X86Subtarget>();
204 X86ScalarSSEf64 = Subtarget->hasSSE2();
205 X86ScalarSSEf32 = Subtarget->hasSSE1();
206 TD = getDataLayout();
208 resetOperationActions();
211 void X86TargetLowering::resetOperationActions() {
212 const TargetMachine &TM = getTargetMachine();
213 static bool FirstTimeThrough = true;
215 // If none of the target options have changed, then we don't need to reset the
216 // operation actions.
217 if (!FirstTimeThrough && TO == TM.Options) return;
219 if (!FirstTimeThrough) {
220 // Reinitialize the actions.
222 FirstTimeThrough = false;
227 // Set up the TargetLowering object.
228 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
230 // X86 is weird, it always uses i8 for shift amounts and setcc results.
231 setBooleanContents(ZeroOrOneBooleanContent);
232 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
233 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
235 // For 64-bit since we have so many registers use the ILP scheduler, for
236 // 32-bit code use the register pressure specific scheduling.
237 // For Atom, always use ILP scheduling.
238 if (Subtarget->isAtom())
239 setSchedulingPreference(Sched::ILP);
240 else if (Subtarget->is64Bit())
241 setSchedulingPreference(Sched::ILP);
243 setSchedulingPreference(Sched::RegPressure);
244 const X86RegisterInfo *RegInfo =
245 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
246 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
248 // Bypass expensive divides on Atom when compiling with O2
249 if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
250 addBypassSlowDiv(32, 8);
251 if (Subtarget->is64Bit())
252 addBypassSlowDiv(64, 16);
255 if (Subtarget->isTargetKnownWindowsMSVC()) {
256 // Setup Windows compiler runtime calls.
257 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
258 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
259 setLibcallName(RTLIB::SREM_I64, "_allrem");
260 setLibcallName(RTLIB::UREM_I64, "_aullrem");
261 setLibcallName(RTLIB::MUL_I64, "_allmul");
262 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
263 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
264 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
265 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
266 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
268 // The _ftol2 runtime function has an unusual calling conv, which
269 // is modeled by a special pseudo-instruction.
270 setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
271 setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
272 setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
273 setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
276 if (Subtarget->isTargetDarwin()) {
277 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
278 setUseUnderscoreSetJmp(false);
279 setUseUnderscoreLongJmp(false);
280 } else if (Subtarget->isTargetWindowsGNU()) {
281 // MS runtime is weird: it exports _setjmp, but longjmp!
282 setUseUnderscoreSetJmp(true);
283 setUseUnderscoreLongJmp(false);
285 setUseUnderscoreSetJmp(true);
286 setUseUnderscoreLongJmp(true);
289 // Set up the register classes.
290 addRegisterClass(MVT::i8, &X86::GR8RegClass);
291 addRegisterClass(MVT::i16, &X86::GR16RegClass);
292 addRegisterClass(MVT::i32, &X86::GR32RegClass);
293 if (Subtarget->is64Bit())
294 addRegisterClass(MVT::i64, &X86::GR64RegClass);
296 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
298 // We don't accept any truncstore of integer registers.
299 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
300 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
301 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
302 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
303 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
304 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
306 // SETOEQ and SETUNE require checking two conditions.
307 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
308 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
309 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
310 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
311 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
312 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
314 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
316 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
317 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
318 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
320 if (Subtarget->is64Bit()) {
321 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
322 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
323 } else if (!TM.Options.UseSoftFloat) {
324 // We have an algorithm for SSE2->double, and we turn this into a
325 // 64-bit FILD followed by conditional FADD for other targets.
326 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
327 // We have an algorithm for SSE2, and we turn this into a 64-bit
328 // FILD for other targets.
329 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
332 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
334 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
335 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
337 if (!TM.Options.UseSoftFloat) {
338 // SSE has no i16 to fp conversion, only i32
339 if (X86ScalarSSEf32) {
340 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
341 // f32 and f64 cases are Legal, f80 case is not
342 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
344 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
345 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
348 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
349 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
352 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
353 // are Legal, f80 is custom lowered.
354 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
355 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
357 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
359 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
360 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
362 if (X86ScalarSSEf32) {
363 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
364 // f32 and f64 cases are Legal, f80 case is not
365 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
367 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
368 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
371 // Handle FP_TO_UINT by promoting the destination to a larger signed
373 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
374 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
375 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
377 if (Subtarget->is64Bit()) {
378 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
379 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
380 } else if (!TM.Options.UseSoftFloat) {
381 // Since AVX is a superset of SSE3, only check for SSE here.
382 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
383 // Expand FP_TO_UINT into a select.
384 // FIXME: We would like to use a Custom expander here eventually to do
385 // the optimal thing for SSE vs. the default expansion in the legalizer.
386 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
388 // With SSE3 we can use fisttpll to convert to a signed i64; without
389 // SSE, we're stuck with a fistpll.
390 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
393 if (isTargetFTOL()) {
394 // Use the _ftol2 runtime function, which has a pseudo-instruction
395 // to handle its weird calling convention.
396 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
399 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
400 if (!X86ScalarSSEf64) {
401 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
402 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
403 if (Subtarget->is64Bit()) {
404 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
405 // Without SSE, i64->f64 goes through memory.
406 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
410 // Scalar integer divide and remainder are lowered to use operations that
411 // produce two results, to match the available instructions. This exposes
412 // the two-result form to trivial CSE, which is able to combine x/y and x%y
413 // into a single instruction.
415 // Scalar integer multiply-high is also lowered to use two-result
416 // operations, to match the available instructions. However, plain multiply
417 // (low) operations are left as Legal, as there are single-result
418 // instructions for this in x86. Using the two-result multiply instructions
419 // when both high and low results are needed must be arranged by dagcombine.
420 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
422 setOperationAction(ISD::MULHS, VT, Expand);
423 setOperationAction(ISD::MULHU, VT, Expand);
424 setOperationAction(ISD::SDIV, VT, Expand);
425 setOperationAction(ISD::UDIV, VT, Expand);
426 setOperationAction(ISD::SREM, VT, Expand);
427 setOperationAction(ISD::UREM, VT, Expand);
429 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
430 setOperationAction(ISD::ADDC, VT, Custom);
431 setOperationAction(ISD::ADDE, VT, Custom);
432 setOperationAction(ISD::SUBC, VT, Custom);
433 setOperationAction(ISD::SUBE, VT, Custom);
436 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
437 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
438 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
439 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
440 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
441 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
442 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
443 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
444 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
445 setOperationAction(ISD::SELECT_CC , MVT::f32, Expand);
446 setOperationAction(ISD::SELECT_CC , MVT::f64, Expand);
447 setOperationAction(ISD::SELECT_CC , MVT::f80, Expand);
448 setOperationAction(ISD::SELECT_CC , MVT::i8, Expand);
449 setOperationAction(ISD::SELECT_CC , MVT::i16, Expand);
450 setOperationAction(ISD::SELECT_CC , MVT::i32, Expand);
451 setOperationAction(ISD::SELECT_CC , MVT::i64, Expand);
452 if (Subtarget->is64Bit())
453 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
454 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
455 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
456 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
457 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
458 setOperationAction(ISD::FREM , MVT::f32 , Expand);
459 setOperationAction(ISD::FREM , MVT::f64 , Expand);
460 setOperationAction(ISD::FREM , MVT::f80 , Expand);
461 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
463 // Promote the i8 variants and force them on up to i32 which has a shorter
465 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
466 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
467 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
468 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
469 if (Subtarget->hasBMI()) {
470 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
471 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
472 if (Subtarget->is64Bit())
473 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
475 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
476 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
477 if (Subtarget->is64Bit())
478 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
481 if (Subtarget->hasLZCNT()) {
482 // When promoting the i8 variants, force them to i32 for a shorter
484 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
485 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
486 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
487 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
488 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
489 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
490 if (Subtarget->is64Bit())
491 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
493 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
494 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
495 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
496 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
497 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
498 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
499 if (Subtarget->is64Bit()) {
500 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
501 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
505 if (Subtarget->hasPOPCNT()) {
506 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
508 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
509 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
510 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
511 if (Subtarget->is64Bit())
512 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
515 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
517 if (!Subtarget->hasMOVBE())
518 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
520 // These should be promoted to a larger select which is supported.
521 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
522 // X86 wants to expand cmov itself.
523 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
524 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
525 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
526 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
527 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
528 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
529 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
530 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
531 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
532 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
533 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
534 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
535 if (Subtarget->is64Bit()) {
536 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
537 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
539 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
540 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
541 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
542 // support continuation, user-level threading, and etc.. As a result, no
543 // other SjLj exception interfaces are implemented and please don't build
544 // your own exception handling based on them.
545 // LLVM/Clang supports zero-cost DWARF exception handling.
546 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
547 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
550 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
551 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
552 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
553 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
554 if (Subtarget->is64Bit())
555 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
556 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
557 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
558 if (Subtarget->is64Bit()) {
559 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
560 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
561 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
562 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
563 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
565 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
566 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
567 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
568 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
569 if (Subtarget->is64Bit()) {
570 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
571 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
572 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
575 if (Subtarget->hasSSE1())
576 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
578 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
580 // Expand certain atomics
581 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
583 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
584 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
585 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
588 if (!Subtarget->is64Bit()) {
589 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
590 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
591 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
592 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
593 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
594 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
595 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
596 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
597 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
598 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
599 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
600 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
603 if (Subtarget->hasCmpxchg16b()) {
604 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
607 // FIXME - use subtarget debug flags
608 if (!Subtarget->isTargetDarwin() &&
609 !Subtarget->isTargetELF() &&
610 !Subtarget->isTargetCygMing()) {
611 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
614 if (Subtarget->is64Bit()) {
615 setExceptionPointerRegister(X86::RAX);
616 setExceptionSelectorRegister(X86::RDX);
618 setExceptionPointerRegister(X86::EAX);
619 setExceptionSelectorRegister(X86::EDX);
621 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
622 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
624 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
625 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
627 setOperationAction(ISD::TRAP, MVT::Other, Legal);
628 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
630 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
631 setOperationAction(ISD::VASTART , MVT::Other, Custom);
632 setOperationAction(ISD::VAEND , MVT::Other, Expand);
633 if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
634 // TargetInfo::X86_64ABIBuiltinVaList
635 setOperationAction(ISD::VAARG , MVT::Other, Custom);
636 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
638 // TargetInfo::CharPtrBuiltinVaList
639 setOperationAction(ISD::VAARG , MVT::Other, Expand);
640 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
643 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
644 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
646 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
647 MVT::i64 : MVT::i32, Custom);
649 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
650 // f32 and f64 use SSE.
651 // Set up the FP register classes.
652 addRegisterClass(MVT::f32, &X86::FR32RegClass);
653 addRegisterClass(MVT::f64, &X86::FR64RegClass);
655 // Use ANDPD to simulate FABS.
656 setOperationAction(ISD::FABS , MVT::f64, Custom);
657 setOperationAction(ISD::FABS , MVT::f32, Custom);
659 // Use XORP to simulate FNEG.
660 setOperationAction(ISD::FNEG , MVT::f64, Custom);
661 setOperationAction(ISD::FNEG , MVT::f32, Custom);
663 // Use ANDPD and ORPD to simulate FCOPYSIGN.
664 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
665 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
667 // Lower this to FGETSIGNx86 plus an AND.
668 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
669 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
671 // We don't support sin/cos/fmod
672 setOperationAction(ISD::FSIN , MVT::f64, Expand);
673 setOperationAction(ISD::FCOS , MVT::f64, Expand);
674 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
675 setOperationAction(ISD::FSIN , MVT::f32, Expand);
676 setOperationAction(ISD::FCOS , MVT::f32, Expand);
677 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
679 // Expand FP immediates into loads from the stack, except for the special
681 addLegalFPImmediate(APFloat(+0.0)); // xorpd
682 addLegalFPImmediate(APFloat(+0.0f)); // xorps
683 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
684 // Use SSE for f32, x87 for f64.
685 // Set up the FP register classes.
686 addRegisterClass(MVT::f32, &X86::FR32RegClass);
687 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
689 // Use ANDPS to simulate FABS.
690 setOperationAction(ISD::FABS , MVT::f32, Custom);
692 // Use XORP to simulate FNEG.
693 setOperationAction(ISD::FNEG , MVT::f32, Custom);
695 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
697 // Use ANDPS and ORPS to simulate FCOPYSIGN.
698 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
699 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
701 // We don't support sin/cos/fmod
702 setOperationAction(ISD::FSIN , MVT::f32, Expand);
703 setOperationAction(ISD::FCOS , MVT::f32, Expand);
704 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
706 // Special cases we handle for FP constants.
707 addLegalFPImmediate(APFloat(+0.0f)); // xorps
708 addLegalFPImmediate(APFloat(+0.0)); // FLD0
709 addLegalFPImmediate(APFloat(+1.0)); // FLD1
710 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
711 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
713 if (!TM.Options.UnsafeFPMath) {
714 setOperationAction(ISD::FSIN , MVT::f64, Expand);
715 setOperationAction(ISD::FCOS , MVT::f64, Expand);
716 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
718 } else if (!TM.Options.UseSoftFloat) {
719 // f32 and f64 in x87.
720 // Set up the FP register classes.
721 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
722 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
724 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
725 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
726 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
727 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
729 if (!TM.Options.UnsafeFPMath) {
730 setOperationAction(ISD::FSIN , MVT::f64, Expand);
731 setOperationAction(ISD::FSIN , MVT::f32, Expand);
732 setOperationAction(ISD::FCOS , MVT::f64, Expand);
733 setOperationAction(ISD::FCOS , MVT::f32, Expand);
734 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
735 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
737 addLegalFPImmediate(APFloat(+0.0)); // FLD0
738 addLegalFPImmediate(APFloat(+1.0)); // FLD1
739 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
740 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
741 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
742 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
743 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
744 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
747 // We don't support FMA.
748 setOperationAction(ISD::FMA, MVT::f64, Expand);
749 setOperationAction(ISD::FMA, MVT::f32, Expand);
751 // Long double always uses X87.
752 if (!TM.Options.UseSoftFloat) {
753 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
754 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
755 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
757 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
758 addLegalFPImmediate(TmpFlt); // FLD0
760 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
763 APFloat TmpFlt2(+1.0);
764 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
766 addLegalFPImmediate(TmpFlt2); // FLD1
767 TmpFlt2.changeSign();
768 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
771 if (!TM.Options.UnsafeFPMath) {
772 setOperationAction(ISD::FSIN , MVT::f80, Expand);
773 setOperationAction(ISD::FCOS , MVT::f80, Expand);
774 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
777 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
778 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
779 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
780 setOperationAction(ISD::FRINT, MVT::f80, Expand);
781 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
782 setOperationAction(ISD::FMA, MVT::f80, Expand);
785 // Always use a library call for pow.
786 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
787 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
788 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
790 setOperationAction(ISD::FLOG, MVT::f80, Expand);
791 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
792 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
793 setOperationAction(ISD::FEXP, MVT::f80, Expand);
794 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
796 // First set operation action for all vector types to either promote
797 // (for widening) or expand (for scalarization). Then we will selectively
798 // turn on ones that can be effectively codegen'd.
799 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
800 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
801 MVT VT = (MVT::SimpleValueType)i;
802 setOperationAction(ISD::ADD , VT, Expand);
803 setOperationAction(ISD::SUB , VT, Expand);
804 setOperationAction(ISD::FADD, VT, Expand);
805 setOperationAction(ISD::FNEG, VT, Expand);
806 setOperationAction(ISD::FSUB, VT, Expand);
807 setOperationAction(ISD::MUL , VT, Expand);
808 setOperationAction(ISD::FMUL, VT, Expand);
809 setOperationAction(ISD::SDIV, VT, Expand);
810 setOperationAction(ISD::UDIV, VT, Expand);
811 setOperationAction(ISD::FDIV, VT, Expand);
812 setOperationAction(ISD::SREM, VT, Expand);
813 setOperationAction(ISD::UREM, VT, Expand);
814 setOperationAction(ISD::LOAD, VT, Expand);
815 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
816 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
817 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
818 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
819 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
820 setOperationAction(ISD::FABS, VT, Expand);
821 setOperationAction(ISD::FSIN, VT, Expand);
822 setOperationAction(ISD::FSINCOS, VT, Expand);
823 setOperationAction(ISD::FCOS, VT, Expand);
824 setOperationAction(ISD::FSINCOS, VT, Expand);
825 setOperationAction(ISD::FREM, VT, Expand);
826 setOperationAction(ISD::FMA, VT, Expand);
827 setOperationAction(ISD::FPOWI, VT, Expand);
828 setOperationAction(ISD::FSQRT, VT, Expand);
829 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
830 setOperationAction(ISD::FFLOOR, VT, Expand);
831 setOperationAction(ISD::FCEIL, VT, Expand);
832 setOperationAction(ISD::FTRUNC, VT, Expand);
833 setOperationAction(ISD::FRINT, VT, Expand);
834 setOperationAction(ISD::FNEARBYINT, VT, Expand);
835 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
836 setOperationAction(ISD::MULHS, VT, Expand);
837 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
838 setOperationAction(ISD::MULHU, VT, Expand);
839 setOperationAction(ISD::SDIVREM, VT, Expand);
840 setOperationAction(ISD::UDIVREM, VT, Expand);
841 setOperationAction(ISD::FPOW, VT, Expand);
842 setOperationAction(ISD::CTPOP, VT, Expand);
843 setOperationAction(ISD::CTTZ, VT, Expand);
844 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
845 setOperationAction(ISD::CTLZ, VT, Expand);
846 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
847 setOperationAction(ISD::SHL, VT, Expand);
848 setOperationAction(ISD::SRA, VT, Expand);
849 setOperationAction(ISD::SRL, VT, Expand);
850 setOperationAction(ISD::ROTL, VT, Expand);
851 setOperationAction(ISD::ROTR, VT, Expand);
852 setOperationAction(ISD::BSWAP, VT, Expand);
853 setOperationAction(ISD::SETCC, VT, Expand);
854 setOperationAction(ISD::FLOG, VT, Expand);
855 setOperationAction(ISD::FLOG2, VT, Expand);
856 setOperationAction(ISD::FLOG10, VT, Expand);
857 setOperationAction(ISD::FEXP, VT, Expand);
858 setOperationAction(ISD::FEXP2, VT, Expand);
859 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
860 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
861 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
862 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
863 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
864 setOperationAction(ISD::TRUNCATE, VT, Expand);
865 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
866 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
867 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
868 setOperationAction(ISD::VSELECT, VT, Expand);
869 setOperationAction(ISD::SELECT_CC, VT, Expand);
870 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
871 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
872 setTruncStoreAction(VT,
873 (MVT::SimpleValueType)InnerVT, Expand);
874 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
875 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
876 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
879 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
880 // with -msoft-float, disable use of MMX as well.
881 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
882 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
883 // No operations on x86mmx supported, everything uses intrinsics.
886 // MMX-sized vectors (other than x86mmx) are expected to be expanded
887 // into smaller operations.
888 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
889 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
890 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
891 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
892 setOperationAction(ISD::AND, MVT::v8i8, Expand);
893 setOperationAction(ISD::AND, MVT::v4i16, Expand);
894 setOperationAction(ISD::AND, MVT::v2i32, Expand);
895 setOperationAction(ISD::AND, MVT::v1i64, Expand);
896 setOperationAction(ISD::OR, MVT::v8i8, Expand);
897 setOperationAction(ISD::OR, MVT::v4i16, Expand);
898 setOperationAction(ISD::OR, MVT::v2i32, Expand);
899 setOperationAction(ISD::OR, MVT::v1i64, Expand);
900 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
901 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
902 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
903 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
904 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
905 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
906 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
907 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
908 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
909 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
910 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
911 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
912 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
913 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
914 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
915 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
916 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
918 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
919 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
921 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
922 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
923 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
924 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
925 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
926 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
927 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
928 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
929 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
930 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
931 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
932 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
935 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
936 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
938 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
939 // registers cannot be used even for integer operations.
940 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
941 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
942 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
943 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
945 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
946 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
947 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
948 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
949 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
950 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
951 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
952 setOperationAction(ISD::SMUL_LOHI, MVT::v4i32, Custom);
953 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
954 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
955 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
956 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
957 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
958 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
959 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
960 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
961 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
962 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
963 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
964 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
965 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
966 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
968 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
969 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
970 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
971 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
973 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
974 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
975 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
976 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
977 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
979 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
980 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
981 MVT VT = (MVT::SimpleValueType)i;
982 // Do not attempt to custom lower non-power-of-2 vectors
983 if (!isPowerOf2_32(VT.getVectorNumElements()))
985 // Do not attempt to custom lower non-128-bit vectors
986 if (!VT.is128BitVector())
988 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
989 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
990 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
993 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
994 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
995 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
996 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
997 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
998 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
1000 if (Subtarget->is64Bit()) {
1001 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1002 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1005 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1006 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1007 MVT VT = (MVT::SimpleValueType)i;
1009 // Do not attempt to promote non-128-bit vectors
1010 if (!VT.is128BitVector())
1013 setOperationAction(ISD::AND, VT, Promote);
1014 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
1015 setOperationAction(ISD::OR, VT, Promote);
1016 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
1017 setOperationAction(ISD::XOR, VT, Promote);
1018 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
1019 setOperationAction(ISD::LOAD, VT, Promote);
1020 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
1021 setOperationAction(ISD::SELECT, VT, Promote);
1022 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1025 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1027 // Custom lower v2i64 and v2f64 selects.
1028 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
1029 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
1030 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
1031 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
1033 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1034 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1036 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1037 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1038 // As there is no 64-bit GPR available, we need build a special custom
1039 // sequence to convert from v2i32 to v2f32.
1040 if (!Subtarget->is64Bit())
1041 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
1043 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1044 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
1046 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
1048 setOperationAction(ISD::BITCAST, MVT::v2i32, Custom);
1049 setOperationAction(ISD::BITCAST, MVT::v4i16, Custom);
1050 setOperationAction(ISD::BITCAST, MVT::v8i8, Custom);
1053 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1054 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1055 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1056 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1057 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1058 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1059 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1060 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1061 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1062 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1063 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1065 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1066 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
1067 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1068 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
1069 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
1070 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
1071 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
1072 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
1073 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
1074 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
1076 // FIXME: Do we need to handle scalar-to-vector here?
1077 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1079 setOperationAction(ISD::VSELECT, MVT::v2f64, Custom);
1080 setOperationAction(ISD::VSELECT, MVT::v2i64, Custom);
1081 setOperationAction(ISD::VSELECT, MVT::v4i32, Custom);
1082 setOperationAction(ISD::VSELECT, MVT::v4f32, Custom);
1083 setOperationAction(ISD::VSELECT, MVT::v8i16, Custom);
1084 // There is no BLENDI for byte vectors. We don't need to custom lower
1085 // some vselects for now.
1086 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
1088 // i8 and i16 vectors are custom , because the source register and source
1089 // source memory operand types are not the same width. f32 vectors are
1090 // custom since the immediate controlling the insert encodes additional
1092 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1093 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1094 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1095 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1097 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1098 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1099 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1100 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1102 // FIXME: these should be Legal but thats only for the case where
1103 // the index is constant. For now custom expand to deal with that.
1104 if (Subtarget->is64Bit()) {
1105 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1106 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1110 if (Subtarget->hasSSE2()) {
1111 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1112 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1114 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1115 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1117 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1118 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1120 // In the customized shift lowering, the legal cases in AVX2 will be
1122 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1123 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1125 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1126 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1128 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1131 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1132 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1133 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1134 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1135 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1136 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1137 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1139 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1140 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1141 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1143 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1144 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1145 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1146 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1147 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1148 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1149 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1150 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1151 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1152 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1153 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1154 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1156 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1157 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1158 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1159 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1160 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1161 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1162 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1163 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1164 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1165 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1166 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1167 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1169 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1170 // even though v8i16 is a legal type.
1171 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1172 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1173 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1175 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1176 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1177 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1179 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1180 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1182 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1184 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1185 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1187 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1188 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1190 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1191 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1193 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1194 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1195 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1196 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1198 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1199 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1200 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1202 setOperationAction(ISD::VSELECT, MVT::v4f64, Custom);
1203 setOperationAction(ISD::VSELECT, MVT::v4i64, Custom);
1204 setOperationAction(ISD::VSELECT, MVT::v8i32, Custom);
1205 setOperationAction(ISD::VSELECT, MVT::v8f32, Custom);
1207 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1208 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1209 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1210 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1211 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1212 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1213 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1214 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1215 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1216 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1217 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1218 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1220 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1221 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1222 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1223 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1224 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1225 setOperationAction(ISD::FMA, MVT::f32, Legal);
1226 setOperationAction(ISD::FMA, MVT::f64, Legal);
1229 if (Subtarget->hasInt256()) {
1230 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1231 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1232 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1233 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1235 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1236 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1237 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1238 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1240 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1241 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1242 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1243 // Don't lower v32i8 because there is no 128-bit byte mul
1245 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1246 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1247 setOperationAction(ISD::MULHU, MVT::v16i16, Legal);
1248 setOperationAction(ISD::MULHS, MVT::v16i16, Legal);
1250 setOperationAction(ISD::VSELECT, MVT::v16i16, Custom);
1251 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1253 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1254 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1255 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1256 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1258 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1259 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1260 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1261 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1263 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1264 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1265 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1266 // Don't lower v32i8 because there is no 128-bit byte mul
1269 // In the customized shift lowering, the legal cases in AVX2 will be
1271 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1272 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1274 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1275 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1277 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1279 // Custom lower several nodes for 256-bit types.
1280 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1281 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1282 MVT VT = (MVT::SimpleValueType)i;
1284 // Extract subvector is special because the value type
1285 // (result) is 128-bit but the source is 256-bit wide.
1286 if (VT.is128BitVector())
1287 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1289 // Do not attempt to custom lower other non-256-bit vectors
1290 if (!VT.is256BitVector())
1293 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1294 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1295 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1296 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1297 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1298 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1299 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1302 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1303 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1304 MVT VT = (MVT::SimpleValueType)i;
1306 // Do not attempt to promote non-256-bit vectors
1307 if (!VT.is256BitVector())
1310 setOperationAction(ISD::AND, VT, Promote);
1311 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1312 setOperationAction(ISD::OR, VT, Promote);
1313 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1314 setOperationAction(ISD::XOR, VT, Promote);
1315 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1316 setOperationAction(ISD::LOAD, VT, Promote);
1317 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1318 setOperationAction(ISD::SELECT, VT, Promote);
1319 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1323 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1324 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1325 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1326 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1327 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1329 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1330 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1331 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1333 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1334 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1335 setOperationAction(ISD::XOR, MVT::i1, Legal);
1336 setOperationAction(ISD::OR, MVT::i1, Legal);
1337 setOperationAction(ISD::AND, MVT::i1, Legal);
1338 setLoadExtAction(ISD::EXTLOAD, MVT::v8f32, Legal);
1339 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1340 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1341 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1342 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1343 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1345 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1346 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1347 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1348 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1349 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1350 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1352 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1353 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1354 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1355 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1356 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1357 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1358 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1359 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1361 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1362 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1363 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1364 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1365 if (Subtarget->is64Bit()) {
1366 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1367 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1368 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1369 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1371 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1372 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1373 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1374 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1375 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1376 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1377 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1378 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1379 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1380 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1382 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1383 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1384 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1385 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1386 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1387 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1388 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1389 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1390 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1391 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1392 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1393 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1394 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1396 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1397 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1398 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1399 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1400 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1401 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1403 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1404 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1406 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1408 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1409 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1410 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1411 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1412 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1413 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1414 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1415 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1416 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1418 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1419 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1421 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1422 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1424 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1426 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1427 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1429 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1430 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1432 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1433 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1435 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1436 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1437 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1438 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1439 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1440 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1442 if (Subtarget->hasCDI()) {
1443 setOperationAction(ISD::CTLZ, MVT::v8i64, Legal);
1444 setOperationAction(ISD::CTLZ, MVT::v16i32, Legal);
1447 // Custom lower several nodes.
1448 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1449 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1450 MVT VT = (MVT::SimpleValueType)i;
1452 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1453 // Extract subvector is special because the value type
1454 // (result) is 256/128-bit but the source is 512-bit wide.
1455 if (VT.is128BitVector() || VT.is256BitVector())
1456 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1458 if (VT.getVectorElementType() == MVT::i1)
1459 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1461 // Do not attempt to custom lower other non-512-bit vectors
1462 if (!VT.is512BitVector())
1465 if ( EltSize >= 32) {
1466 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1467 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1468 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1469 setOperationAction(ISD::VSELECT, VT, Legal);
1470 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1471 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1472 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1475 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1476 MVT VT = (MVT::SimpleValueType)i;
1478 // Do not attempt to promote non-256-bit vectors
1479 if (!VT.is512BitVector())
1482 setOperationAction(ISD::SELECT, VT, Promote);
1483 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1487 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1488 // of this type with custom code.
1489 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1490 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1491 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1495 // We want to custom lower some of our intrinsics.
1496 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1497 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1498 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1499 if (!Subtarget->is64Bit())
1500 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1502 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1503 // handle type legalization for these operations here.
1505 // FIXME: We really should do custom legalization for addition and
1506 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1507 // than generic legalization for 64-bit multiplication-with-overflow, though.
1508 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1509 // Add/Sub/Mul with overflow operations are custom lowered.
1511 setOperationAction(ISD::SADDO, VT, Custom);
1512 setOperationAction(ISD::UADDO, VT, Custom);
1513 setOperationAction(ISD::SSUBO, VT, Custom);
1514 setOperationAction(ISD::USUBO, VT, Custom);
1515 setOperationAction(ISD::SMULO, VT, Custom);
1516 setOperationAction(ISD::UMULO, VT, Custom);
1519 // There are no 8-bit 3-address imul/mul instructions
1520 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1521 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1523 if (!Subtarget->is64Bit()) {
1524 // These libcalls are not available in 32-bit.
1525 setLibcallName(RTLIB::SHL_I128, nullptr);
1526 setLibcallName(RTLIB::SRL_I128, nullptr);
1527 setLibcallName(RTLIB::SRA_I128, nullptr);
1530 // Combine sin / cos into one node or libcall if possible.
1531 if (Subtarget->hasSinCos()) {
1532 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1533 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1534 if (Subtarget->isTargetDarwin()) {
1535 // For MacOSX, we don't want to the normal expansion of a libcall to
1536 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1538 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1539 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1543 if (Subtarget->isTargetWin64()) {
1544 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1545 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1546 setOperationAction(ISD::SREM, MVT::i128, Custom);
1547 setOperationAction(ISD::UREM, MVT::i128, Custom);
1548 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1549 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1552 // We have target-specific dag combine patterns for the following nodes:
1553 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1554 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1555 setTargetDAGCombine(ISD::VSELECT);
1556 setTargetDAGCombine(ISD::SELECT);
1557 setTargetDAGCombine(ISD::SHL);
1558 setTargetDAGCombine(ISD::SRA);
1559 setTargetDAGCombine(ISD::SRL);
1560 setTargetDAGCombine(ISD::OR);
1561 setTargetDAGCombine(ISD::AND);
1562 setTargetDAGCombine(ISD::ADD);
1563 setTargetDAGCombine(ISD::FADD);
1564 setTargetDAGCombine(ISD::FSUB);
1565 setTargetDAGCombine(ISD::FMA);
1566 setTargetDAGCombine(ISD::SUB);
1567 setTargetDAGCombine(ISD::LOAD);
1568 setTargetDAGCombine(ISD::STORE);
1569 setTargetDAGCombine(ISD::ZERO_EXTEND);
1570 setTargetDAGCombine(ISD::ANY_EXTEND);
1571 setTargetDAGCombine(ISD::SIGN_EXTEND);
1572 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1573 setTargetDAGCombine(ISD::TRUNCATE);
1574 setTargetDAGCombine(ISD::SINT_TO_FP);
1575 setTargetDAGCombine(ISD::SETCC);
1576 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1577 setTargetDAGCombine(ISD::BUILD_VECTOR);
1578 if (Subtarget->is64Bit())
1579 setTargetDAGCombine(ISD::MUL);
1580 setTargetDAGCombine(ISD::XOR);
1582 computeRegisterProperties();
1584 // On Darwin, -Os means optimize for size without hurting performance,
1585 // do not reduce the limit.
1586 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1587 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1588 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1589 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1590 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1591 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1592 setPrefLoopAlignment(4); // 2^4 bytes.
1594 // Predictable cmov don't hurt on atom because it's in-order.
1595 PredictableSelectIsExpensive = !Subtarget->isAtom();
1597 setPrefFunctionAlignment(4); // 2^4 bytes.
1600 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1602 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1604 if (Subtarget->hasAVX512())
1605 switch(VT.getVectorNumElements()) {
1606 case 8: return MVT::v8i1;
1607 case 16: return MVT::v16i1;
1610 return VT.changeVectorElementTypeToInteger();
1613 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1614 /// the desired ByVal argument alignment.
1615 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1618 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1619 if (VTy->getBitWidth() == 128)
1621 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1622 unsigned EltAlign = 0;
1623 getMaxByValAlign(ATy->getElementType(), EltAlign);
1624 if (EltAlign > MaxAlign)
1625 MaxAlign = EltAlign;
1626 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1627 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1628 unsigned EltAlign = 0;
1629 getMaxByValAlign(STy->getElementType(i), EltAlign);
1630 if (EltAlign > MaxAlign)
1631 MaxAlign = EltAlign;
1638 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1639 /// function arguments in the caller parameter area. For X86, aggregates
1640 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1641 /// are at 4-byte boundaries.
1642 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1643 if (Subtarget->is64Bit()) {
1644 // Max of 8 and alignment of type.
1645 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1652 if (Subtarget->hasSSE1())
1653 getMaxByValAlign(Ty, Align);
1657 /// getOptimalMemOpType - Returns the target specific optimal type for load
1658 /// and store operations as a result of memset, memcpy, and memmove
1659 /// lowering. If DstAlign is zero that means it's safe to destination
1660 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1661 /// means there isn't a need to check it against alignment requirement,
1662 /// probably because the source does not need to be loaded. If 'IsMemset' is
1663 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1664 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1665 /// source is constant so it does not need to be loaded.
1666 /// It returns EVT::Other if the type should be determined using generic
1667 /// target-independent logic.
1669 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1670 unsigned DstAlign, unsigned SrcAlign,
1671 bool IsMemset, bool ZeroMemset,
1673 MachineFunction &MF) const {
1674 const Function *F = MF.getFunction();
1675 if ((!IsMemset || ZeroMemset) &&
1676 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1677 Attribute::NoImplicitFloat)) {
1679 (Subtarget->isUnalignedMemAccessFast() ||
1680 ((DstAlign == 0 || DstAlign >= 16) &&
1681 (SrcAlign == 0 || SrcAlign >= 16)))) {
1683 if (Subtarget->hasInt256())
1685 if (Subtarget->hasFp256())
1688 if (Subtarget->hasSSE2())
1690 if (Subtarget->hasSSE1())
1692 } else if (!MemcpyStrSrc && Size >= 8 &&
1693 !Subtarget->is64Bit() &&
1694 Subtarget->hasSSE2()) {
1695 // Do not use f64 to lower memcpy if source is string constant. It's
1696 // better to use i32 to avoid the loads.
1700 if (Subtarget->is64Bit() && Size >= 8)
1705 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1707 return X86ScalarSSEf32;
1708 else if (VT == MVT::f64)
1709 return X86ScalarSSEf64;
1714 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1718 *Fast = Subtarget->isUnalignedMemAccessFast();
1722 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1723 /// current function. The returned value is a member of the
1724 /// MachineJumpTableInfo::JTEntryKind enum.
1725 unsigned X86TargetLowering::getJumpTableEncoding() const {
1726 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1728 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1729 Subtarget->isPICStyleGOT())
1730 return MachineJumpTableInfo::EK_Custom32;
1732 // Otherwise, use the normal jump table encoding heuristics.
1733 return TargetLowering::getJumpTableEncoding();
1737 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1738 const MachineBasicBlock *MBB,
1739 unsigned uid,MCContext &Ctx) const{
1740 assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1741 Subtarget->isPICStyleGOT());
1742 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1744 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1745 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1748 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1750 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1751 SelectionDAG &DAG) const {
1752 if (!Subtarget->is64Bit())
1753 // This doesn't have SDLoc associated with it, but is not really the
1754 // same as a Register.
1755 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1759 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1760 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1762 const MCExpr *X86TargetLowering::
1763 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1764 MCContext &Ctx) const {
1765 // X86-64 uses RIP relative addressing based on the jump table label.
1766 if (Subtarget->isPICStyleRIPRel())
1767 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1769 // Otherwise, the reference is relative to the PIC base.
1770 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1773 // FIXME: Why this routine is here? Move to RegInfo!
1774 std::pair<const TargetRegisterClass*, uint8_t>
1775 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1776 const TargetRegisterClass *RRC = nullptr;
1778 switch (VT.SimpleTy) {
1780 return TargetLowering::findRepresentativeClass(VT);
1781 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1782 RRC = Subtarget->is64Bit() ?
1783 (const TargetRegisterClass*)&X86::GR64RegClass :
1784 (const TargetRegisterClass*)&X86::GR32RegClass;
1787 RRC = &X86::VR64RegClass;
1789 case MVT::f32: case MVT::f64:
1790 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1791 case MVT::v4f32: case MVT::v2f64:
1792 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1794 RRC = &X86::VR128RegClass;
1797 return std::make_pair(RRC, Cost);
1800 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1801 unsigned &Offset) const {
1802 if (!Subtarget->isTargetLinux())
1805 if (Subtarget->is64Bit()) {
1806 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1808 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1820 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1821 unsigned DestAS) const {
1822 assert(SrcAS != DestAS && "Expected different address spaces!");
1824 return SrcAS < 256 && DestAS < 256;
1827 //===----------------------------------------------------------------------===//
1828 // Return Value Calling Convention Implementation
1829 //===----------------------------------------------------------------------===//
1831 #include "X86GenCallingConv.inc"
1834 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1835 MachineFunction &MF, bool isVarArg,
1836 const SmallVectorImpl<ISD::OutputArg> &Outs,
1837 LLVMContext &Context) const {
1838 SmallVector<CCValAssign, 16> RVLocs;
1839 CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
1841 return CCInfo.CheckReturn(Outs, RetCC_X86);
1844 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1845 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1850 X86TargetLowering::LowerReturn(SDValue Chain,
1851 CallingConv::ID CallConv, bool isVarArg,
1852 const SmallVectorImpl<ISD::OutputArg> &Outs,
1853 const SmallVectorImpl<SDValue> &OutVals,
1854 SDLoc dl, SelectionDAG &DAG) const {
1855 MachineFunction &MF = DAG.getMachineFunction();
1856 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1858 SmallVector<CCValAssign, 16> RVLocs;
1859 CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
1860 RVLocs, *DAG.getContext());
1861 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1864 SmallVector<SDValue, 6> RetOps;
1865 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1866 // Operand #1 = Bytes To Pop
1867 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1870 // Copy the result values into the output registers.
1871 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1872 CCValAssign &VA = RVLocs[i];
1873 assert(VA.isRegLoc() && "Can only return in registers!");
1874 SDValue ValToCopy = OutVals[i];
1875 EVT ValVT = ValToCopy.getValueType();
1877 // Promote values to the appropriate types
1878 if (VA.getLocInfo() == CCValAssign::SExt)
1879 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1880 else if (VA.getLocInfo() == CCValAssign::ZExt)
1881 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1882 else if (VA.getLocInfo() == CCValAssign::AExt)
1883 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1884 else if (VA.getLocInfo() == CCValAssign::BCvt)
1885 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1887 assert(VA.getLocInfo() != CCValAssign::FPExt &&
1888 "Unexpected FP-extend for return value.");
1890 // If this is x86-64, and we disabled SSE, we can't return FP values,
1891 // or SSE or MMX vectors.
1892 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1893 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1894 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1895 report_fatal_error("SSE register return with SSE disabled");
1897 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1898 // llvm-gcc has never done it right and no one has noticed, so this
1899 // should be OK for now.
1900 if (ValVT == MVT::f64 &&
1901 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1902 report_fatal_error("SSE2 register return with SSE2 disabled");
1904 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1905 // the RET instruction and handled by the FP Stackifier.
1906 if (VA.getLocReg() == X86::ST0 ||
1907 VA.getLocReg() == X86::ST1) {
1908 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1909 // change the value to the FP stack register class.
1910 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1911 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1912 RetOps.push_back(ValToCopy);
1913 // Don't emit a copytoreg.
1917 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1918 // which is returned in RAX / RDX.
1919 if (Subtarget->is64Bit()) {
1920 if (ValVT == MVT::x86mmx) {
1921 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1922 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1923 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1925 // If we don't have SSE2 available, convert to v4f32 so the generated
1926 // register is legal.
1927 if (!Subtarget->hasSSE2())
1928 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1933 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1934 Flag = Chain.getValue(1);
1935 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1938 // The x86-64 ABIs require that for returning structs by value we copy
1939 // the sret argument into %rax/%eax (depending on ABI) for the return.
1940 // Win32 requires us to put the sret argument to %eax as well.
1941 // We saved the argument into a virtual register in the entry block,
1942 // so now we copy the value out and into %rax/%eax.
1943 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1944 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1945 MachineFunction &MF = DAG.getMachineFunction();
1946 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1947 unsigned Reg = FuncInfo->getSRetReturnReg();
1949 "SRetReturnReg should have been set in LowerFormalArguments().");
1950 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1953 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1954 X86::RAX : X86::EAX;
1955 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1956 Flag = Chain.getValue(1);
1958 // RAX/EAX now acts like a return value.
1959 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1962 RetOps[0] = Chain; // Update chain.
1964 // Add the flag if we have it.
1966 RetOps.push_back(Flag);
1968 return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
1971 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1972 if (N->getNumValues() != 1)
1974 if (!N->hasNUsesOfValue(1, 0))
1977 SDValue TCChain = Chain;
1978 SDNode *Copy = *N->use_begin();
1979 if (Copy->getOpcode() == ISD::CopyToReg) {
1980 // If the copy has a glue operand, we conservatively assume it isn't safe to
1981 // perform a tail call.
1982 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1984 TCChain = Copy->getOperand(0);
1985 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1988 bool HasRet = false;
1989 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1991 if (UI->getOpcode() != X86ISD::RET_FLAG)
2004 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
2005 ISD::NodeType ExtendKind) const {
2007 // TODO: Is this also valid on 32-bit?
2008 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2009 ReturnMVT = MVT::i8;
2011 ReturnMVT = MVT::i32;
2013 MVT MinVT = getRegisterType(ReturnMVT);
2014 return VT.bitsLT(MinVT) ? MinVT : VT;
2017 /// LowerCallResult - Lower the result values of a call into the
2018 /// appropriate copies out of appropriate physical registers.
2021 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2022 CallingConv::ID CallConv, bool isVarArg,
2023 const SmallVectorImpl<ISD::InputArg> &Ins,
2024 SDLoc dl, SelectionDAG &DAG,
2025 SmallVectorImpl<SDValue> &InVals) const {
2027 // Assign locations to each value returned by this call.
2028 SmallVector<CCValAssign, 16> RVLocs;
2029 bool Is64Bit = Subtarget->is64Bit();
2030 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2031 DAG.getTarget(), RVLocs, *DAG.getContext());
2032 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2034 // Copy all of the result registers out of their specified physreg.
2035 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2036 CCValAssign &VA = RVLocs[i];
2037 EVT CopyVT = VA.getValVT();
2039 // If this is x86-64, and we disabled SSE, we can't return FP values
2040 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2041 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2042 report_fatal_error("SSE register return with SSE disabled");
2047 // If this is a call to a function that returns an fp value on the floating
2048 // point stack, we must guarantee the value is popped from the stack, so
2049 // a CopyFromReg is not good enough - the copy instruction may be eliminated
2050 // if the return value is not used. We use the FpPOP_RETVAL instruction
2052 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2053 // If we prefer to use the value in xmm registers, copy it out as f80 and
2054 // use a truncate to move it from fp stack reg to xmm reg.
2055 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2056 SDValue Ops[] = { Chain, InFlag };
2057 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2058 MVT::Other, MVT::Glue, Ops), 1);
2059 Val = Chain.getValue(0);
2061 // Round the f80 to the right size, which also moves it to the appropriate
2063 if (CopyVT != VA.getValVT())
2064 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2065 // This truncation won't change the value.
2066 DAG.getIntPtrConstant(1));
2068 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2069 CopyVT, InFlag).getValue(1);
2070 Val = Chain.getValue(0);
2072 InFlag = Chain.getValue(2);
2073 InVals.push_back(Val);
2079 //===----------------------------------------------------------------------===//
2080 // C & StdCall & Fast Calling Convention implementation
2081 //===----------------------------------------------------------------------===//
2082 // StdCall calling convention seems to be standard for many Windows' API
2083 // routines and around. It differs from C calling convention just a little:
2084 // callee should clean up the stack, not caller. Symbols should be also
2085 // decorated in some fancy way :) It doesn't support any vector arguments.
2086 // For info on fast calling convention see Fast Calling Convention (tail call)
2087 // implementation LowerX86_32FastCCCallTo.
2089 /// CallIsStructReturn - Determines whether a call uses struct return
2091 enum StructReturnType {
2096 static StructReturnType
2097 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2099 return NotStructReturn;
2101 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2102 if (!Flags.isSRet())
2103 return NotStructReturn;
2104 if (Flags.isInReg())
2105 return RegStructReturn;
2106 return StackStructReturn;
2109 /// ArgsAreStructReturn - Determines whether a function uses struct
2110 /// return semantics.
2111 static StructReturnType
2112 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2114 return NotStructReturn;
2116 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2117 if (!Flags.isSRet())
2118 return NotStructReturn;
2119 if (Flags.isInReg())
2120 return RegStructReturn;
2121 return StackStructReturn;
2124 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2125 /// by "Src" to address "Dst" with size and alignment information specified by
2126 /// the specific parameter attribute. The copy will be passed as a byval
2127 /// function parameter.
2129 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2130 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2132 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2134 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2135 /*isVolatile*/false, /*AlwaysInline=*/true,
2136 MachinePointerInfo(), MachinePointerInfo());
2139 /// IsTailCallConvention - Return true if the calling convention is one that
2140 /// supports tail call optimization.
2141 static bool IsTailCallConvention(CallingConv::ID CC) {
2142 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2143 CC == CallingConv::HiPE);
2146 /// \brief Return true if the calling convention is a C calling convention.
2147 static bool IsCCallConvention(CallingConv::ID CC) {
2148 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2149 CC == CallingConv::X86_64_SysV);
2152 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2153 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2157 CallingConv::ID CalleeCC = CS.getCallingConv();
2158 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2164 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2165 /// a tailcall target by changing its ABI.
2166 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2167 bool GuaranteedTailCallOpt) {
2168 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2172 X86TargetLowering::LowerMemArgument(SDValue Chain,
2173 CallingConv::ID CallConv,
2174 const SmallVectorImpl<ISD::InputArg> &Ins,
2175 SDLoc dl, SelectionDAG &DAG,
2176 const CCValAssign &VA,
2177 MachineFrameInfo *MFI,
2179 // Create the nodes corresponding to a load from this parameter slot.
2180 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2181 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2182 CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2183 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2186 // If value is passed by pointer we have address passed instead of the value
2188 if (VA.getLocInfo() == CCValAssign::Indirect)
2189 ValVT = VA.getLocVT();
2191 ValVT = VA.getValVT();
2193 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2194 // changed with more analysis.
2195 // In case of tail call optimization mark all arguments mutable. Since they
2196 // could be overwritten by lowering of arguments in case of a tail call.
2197 if (Flags.isByVal()) {
2198 unsigned Bytes = Flags.getByValSize();
2199 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2200 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2201 return DAG.getFrameIndex(FI, getPointerTy());
2203 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2204 VA.getLocMemOffset(), isImmutable);
2205 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2206 return DAG.getLoad(ValVT, dl, Chain, FIN,
2207 MachinePointerInfo::getFixedStack(FI),
2208 false, false, false, 0);
2213 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2214 CallingConv::ID CallConv,
2216 const SmallVectorImpl<ISD::InputArg> &Ins,
2219 SmallVectorImpl<SDValue> &InVals)
2221 MachineFunction &MF = DAG.getMachineFunction();
2222 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2224 const Function* Fn = MF.getFunction();
2225 if (Fn->hasExternalLinkage() &&
2226 Subtarget->isTargetCygMing() &&
2227 Fn->getName() == "main")
2228 FuncInfo->setForceFramePointer(true);
2230 MachineFrameInfo *MFI = MF.getFrameInfo();
2231 bool Is64Bit = Subtarget->is64Bit();
2232 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2234 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2235 "Var args not supported with calling convention fastcc, ghc or hipe");
2237 // Assign locations to all of the incoming arguments.
2238 SmallVector<CCValAssign, 16> ArgLocs;
2239 CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
2240 ArgLocs, *DAG.getContext());
2242 // Allocate shadow area for Win64
2244 CCInfo.AllocateStack(32, 8);
2246 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2248 unsigned LastVal = ~0U;
2250 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2251 CCValAssign &VA = ArgLocs[i];
2252 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2254 assert(VA.getValNo() != LastVal &&
2255 "Don't support value assigned to multiple locs yet");
2257 LastVal = VA.getValNo();
2259 if (VA.isRegLoc()) {
2260 EVT RegVT = VA.getLocVT();
2261 const TargetRegisterClass *RC;
2262 if (RegVT == MVT::i32)
2263 RC = &X86::GR32RegClass;
2264 else if (Is64Bit && RegVT == MVT::i64)
2265 RC = &X86::GR64RegClass;
2266 else if (RegVT == MVT::f32)
2267 RC = &X86::FR32RegClass;
2268 else if (RegVT == MVT::f64)
2269 RC = &X86::FR64RegClass;
2270 else if (RegVT.is512BitVector())
2271 RC = &X86::VR512RegClass;
2272 else if (RegVT.is256BitVector())
2273 RC = &X86::VR256RegClass;
2274 else if (RegVT.is128BitVector())
2275 RC = &X86::VR128RegClass;
2276 else if (RegVT == MVT::x86mmx)
2277 RC = &X86::VR64RegClass;
2278 else if (RegVT == MVT::i1)
2279 RC = &X86::VK1RegClass;
2280 else if (RegVT == MVT::v8i1)
2281 RC = &X86::VK8RegClass;
2282 else if (RegVT == MVT::v16i1)
2283 RC = &X86::VK16RegClass;
2285 llvm_unreachable("Unknown argument type!");
2287 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2288 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2290 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2291 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2293 if (VA.getLocInfo() == CCValAssign::SExt)
2294 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2295 DAG.getValueType(VA.getValVT()));
2296 else if (VA.getLocInfo() == CCValAssign::ZExt)
2297 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2298 DAG.getValueType(VA.getValVT()));
2299 else if (VA.getLocInfo() == CCValAssign::BCvt)
2300 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2302 if (VA.isExtInLoc()) {
2303 // Handle MMX values passed in XMM regs.
2304 if (RegVT.isVector())
2305 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2307 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2310 assert(VA.isMemLoc());
2311 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2314 // If value is passed via pointer - do a load.
2315 if (VA.getLocInfo() == CCValAssign::Indirect)
2316 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2317 MachinePointerInfo(), false, false, false, 0);
2319 InVals.push_back(ArgValue);
2322 if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2323 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2324 // The x86-64 ABIs require that for returning structs by value we copy
2325 // the sret argument into %rax/%eax (depending on ABI) for the return.
2326 // Win32 requires us to put the sret argument to %eax as well.
2327 // Save the argument into a virtual register so that we can access it
2328 // from the return points.
2329 if (Ins[i].Flags.isSRet()) {
2330 unsigned Reg = FuncInfo->getSRetReturnReg();
2332 MVT PtrTy = getPointerTy();
2333 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2334 FuncInfo->setSRetReturnReg(Reg);
2336 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2337 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2343 unsigned StackSize = CCInfo.getNextStackOffset();
2344 // Align stack specially for tail calls.
2345 if (FuncIsMadeTailCallSafe(CallConv,
2346 MF.getTarget().Options.GuaranteedTailCallOpt))
2347 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2349 // If the function takes variable number of arguments, make a frame index for
2350 // the start of the first vararg value... for expansion of llvm.va_start.
2352 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2353 CallConv != CallingConv::X86_ThisCall)) {
2354 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2357 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2359 // FIXME: We should really autogenerate these arrays
2360 static const MCPhysReg GPR64ArgRegsWin64[] = {
2361 X86::RCX, X86::RDX, X86::R8, X86::R9
2363 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2364 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2366 static const MCPhysReg XMMArgRegs64Bit[] = {
2367 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2368 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2370 const MCPhysReg *GPR64ArgRegs;
2371 unsigned NumXMMRegs = 0;
2374 // The XMM registers which might contain var arg parameters are shadowed
2375 // in their paired GPR. So we only need to save the GPR to their home
2377 TotalNumIntRegs = 4;
2378 GPR64ArgRegs = GPR64ArgRegsWin64;
2380 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2381 GPR64ArgRegs = GPR64ArgRegs64Bit;
2383 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2386 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2389 bool NoImplicitFloatOps = Fn->getAttributes().
2390 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2391 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2392 "SSE register cannot be used when SSE is disabled!");
2393 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2394 NoImplicitFloatOps) &&
2395 "SSE register cannot be used when SSE is disabled!");
2396 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2397 !Subtarget->hasSSE1())
2398 // Kernel mode asks for SSE to be disabled, so don't push them
2400 TotalNumXMMRegs = 0;
2403 const TargetFrameLowering &TFI = *MF.getTarget().getFrameLowering();
2404 // Get to the caller-allocated home save location. Add 8 to account
2405 // for the return address.
2406 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2407 FuncInfo->setRegSaveFrameIndex(
2408 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2409 // Fixup to set vararg frame on shadow area (4 x i64).
2411 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2413 // For X86-64, if there are vararg parameters that are passed via
2414 // registers, then we must store them to their spots on the stack so
2415 // they may be loaded by deferencing the result of va_next.
2416 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2417 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2418 FuncInfo->setRegSaveFrameIndex(
2419 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2423 // Store the integer parameter registers.
2424 SmallVector<SDValue, 8> MemOps;
2425 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2427 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2428 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2429 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2430 DAG.getIntPtrConstant(Offset));
2431 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2432 &X86::GR64RegClass);
2433 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2435 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2436 MachinePointerInfo::getFixedStack(
2437 FuncInfo->getRegSaveFrameIndex(), Offset),
2439 MemOps.push_back(Store);
2443 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2444 // Now store the XMM (fp + vector) parameter registers.
2445 SmallVector<SDValue, 11> SaveXMMOps;
2446 SaveXMMOps.push_back(Chain);
2448 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2449 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2450 SaveXMMOps.push_back(ALVal);
2452 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2453 FuncInfo->getRegSaveFrameIndex()));
2454 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2455 FuncInfo->getVarArgsFPOffset()));
2457 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2458 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2459 &X86::VR128RegClass);
2460 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2461 SaveXMMOps.push_back(Val);
2463 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2464 MVT::Other, SaveXMMOps));
2467 if (!MemOps.empty())
2468 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2472 // Some CCs need callee pop.
2473 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2474 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2475 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2477 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2478 // If this is an sret function, the return should pop the hidden pointer.
2479 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2480 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2481 argsAreStructReturn(Ins) == StackStructReturn)
2482 FuncInfo->setBytesToPopOnReturn(4);
2486 // RegSaveFrameIndex is X86-64 only.
2487 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2488 if (CallConv == CallingConv::X86_FastCall ||
2489 CallConv == CallingConv::X86_ThisCall)
2490 // fastcc functions can't have varargs.
2491 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2494 FuncInfo->setArgumentStackSize(StackSize);
2500 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2501 SDValue StackPtr, SDValue Arg,
2502 SDLoc dl, SelectionDAG &DAG,
2503 const CCValAssign &VA,
2504 ISD::ArgFlagsTy Flags) const {
2505 unsigned LocMemOffset = VA.getLocMemOffset();
2506 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2507 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2508 if (Flags.isByVal())
2509 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2511 return DAG.getStore(Chain, dl, Arg, PtrOff,
2512 MachinePointerInfo::getStack(LocMemOffset),
2516 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2517 /// optimization is performed and it is required.
2519 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2520 SDValue &OutRetAddr, SDValue Chain,
2521 bool IsTailCall, bool Is64Bit,
2522 int FPDiff, SDLoc dl) const {
2523 // Adjust the Return address stack slot.
2524 EVT VT = getPointerTy();
2525 OutRetAddr = getReturnAddressFrameIndex(DAG);
2527 // Load the "old" Return address.
2528 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2529 false, false, false, 0);
2530 return SDValue(OutRetAddr.getNode(), 1);
2533 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2534 /// optimization is performed and it is required (FPDiff!=0).
2535 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2536 SDValue Chain, SDValue RetAddrFrIdx,
2537 EVT PtrVT, unsigned SlotSize,
2538 int FPDiff, SDLoc dl) {
2539 // Store the return address to the appropriate stack slot.
2540 if (!FPDiff) return Chain;
2541 // Calculate the new stack slot for the return address.
2542 int NewReturnAddrFI =
2543 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2545 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2546 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2547 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2553 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2554 SmallVectorImpl<SDValue> &InVals) const {
2555 SelectionDAG &DAG = CLI.DAG;
2557 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2558 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2559 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2560 SDValue Chain = CLI.Chain;
2561 SDValue Callee = CLI.Callee;
2562 CallingConv::ID CallConv = CLI.CallConv;
2563 bool &isTailCall = CLI.IsTailCall;
2564 bool isVarArg = CLI.IsVarArg;
2566 MachineFunction &MF = DAG.getMachineFunction();
2567 bool Is64Bit = Subtarget->is64Bit();
2568 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2569 StructReturnType SR = callIsStructReturn(Outs);
2570 bool IsSibcall = false;
2572 if (MF.getTarget().Options.DisableTailCalls)
2575 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2577 // Force this to be a tail call. The verifier rules are enough to ensure
2578 // that we can lower this successfully without moving the return address
2581 } else if (isTailCall) {
2582 // Check if it's really possible to do a tail call.
2583 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2584 isVarArg, SR != NotStructReturn,
2585 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2586 Outs, OutVals, Ins, DAG);
2588 // Sibcalls are automatically detected tailcalls which do not require
2590 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2597 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2598 "Var args not supported with calling convention fastcc, ghc or hipe");
2600 // Analyze operands of the call, assigning locations to each operand.
2601 SmallVector<CCValAssign, 16> ArgLocs;
2602 CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
2603 ArgLocs, *DAG.getContext());
2605 // Allocate shadow area for Win64
2607 CCInfo.AllocateStack(32, 8);
2609 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2611 // Get a count of how many bytes are to be pushed on the stack.
2612 unsigned NumBytes = CCInfo.getNextStackOffset();
2614 // This is a sibcall. The memory operands are available in caller's
2615 // own caller's stack.
2617 else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2618 IsTailCallConvention(CallConv))
2619 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2622 if (isTailCall && !IsSibcall && !IsMustTail) {
2623 // Lower arguments at fp - stackoffset + fpdiff.
2624 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2625 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2627 FPDiff = NumBytesCallerPushed - NumBytes;
2629 // Set the delta of movement of the returnaddr stackslot.
2630 // But only set if delta is greater than previous delta.
2631 if (FPDiff < X86Info->getTCReturnAddrDelta())
2632 X86Info->setTCReturnAddrDelta(FPDiff);
2635 unsigned NumBytesToPush = NumBytes;
2636 unsigned NumBytesToPop = NumBytes;
2638 // If we have an inalloca argument, all stack space has already been allocated
2639 // for us and be right at the top of the stack. We don't support multiple
2640 // arguments passed in memory when using inalloca.
2641 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2643 assert(ArgLocs.back().getLocMemOffset() == 0 &&
2644 "an inalloca argument must be the only memory argument");
2648 Chain = DAG.getCALLSEQ_START(
2649 Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2651 SDValue RetAddrFrIdx;
2652 // Load return address for tail calls.
2653 if (isTailCall && FPDiff)
2654 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2655 Is64Bit, FPDiff, dl);
2657 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2658 SmallVector<SDValue, 8> MemOpChains;
2661 // Walk the register/memloc assignments, inserting copies/loads. In the case
2662 // of tail call optimization arguments are handle later.
2663 const X86RegisterInfo *RegInfo =
2664 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
2665 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2666 // Skip inalloca arguments, they have already been written.
2667 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2668 if (Flags.isInAlloca())
2671 CCValAssign &VA = ArgLocs[i];
2672 EVT RegVT = VA.getLocVT();
2673 SDValue Arg = OutVals[i];
2674 bool isByVal = Flags.isByVal();
2676 // Promote the value if needed.
2677 switch (VA.getLocInfo()) {
2678 default: llvm_unreachable("Unknown loc info!");
2679 case CCValAssign::Full: break;
2680 case CCValAssign::SExt:
2681 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2683 case CCValAssign::ZExt:
2684 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2686 case CCValAssign::AExt:
2687 if (RegVT.is128BitVector()) {
2688 // Special case: passing MMX values in XMM registers.
2689 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2690 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2691 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2693 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2695 case CCValAssign::BCvt:
2696 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2698 case CCValAssign::Indirect: {
2699 // Store the argument.
2700 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2701 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2702 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2703 MachinePointerInfo::getFixedStack(FI),
2710 if (VA.isRegLoc()) {
2711 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2712 if (isVarArg && IsWin64) {
2713 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2714 // shadow reg if callee is a varargs function.
2715 unsigned ShadowReg = 0;
2716 switch (VA.getLocReg()) {
2717 case X86::XMM0: ShadowReg = X86::RCX; break;
2718 case X86::XMM1: ShadowReg = X86::RDX; break;
2719 case X86::XMM2: ShadowReg = X86::R8; break;
2720 case X86::XMM3: ShadowReg = X86::R9; break;
2723 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2725 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2726 assert(VA.isMemLoc());
2727 if (!StackPtr.getNode())
2728 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2730 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2731 dl, DAG, VA, Flags));
2735 if (!MemOpChains.empty())
2736 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2738 if (Subtarget->isPICStyleGOT()) {
2739 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2742 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2743 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2745 // If we are tail calling and generating PIC/GOT style code load the
2746 // address of the callee into ECX. The value in ecx is used as target of
2747 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2748 // for tail calls on PIC/GOT architectures. Normally we would just put the
2749 // address of GOT into ebx and then call target@PLT. But for tail calls
2750 // ebx would be restored (since ebx is callee saved) before jumping to the
2753 // Note: The actual moving to ECX is done further down.
2754 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2755 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2756 !G->getGlobal()->hasProtectedVisibility())
2757 Callee = LowerGlobalAddress(Callee, DAG);
2758 else if (isa<ExternalSymbolSDNode>(Callee))
2759 Callee = LowerExternalSymbol(Callee, DAG);
2763 if (Is64Bit && isVarArg && !IsWin64) {
2764 // From AMD64 ABI document:
2765 // For calls that may call functions that use varargs or stdargs
2766 // (prototype-less calls or calls to functions containing ellipsis (...) in
2767 // the declaration) %al is used as hidden argument to specify the number
2768 // of SSE registers used. The contents of %al do not need to match exactly
2769 // the number of registers, but must be an ubound on the number of SSE
2770 // registers used and is in the range 0 - 8 inclusive.
2772 // Count the number of XMM registers allocated.
2773 static const MCPhysReg XMMArgRegs[] = {
2774 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2775 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2777 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2778 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2779 && "SSE registers cannot be used when SSE is disabled");
2781 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2782 DAG.getConstant(NumXMMRegs, MVT::i8)));
2785 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
2786 // don't need this because the eligibility check rejects calls that require
2787 // shuffling arguments passed in memory.
2788 if (!IsSibcall && isTailCall) {
2789 // Force all the incoming stack arguments to be loaded from the stack
2790 // before any new outgoing arguments are stored to the stack, because the
2791 // outgoing stack slots may alias the incoming argument stack slots, and
2792 // the alias isn't otherwise explicit. This is slightly more conservative
2793 // than necessary, because it means that each store effectively depends
2794 // on every argument instead of just those arguments it would clobber.
2795 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2797 SmallVector<SDValue, 8> MemOpChains2;
2800 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2801 CCValAssign &VA = ArgLocs[i];
2804 assert(VA.isMemLoc());
2805 SDValue Arg = OutVals[i];
2806 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2807 // Skip inalloca arguments. They don't require any work.
2808 if (Flags.isInAlloca())
2810 // Create frame index.
2811 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2812 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2813 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2814 FIN = DAG.getFrameIndex(FI, getPointerTy());
2816 if (Flags.isByVal()) {
2817 // Copy relative to framepointer.
2818 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2819 if (!StackPtr.getNode())
2820 StackPtr = DAG.getCopyFromReg(Chain, dl,
2821 RegInfo->getStackRegister(),
2823 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2825 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2829 // Store relative to framepointer.
2830 MemOpChains2.push_back(
2831 DAG.getStore(ArgChain, dl, Arg, FIN,
2832 MachinePointerInfo::getFixedStack(FI),
2837 if (!MemOpChains2.empty())
2838 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2840 // Store the return address to the appropriate stack slot.
2841 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2842 getPointerTy(), RegInfo->getSlotSize(),
2846 // Build a sequence of copy-to-reg nodes chained together with token chain
2847 // and flag operands which copy the outgoing args into registers.
2849 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2850 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2851 RegsToPass[i].second, InFlag);
2852 InFlag = Chain.getValue(1);
2855 if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
2856 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2857 // In the 64-bit large code model, we have to make all calls
2858 // through a register, since the call instruction's 32-bit
2859 // pc-relative offset may not be large enough to hold the whole
2861 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2862 // If the callee is a GlobalAddress node (quite common, every direct call
2863 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2866 // We should use extra load for direct calls to dllimported functions in
2868 const GlobalValue *GV = G->getGlobal();
2869 if (!GV->hasDLLImportStorageClass()) {
2870 unsigned char OpFlags = 0;
2871 bool ExtraLoad = false;
2872 unsigned WrapperKind = ISD::DELETED_NODE;
2874 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2875 // external symbols most go through the PLT in PIC mode. If the symbol
2876 // has hidden or protected visibility, or if it is static or local, then
2877 // we don't need to use the PLT - we can directly call it.
2878 if (Subtarget->isTargetELF() &&
2879 DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
2880 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2881 OpFlags = X86II::MO_PLT;
2882 } else if (Subtarget->isPICStyleStubAny() &&
2883 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2884 (!Subtarget->getTargetTriple().isMacOSX() ||
2885 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2886 // PC-relative references to external symbols should go through $stub,
2887 // unless we're building with the leopard linker or later, which
2888 // automatically synthesizes these stubs.
2889 OpFlags = X86II::MO_DARWIN_STUB;
2890 } else if (Subtarget->isPICStyleRIPRel() &&
2891 isa<Function>(GV) &&
2892 cast<Function>(GV)->getAttributes().
2893 hasAttribute(AttributeSet::FunctionIndex,
2894 Attribute::NonLazyBind)) {
2895 // If the function is marked as non-lazy, generate an indirect call
2896 // which loads from the GOT directly. This avoids runtime overhead
2897 // at the cost of eager binding (and one extra byte of encoding).
2898 OpFlags = X86II::MO_GOTPCREL;
2899 WrapperKind = X86ISD::WrapperRIP;
2903 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2904 G->getOffset(), OpFlags);
2906 // Add a wrapper if needed.
2907 if (WrapperKind != ISD::DELETED_NODE)
2908 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2909 // Add extra indirection if needed.
2911 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2912 MachinePointerInfo::getGOT(),
2913 false, false, false, 0);
2915 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2916 unsigned char OpFlags = 0;
2918 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2919 // external symbols should go through the PLT.
2920 if (Subtarget->isTargetELF() &&
2921 DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
2922 OpFlags = X86II::MO_PLT;
2923 } else if (Subtarget->isPICStyleStubAny() &&
2924 (!Subtarget->getTargetTriple().isMacOSX() ||
2925 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2926 // PC-relative references to external symbols should go through $stub,
2927 // unless we're building with the leopard linker or later, which
2928 // automatically synthesizes these stubs.
2929 OpFlags = X86II::MO_DARWIN_STUB;
2932 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2936 // Returns a chain & a flag for retval copy to use.
2937 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2938 SmallVector<SDValue, 8> Ops;
2940 if (!IsSibcall && isTailCall) {
2941 Chain = DAG.getCALLSEQ_END(Chain,
2942 DAG.getIntPtrConstant(NumBytesToPop, true),
2943 DAG.getIntPtrConstant(0, true), InFlag, dl);
2944 InFlag = Chain.getValue(1);
2947 Ops.push_back(Chain);
2948 Ops.push_back(Callee);
2951 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2953 // Add argument registers to the end of the list so that they are known live
2955 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2956 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2957 RegsToPass[i].second.getValueType()));
2959 // Add a register mask operand representing the call-preserved registers.
2960 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
2961 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2962 assert(Mask && "Missing call preserved mask for calling convention");
2963 Ops.push_back(DAG.getRegisterMask(Mask));
2965 if (InFlag.getNode())
2966 Ops.push_back(InFlag);
2970 //// If this is the first return lowered for this function, add the regs
2971 //// to the liveout set for the function.
2972 // This isn't right, although it's probably harmless on x86; liveouts
2973 // should be computed from returns not tail calls. Consider a void
2974 // function making a tail call to a function returning int.
2975 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
2978 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
2979 InFlag = Chain.getValue(1);
2981 // Create the CALLSEQ_END node.
2982 unsigned NumBytesForCalleeToPop;
2983 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2984 DAG.getTarget().Options.GuaranteedTailCallOpt))
2985 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
2986 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2987 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2988 SR == StackStructReturn)
2989 // If this is a call to a struct-return function, the callee
2990 // pops the hidden struct pointer, so we have to push it back.
2991 // This is common for Darwin/X86, Linux & Mingw32 targets.
2992 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2993 NumBytesForCalleeToPop = 4;
2995 NumBytesForCalleeToPop = 0; // Callee pops nothing.
2997 // Returns a flag for retval copy to use.
2999 Chain = DAG.getCALLSEQ_END(Chain,
3000 DAG.getIntPtrConstant(NumBytesToPop, true),
3001 DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3004 InFlag = Chain.getValue(1);
3007 // Handle result values, copying them out of physregs into vregs that we
3009 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3010 Ins, dl, DAG, InVals);
3013 //===----------------------------------------------------------------------===//
3014 // Fast Calling Convention (tail call) implementation
3015 //===----------------------------------------------------------------------===//
3017 // Like std call, callee cleans arguments, convention except that ECX is
3018 // reserved for storing the tail called function address. Only 2 registers are
3019 // free for argument passing (inreg). Tail call optimization is performed
3021 // * tailcallopt is enabled
3022 // * caller/callee are fastcc
3023 // On X86_64 architecture with GOT-style position independent code only local
3024 // (within module) calls are supported at the moment.
3025 // To keep the stack aligned according to platform abi the function
3026 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3027 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3028 // If a tail called function callee has more arguments than the caller the
3029 // caller needs to make sure that there is room to move the RETADDR to. This is
3030 // achieved by reserving an area the size of the argument delta right after the
3031 // original REtADDR, but before the saved framepointer or the spilled registers
3032 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3044 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3045 /// for a 16 byte align requirement.
3047 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3048 SelectionDAG& DAG) const {
3049 MachineFunction &MF = DAG.getMachineFunction();
3050 const TargetMachine &TM = MF.getTarget();
3051 const X86RegisterInfo *RegInfo =
3052 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3053 const TargetFrameLowering &TFI = *TM.getFrameLowering();
3054 unsigned StackAlignment = TFI.getStackAlignment();
3055 uint64_t AlignMask = StackAlignment - 1;
3056 int64_t Offset = StackSize;
3057 unsigned SlotSize = RegInfo->getSlotSize();
3058 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3059 // Number smaller than 12 so just add the difference.
3060 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3062 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3063 Offset = ((~AlignMask) & Offset) + StackAlignment +
3064 (StackAlignment-SlotSize);
3069 /// MatchingStackOffset - Return true if the given stack call argument is
3070 /// already available in the same position (relatively) of the caller's
3071 /// incoming argument stack.
3073 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3074 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3075 const X86InstrInfo *TII) {
3076 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3078 if (Arg.getOpcode() == ISD::CopyFromReg) {
3079 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3080 if (!TargetRegisterInfo::isVirtualRegister(VR))
3082 MachineInstr *Def = MRI->getVRegDef(VR);
3085 if (!Flags.isByVal()) {
3086 if (!TII->isLoadFromStackSlot(Def, FI))
3089 unsigned Opcode = Def->getOpcode();
3090 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3091 Def->getOperand(1).isFI()) {
3092 FI = Def->getOperand(1).getIndex();
3093 Bytes = Flags.getByValSize();
3097 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3098 if (Flags.isByVal())
3099 // ByVal argument is passed in as a pointer but it's now being
3100 // dereferenced. e.g.
3101 // define @foo(%struct.X* %A) {
3102 // tail call @bar(%struct.X* byval %A)
3105 SDValue Ptr = Ld->getBasePtr();
3106 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3109 FI = FINode->getIndex();
3110 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3111 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3112 FI = FINode->getIndex();
3113 Bytes = Flags.getByValSize();
3117 assert(FI != INT_MAX);
3118 if (!MFI->isFixedObjectIndex(FI))
3120 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3123 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3124 /// for tail call optimization. Targets which want to do tail call
3125 /// optimization should implement this function.
3127 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3128 CallingConv::ID CalleeCC,
3130 bool isCalleeStructRet,
3131 bool isCallerStructRet,
3133 const SmallVectorImpl<ISD::OutputArg> &Outs,
3134 const SmallVectorImpl<SDValue> &OutVals,
3135 const SmallVectorImpl<ISD::InputArg> &Ins,
3136 SelectionDAG &DAG) const {
3137 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3140 // If -tailcallopt is specified, make fastcc functions tail-callable.
3141 const MachineFunction &MF = DAG.getMachineFunction();
3142 const Function *CallerF = MF.getFunction();
3144 // If the function return type is x86_fp80 and the callee return type is not,
3145 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3146 // perform a tailcall optimization here.
3147 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3150 CallingConv::ID CallerCC = CallerF->getCallingConv();
3151 bool CCMatch = CallerCC == CalleeCC;
3152 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3153 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3155 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3156 if (IsTailCallConvention(CalleeCC) && CCMatch)
3161 // Look for obvious safe cases to perform tail call optimization that do not
3162 // require ABI changes. This is what gcc calls sibcall.
3164 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3165 // emit a special epilogue.
3166 const X86RegisterInfo *RegInfo =
3167 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
3168 if (RegInfo->needsStackRealignment(MF))
3171 // Also avoid sibcall optimization if either caller or callee uses struct
3172 // return semantics.
3173 if (isCalleeStructRet || isCallerStructRet)
3176 // An stdcall/thiscall caller is expected to clean up its arguments; the
3177 // callee isn't going to do that.
3178 // FIXME: this is more restrictive than needed. We could produce a tailcall
3179 // when the stack adjustment matches. For example, with a thiscall that takes
3180 // only one argument.
3181 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3182 CallerCC == CallingConv::X86_ThisCall))
3185 // Do not sibcall optimize vararg calls unless all arguments are passed via
3187 if (isVarArg && !Outs.empty()) {
3189 // Optimizing for varargs on Win64 is unlikely to be safe without
3190 // additional testing.
3191 if (IsCalleeWin64 || IsCallerWin64)
3194 SmallVector<CCValAssign, 16> ArgLocs;
3195 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3196 DAG.getTarget(), ArgLocs, *DAG.getContext());
3198 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3199 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3200 if (!ArgLocs[i].isRegLoc())
3204 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3205 // stack. Therefore, if it's not used by the call it is not safe to optimize
3206 // this into a sibcall.
3207 bool Unused = false;
3208 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3215 SmallVector<CCValAssign, 16> RVLocs;
3216 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3217 DAG.getTarget(), RVLocs, *DAG.getContext());
3218 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3219 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3220 CCValAssign &VA = RVLocs[i];
3221 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3226 // If the calling conventions do not match, then we'd better make sure the
3227 // results are returned in the same way as what the caller expects.
3229 SmallVector<CCValAssign, 16> RVLocs1;
3230 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3231 DAG.getTarget(), RVLocs1, *DAG.getContext());
3232 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3234 SmallVector<CCValAssign, 16> RVLocs2;
3235 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3236 DAG.getTarget(), RVLocs2, *DAG.getContext());
3237 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3239 if (RVLocs1.size() != RVLocs2.size())
3241 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3242 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3244 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3246 if (RVLocs1[i].isRegLoc()) {
3247 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3250 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3256 // If the callee takes no arguments then go on to check the results of the
3258 if (!Outs.empty()) {
3259 // Check if stack adjustment is needed. For now, do not do this if any
3260 // argument is passed on the stack.
3261 SmallVector<CCValAssign, 16> ArgLocs;
3262 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3263 DAG.getTarget(), ArgLocs, *DAG.getContext());
3265 // Allocate shadow area for Win64
3267 CCInfo.AllocateStack(32, 8);
3269 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3270 if (CCInfo.getNextStackOffset()) {
3271 MachineFunction &MF = DAG.getMachineFunction();
3272 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3275 // Check if the arguments are already laid out in the right way as
3276 // the caller's fixed stack objects.
3277 MachineFrameInfo *MFI = MF.getFrameInfo();
3278 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3279 const X86InstrInfo *TII =
3280 static_cast<const X86InstrInfo *>(DAG.getTarget().getInstrInfo());
3281 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3282 CCValAssign &VA = ArgLocs[i];
3283 SDValue Arg = OutVals[i];
3284 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3285 if (VA.getLocInfo() == CCValAssign::Indirect)
3287 if (!VA.isRegLoc()) {
3288 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3295 // If the tailcall address may be in a register, then make sure it's
3296 // possible to register allocate for it. In 32-bit, the call address can
3297 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3298 // callee-saved registers are restored. These happen to be the same
3299 // registers used to pass 'inreg' arguments so watch out for those.
3300 if (!Subtarget->is64Bit() &&
3301 ((!isa<GlobalAddressSDNode>(Callee) &&
3302 !isa<ExternalSymbolSDNode>(Callee)) ||
3303 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3304 unsigned NumInRegs = 0;
3305 // In PIC we need an extra register to formulate the address computation
3307 unsigned MaxInRegs =
3308 (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3310 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3311 CCValAssign &VA = ArgLocs[i];
3314 unsigned Reg = VA.getLocReg();
3317 case X86::EAX: case X86::EDX: case X86::ECX:
3318 if (++NumInRegs == MaxInRegs)
3330 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3331 const TargetLibraryInfo *libInfo) const {
3332 return X86::createFastISel(funcInfo, libInfo);
3335 //===----------------------------------------------------------------------===//
3336 // Other Lowering Hooks
3337 //===----------------------------------------------------------------------===//
3339 static bool MayFoldLoad(SDValue Op) {
3340 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3343 static bool MayFoldIntoStore(SDValue Op) {
3344 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3347 static bool isTargetShuffle(unsigned Opcode) {
3349 default: return false;
3350 case X86ISD::PSHUFD:
3351 case X86ISD::PSHUFHW:
3352 case X86ISD::PSHUFLW:
3354 case X86ISD::PALIGNR:
3355 case X86ISD::MOVLHPS:
3356 case X86ISD::MOVLHPD:
3357 case X86ISD::MOVHLPS:
3358 case X86ISD::MOVLPS:
3359 case X86ISD::MOVLPD:
3360 case X86ISD::MOVSHDUP:
3361 case X86ISD::MOVSLDUP:
3362 case X86ISD::MOVDDUP:
3365 case X86ISD::UNPCKL:
3366 case X86ISD::UNPCKH:
3367 case X86ISD::VPERMILP:
3368 case X86ISD::VPERM2X128:
3369 case X86ISD::VPERMI:
3374 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3375 SDValue V1, SelectionDAG &DAG) {
3377 default: llvm_unreachable("Unknown x86 shuffle node");
3378 case X86ISD::MOVSHDUP:
3379 case X86ISD::MOVSLDUP:
3380 case X86ISD::MOVDDUP:
3381 return DAG.getNode(Opc, dl, VT, V1);
3385 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3386 SDValue V1, unsigned TargetMask,
3387 SelectionDAG &DAG) {
3389 default: llvm_unreachable("Unknown x86 shuffle node");
3390 case X86ISD::PSHUFD:
3391 case X86ISD::PSHUFHW:
3392 case X86ISD::PSHUFLW:
3393 case X86ISD::VPERMILP:
3394 case X86ISD::VPERMI:
3395 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3399 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3400 SDValue V1, SDValue V2, unsigned TargetMask,
3401 SelectionDAG &DAG) {
3403 default: llvm_unreachable("Unknown x86 shuffle node");
3404 case X86ISD::PALIGNR:
3406 case X86ISD::VPERM2X128:
3407 return DAG.getNode(Opc, dl, VT, V1, V2,
3408 DAG.getConstant(TargetMask, MVT::i8));
3412 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3413 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3415 default: llvm_unreachable("Unknown x86 shuffle node");
3416 case X86ISD::MOVLHPS:
3417 case X86ISD::MOVLHPD:
3418 case X86ISD::MOVHLPS:
3419 case X86ISD::MOVLPS:
3420 case X86ISD::MOVLPD:
3423 case X86ISD::UNPCKL:
3424 case X86ISD::UNPCKH:
3425 return DAG.getNode(Opc, dl, VT, V1, V2);
3429 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3430 MachineFunction &MF = DAG.getMachineFunction();
3431 const X86RegisterInfo *RegInfo =
3432 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
3433 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3434 int ReturnAddrIndex = FuncInfo->getRAIndex();
3436 if (ReturnAddrIndex == 0) {
3437 // Set up a frame object for the return address.
3438 unsigned SlotSize = RegInfo->getSlotSize();
3439 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3442 FuncInfo->setRAIndex(ReturnAddrIndex);
3445 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3448 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3449 bool hasSymbolicDisplacement) {
3450 // Offset should fit into 32 bit immediate field.
3451 if (!isInt<32>(Offset))
3454 // If we don't have a symbolic displacement - we don't have any extra
3456 if (!hasSymbolicDisplacement)
3459 // FIXME: Some tweaks might be needed for medium code model.
3460 if (M != CodeModel::Small && M != CodeModel::Kernel)
3463 // For small code model we assume that latest object is 16MB before end of 31
3464 // bits boundary. We may also accept pretty large negative constants knowing
3465 // that all objects are in the positive half of address space.
3466 if (M == CodeModel::Small && Offset < 16*1024*1024)
3469 // For kernel code model we know that all object resist in the negative half
3470 // of 32bits address space. We may not accept negative offsets, since they may
3471 // be just off and we may accept pretty large positive ones.
3472 if (M == CodeModel::Kernel && Offset > 0)
3478 /// isCalleePop - Determines whether the callee is required to pop its
3479 /// own arguments. Callee pop is necessary to support tail calls.
3480 bool X86::isCalleePop(CallingConv::ID CallingConv,
3481 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3485 switch (CallingConv) {
3488 case CallingConv::X86_StdCall:
3490 case CallingConv::X86_FastCall:
3492 case CallingConv::X86_ThisCall:
3494 case CallingConv::Fast:
3496 case CallingConv::GHC:
3498 case CallingConv::HiPE:
3503 /// \brief Return true if the condition is an unsigned comparison operation.
3504 static bool isX86CCUnsigned(unsigned X86CC) {
3506 default: llvm_unreachable("Invalid integer condition!");
3507 case X86::COND_E: return true;
3508 case X86::COND_G: return false;
3509 case X86::COND_GE: return false;
3510 case X86::COND_L: return false;
3511 case X86::COND_LE: return false;
3512 case X86::COND_NE: return true;
3513 case X86::COND_B: return true;
3514 case X86::COND_A: return true;
3515 case X86::COND_BE: return true;
3516 case X86::COND_AE: return true;
3518 llvm_unreachable("covered switch fell through?!");
3521 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3522 /// specific condition code, returning the condition code and the LHS/RHS of the
3523 /// comparison to make.
3524 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3525 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3527 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3528 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3529 // X > -1 -> X == 0, jump !sign.
3530 RHS = DAG.getConstant(0, RHS.getValueType());
3531 return X86::COND_NS;
3533 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3534 // X < 0 -> X == 0, jump on sign.
3537 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3539 RHS = DAG.getConstant(0, RHS.getValueType());
3540 return X86::COND_LE;
3544 switch (SetCCOpcode) {
3545 default: llvm_unreachable("Invalid integer condition!");
3546 case ISD::SETEQ: return X86::COND_E;
3547 case ISD::SETGT: return X86::COND_G;
3548 case ISD::SETGE: return X86::COND_GE;
3549 case ISD::SETLT: return X86::COND_L;
3550 case ISD::SETLE: return X86::COND_LE;
3551 case ISD::SETNE: return X86::COND_NE;
3552 case ISD::SETULT: return X86::COND_B;
3553 case ISD::SETUGT: return X86::COND_A;
3554 case ISD::SETULE: return X86::COND_BE;
3555 case ISD::SETUGE: return X86::COND_AE;
3559 // First determine if it is required or is profitable to flip the operands.
3561 // If LHS is a foldable load, but RHS is not, flip the condition.
3562 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3563 !ISD::isNON_EXTLoad(RHS.getNode())) {
3564 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3565 std::swap(LHS, RHS);
3568 switch (SetCCOpcode) {
3574 std::swap(LHS, RHS);
3578 // On a floating point condition, the flags are set as follows:
3580 // 0 | 0 | 0 | X > Y
3581 // 0 | 0 | 1 | X < Y
3582 // 1 | 0 | 0 | X == Y
3583 // 1 | 1 | 1 | unordered
3584 switch (SetCCOpcode) {
3585 default: llvm_unreachable("Condcode should be pre-legalized away");
3587 case ISD::SETEQ: return X86::COND_E;
3588 case ISD::SETOLT: // flipped
3590 case ISD::SETGT: return X86::COND_A;
3591 case ISD::SETOLE: // flipped
3593 case ISD::SETGE: return X86::COND_AE;
3594 case ISD::SETUGT: // flipped
3596 case ISD::SETLT: return X86::COND_B;
3597 case ISD::SETUGE: // flipped
3599 case ISD::SETLE: return X86::COND_BE;
3601 case ISD::SETNE: return X86::COND_NE;
3602 case ISD::SETUO: return X86::COND_P;
3603 case ISD::SETO: return X86::COND_NP;
3605 case ISD::SETUNE: return X86::COND_INVALID;
3609 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3610 /// code. Current x86 isa includes the following FP cmov instructions:
3611 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3612 static bool hasFPCMov(unsigned X86CC) {
3628 /// isFPImmLegal - Returns true if the target can instruction select the
3629 /// specified FP immediate natively. If false, the legalizer will
3630 /// materialize the FP immediate as a load from a constant pool.
3631 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3632 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3633 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3639 /// \brief Returns true if it is beneficial to convert a load of a constant
3640 /// to just the constant itself.
3641 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3643 assert(Ty->isIntegerTy());
3645 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3646 if (BitSize == 0 || BitSize > 64)
3651 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3652 /// the specified range (L, H].
3653 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3654 return (Val < 0) || (Val >= Low && Val < Hi);
3657 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3658 /// specified value.
3659 static bool isUndefOrEqual(int Val, int CmpVal) {
3660 return (Val < 0 || Val == CmpVal);
3663 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3664 /// from position Pos and ending in Pos+Size, falls within the specified
3665 /// sequential range (L, L+Pos]. or is undef.
3666 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3667 unsigned Pos, unsigned Size, int Low) {
3668 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3669 if (!isUndefOrEqual(Mask[i], Low))
3674 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3675 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3676 /// the second operand.
3677 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3678 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3679 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3680 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3681 return (Mask[0] < 2 && Mask[1] < 2);
3685 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3686 /// is suitable for input to PSHUFHW.
3687 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3688 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3691 // Lower quadword copied in order or undef.
3692 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3695 // Upper quadword shuffled.
3696 for (unsigned i = 4; i != 8; ++i)
3697 if (!isUndefOrInRange(Mask[i], 4, 8))
3700 if (VT == MVT::v16i16) {
3701 // Lower quadword copied in order or undef.
3702 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3705 // Upper quadword shuffled.
3706 for (unsigned i = 12; i != 16; ++i)
3707 if (!isUndefOrInRange(Mask[i], 12, 16))
3714 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3715 /// is suitable for input to PSHUFLW.
3716 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3717 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3720 // Upper quadword copied in order.
3721 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3724 // Lower quadword shuffled.
3725 for (unsigned i = 0; i != 4; ++i)
3726 if (!isUndefOrInRange(Mask[i], 0, 4))
3729 if (VT == MVT::v16i16) {
3730 // Upper quadword copied in order.
3731 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3734 // Lower quadword shuffled.
3735 for (unsigned i = 8; i != 12; ++i)
3736 if (!isUndefOrInRange(Mask[i], 8, 12))
3743 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3744 /// is suitable for input to PALIGNR.
3745 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3746 const X86Subtarget *Subtarget) {
3747 if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3748 (VT.is256BitVector() && !Subtarget->hasInt256()))
3751 unsigned NumElts = VT.getVectorNumElements();
3752 unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3753 unsigned NumLaneElts = NumElts/NumLanes;
3755 // Do not handle 64-bit element shuffles with palignr.
3756 if (NumLaneElts == 2)
3759 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3761 for (i = 0; i != NumLaneElts; ++i) {
3766 // Lane is all undef, go to next lane
3767 if (i == NumLaneElts)
3770 int Start = Mask[i+l];
3772 // Make sure its in this lane in one of the sources
3773 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3774 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3777 // If not lane 0, then we must match lane 0
3778 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3781 // Correct second source to be contiguous with first source
3782 if (Start >= (int)NumElts)
3783 Start -= NumElts - NumLaneElts;
3785 // Make sure we're shifting in the right direction.
3786 if (Start <= (int)(i+l))
3791 // Check the rest of the elements to see if they are consecutive.
3792 for (++i; i != NumLaneElts; ++i) {
3793 int Idx = Mask[i+l];
3795 // Make sure its in this lane
3796 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3797 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3800 // If not lane 0, then we must match lane 0
3801 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3804 if (Idx >= (int)NumElts)
3805 Idx -= NumElts - NumLaneElts;
3807 if (!isUndefOrEqual(Idx, Start+i))
3816 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3817 /// the two vector operands have swapped position.
3818 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3819 unsigned NumElems) {
3820 for (unsigned i = 0; i != NumElems; ++i) {
3824 else if (idx < (int)NumElems)
3825 Mask[i] = idx + NumElems;
3827 Mask[i] = idx - NumElems;
3831 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3832 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3833 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3834 /// reverse of what x86 shuffles want.
3835 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3837 unsigned NumElems = VT.getVectorNumElements();
3838 unsigned NumLanes = VT.getSizeInBits()/128;
3839 unsigned NumLaneElems = NumElems/NumLanes;
3841 if (NumLaneElems != 2 && NumLaneElems != 4)
3844 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3845 bool symetricMaskRequired =
3846 (VT.getSizeInBits() >= 256) && (EltSize == 32);
3848 // VSHUFPSY divides the resulting vector into 4 chunks.
3849 // The sources are also splitted into 4 chunks, and each destination
3850 // chunk must come from a different source chunk.
3852 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3853 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3855 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3856 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3858 // VSHUFPDY divides the resulting vector into 4 chunks.
3859 // The sources are also splitted into 4 chunks, and each destination
3860 // chunk must come from a different source chunk.
3862 // SRC1 => X3 X2 X1 X0
3863 // SRC2 => Y3 Y2 Y1 Y0
3865 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3867 SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3868 unsigned HalfLaneElems = NumLaneElems/2;
3869 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3870 for (unsigned i = 0; i != NumLaneElems; ++i) {
3871 int Idx = Mask[i+l];
3872 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3873 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3875 // For VSHUFPSY, the mask of the second half must be the same as the
3876 // first but with the appropriate offsets. This works in the same way as
3877 // VPERMILPS works with masks.
3878 if (!symetricMaskRequired || Idx < 0)
3880 if (MaskVal[i] < 0) {
3881 MaskVal[i] = Idx - l;
3884 if ((signed)(Idx - l) != MaskVal[i])
3892 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3893 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3894 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3895 if (!VT.is128BitVector())
3898 unsigned NumElems = VT.getVectorNumElements();
3903 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3904 return isUndefOrEqual(Mask[0], 6) &&
3905 isUndefOrEqual(Mask[1], 7) &&
3906 isUndefOrEqual(Mask[2], 2) &&
3907 isUndefOrEqual(Mask[3], 3);
3910 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3911 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3913 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3914 if (!VT.is128BitVector())
3917 unsigned NumElems = VT.getVectorNumElements();
3922 return isUndefOrEqual(Mask[0], 2) &&
3923 isUndefOrEqual(Mask[1], 3) &&
3924 isUndefOrEqual(Mask[2], 2) &&
3925 isUndefOrEqual(Mask[3], 3);
3928 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3929 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3930 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3931 if (!VT.is128BitVector())
3934 unsigned NumElems = VT.getVectorNumElements();
3936 if (NumElems != 2 && NumElems != 4)
3939 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3940 if (!isUndefOrEqual(Mask[i], i + NumElems))
3943 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3944 if (!isUndefOrEqual(Mask[i], i))
3950 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3951 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3952 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3953 if (!VT.is128BitVector())
3956 unsigned NumElems = VT.getVectorNumElements();
3958 if (NumElems != 2 && NumElems != 4)
3961 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3962 if (!isUndefOrEqual(Mask[i], i))
3965 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3966 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3972 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
3973 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
3974 /// i. e: If all but one element come from the same vector.
3975 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
3976 // TODO: Deal with AVX's VINSERTPS
3977 if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
3980 unsigned CorrectPosV1 = 0;
3981 unsigned CorrectPosV2 = 0;
3982 for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
3983 if (Mask[i] == -1) {
3991 else if (Mask[i] == i + 4)
3995 if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
3996 // We have 3 elements (undefs count as elements from any vector) from one
3997 // vector, and one from another.
4004 // Some special combinations that can be optimized.
4007 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4008 SelectionDAG &DAG) {
4009 MVT VT = SVOp->getSimpleValueType(0);
4012 if (VT != MVT::v8i32 && VT != MVT::v8f32)
4015 ArrayRef<int> Mask = SVOp->getMask();
4017 // These are the special masks that may be optimized.
4018 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4019 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
4020 bool MatchEvenMask = true;
4021 bool MatchOddMask = true;
4022 for (int i=0; i<8; ++i) {
4023 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4024 MatchEvenMask = false;
4025 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4026 MatchOddMask = false;
4029 if (!MatchEvenMask && !MatchOddMask)
4032 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4034 SDValue Op0 = SVOp->getOperand(0);
4035 SDValue Op1 = SVOp->getOperand(1);
4037 if (MatchEvenMask) {
4038 // Shift the second operand right to 32 bits.
4039 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4040 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4042 // Shift the first operand left to 32 bits.
4043 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4044 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4046 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4047 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4050 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4051 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4052 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4053 bool HasInt256, bool V2IsSplat = false) {
4055 assert(VT.getSizeInBits() >= 128 &&
4056 "Unsupported vector type for unpckl");
4058 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4060 unsigned NumOf256BitLanes;
4061 unsigned NumElts = VT.getVectorNumElements();
4062 if (VT.is256BitVector()) {
4063 if (NumElts != 4 && NumElts != 8 &&
4064 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4067 NumOf256BitLanes = 1;
4068 } else if (VT.is512BitVector()) {
4069 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4070 "Unsupported vector type for unpckh");
4072 NumOf256BitLanes = 2;
4075 NumOf256BitLanes = 1;
4078 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4079 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4081 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4082 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4083 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4084 int BitI = Mask[l256*NumEltsInStride+l+i];
4085 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4086 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4088 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4090 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4098 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4099 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4100 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4101 bool HasInt256, bool V2IsSplat = false) {
4102 assert(VT.getSizeInBits() >= 128 &&
4103 "Unsupported vector type for unpckh");
4105 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4107 unsigned NumOf256BitLanes;
4108 unsigned NumElts = VT.getVectorNumElements();
4109 if (VT.is256BitVector()) {
4110 if (NumElts != 4 && NumElts != 8 &&
4111 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4114 NumOf256BitLanes = 1;
4115 } else if (VT.is512BitVector()) {
4116 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4117 "Unsupported vector type for unpckh");
4119 NumOf256BitLanes = 2;
4122 NumOf256BitLanes = 1;
4125 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4126 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4128 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4129 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4130 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4131 int BitI = Mask[l256*NumEltsInStride+l+i];
4132 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4133 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4135 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4137 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4145 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4146 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4148 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4149 unsigned NumElts = VT.getVectorNumElements();
4150 bool Is256BitVec = VT.is256BitVector();
4152 if (VT.is512BitVector())
4154 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4155 "Unsupported vector type for unpckh");
4157 if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4158 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4161 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4162 // FIXME: Need a better way to get rid of this, there's no latency difference
4163 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4164 // the former later. We should also remove the "_undef" special mask.
4165 if (NumElts == 4 && Is256BitVec)
4168 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4169 // independently on 128-bit lanes.
4170 unsigned NumLanes = VT.getSizeInBits()/128;
4171 unsigned NumLaneElts = NumElts/NumLanes;
4173 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4174 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4175 int BitI = Mask[l+i];
4176 int BitI1 = Mask[l+i+1];
4178 if (!isUndefOrEqual(BitI, j))
4180 if (!isUndefOrEqual(BitI1, j))
4188 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4189 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4191 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4192 unsigned NumElts = VT.getVectorNumElements();
4194 if (VT.is512BitVector())
4197 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4198 "Unsupported vector type for unpckh");
4200 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4201 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4204 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4205 // independently on 128-bit lanes.
4206 unsigned NumLanes = VT.getSizeInBits()/128;
4207 unsigned NumLaneElts = NumElts/NumLanes;
4209 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4210 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4211 int BitI = Mask[l+i];
4212 int BitI1 = Mask[l+i+1];
4213 if (!isUndefOrEqual(BitI, j))
4215 if (!isUndefOrEqual(BitI1, j))
4222 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4223 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4224 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4225 if (!VT.is512BitVector())
4228 unsigned NumElts = VT.getVectorNumElements();
4229 unsigned HalfSize = NumElts/2;
4230 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4231 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4236 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4237 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4245 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4246 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4247 /// MOVSD, and MOVD, i.e. setting the lowest element.
4248 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4249 if (VT.getVectorElementType().getSizeInBits() < 32)
4251 if (!VT.is128BitVector())
4254 unsigned NumElts = VT.getVectorNumElements();
4256 if (!isUndefOrEqual(Mask[0], NumElts))
4259 for (unsigned i = 1; i != NumElts; ++i)
4260 if (!isUndefOrEqual(Mask[i], i))
4266 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4267 /// as permutations between 128-bit chunks or halves. As an example: this
4269 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4270 /// The first half comes from the second half of V1 and the second half from the
4271 /// the second half of V2.
4272 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4273 if (!HasFp256 || !VT.is256BitVector())
4276 // The shuffle result is divided into half A and half B. In total the two
4277 // sources have 4 halves, namely: C, D, E, F. The final values of A and
4278 // B must come from C, D, E or F.
4279 unsigned HalfSize = VT.getVectorNumElements()/2;
4280 bool MatchA = false, MatchB = false;
4282 // Check if A comes from one of C, D, E, F.
4283 for (unsigned Half = 0; Half != 4; ++Half) {
4284 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4290 // Check if B comes from one of C, D, E, F.
4291 for (unsigned Half = 0; Half != 4; ++Half) {
4292 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4298 return MatchA && MatchB;
4301 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4302 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4303 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4304 MVT VT = SVOp->getSimpleValueType(0);
4306 unsigned HalfSize = VT.getVectorNumElements()/2;
4308 unsigned FstHalf = 0, SndHalf = 0;
4309 for (unsigned i = 0; i < HalfSize; ++i) {
4310 if (SVOp->getMaskElt(i) > 0) {
4311 FstHalf = SVOp->getMaskElt(i)/HalfSize;
4315 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4316 if (SVOp->getMaskElt(i) > 0) {
4317 SndHalf = SVOp->getMaskElt(i)/HalfSize;
4322 return (FstHalf | (SndHalf << 4));
4325 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4326 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4327 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4331 unsigned NumElts = VT.getVectorNumElements();
4333 if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4334 for (unsigned i = 0; i != NumElts; ++i) {
4337 Imm8 |= Mask[i] << (i*2);
4342 unsigned LaneSize = 4;
4343 SmallVector<int, 4> MaskVal(LaneSize, -1);
4345 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4346 for (unsigned i = 0; i != LaneSize; ++i) {
4347 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4351 if (MaskVal[i] < 0) {
4352 MaskVal[i] = Mask[i+l] - l;
4353 Imm8 |= MaskVal[i] << (i*2);
4356 if (Mask[i+l] != (signed)(MaskVal[i]+l))
4363 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4364 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4365 /// Note that VPERMIL mask matching is different depending whether theunderlying
4366 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4367 /// to the same elements of the low, but to the higher half of the source.
4368 /// In VPERMILPD the two lanes could be shuffled independently of each other
4369 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4370 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4371 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4372 if (VT.getSizeInBits() < 256 || EltSize < 32)
4374 bool symetricMaskRequired = (EltSize == 32);
4375 unsigned NumElts = VT.getVectorNumElements();
4377 unsigned NumLanes = VT.getSizeInBits()/128;
4378 unsigned LaneSize = NumElts/NumLanes;
4379 // 2 or 4 elements in one lane
4381 SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4382 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4383 for (unsigned i = 0; i != LaneSize; ++i) {
4384 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4386 if (symetricMaskRequired) {
4387 if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4388 ExpectedMaskVal[i] = Mask[i+l] - l;
4391 if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4399 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4400 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
4401 /// element of vector 2 and the other elements to come from vector 1 in order.
4402 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4403 bool V2IsSplat = false, bool V2IsUndef = false) {
4404 if (!VT.is128BitVector())
4407 unsigned NumOps = VT.getVectorNumElements();
4408 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4411 if (!isUndefOrEqual(Mask[0], 0))
4414 for (unsigned i = 1; i != NumOps; ++i)
4415 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4416 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4417 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4423 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4424 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4425 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4426 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4427 const X86Subtarget *Subtarget) {
4428 if (!Subtarget->hasSSE3())
4431 unsigned NumElems = VT.getVectorNumElements();
4433 if ((VT.is128BitVector() && NumElems != 4) ||
4434 (VT.is256BitVector() && NumElems != 8) ||
4435 (VT.is512BitVector() && NumElems != 16))
4438 // "i+1" is the value the indexed mask element must have
4439 for (unsigned i = 0; i != NumElems; i += 2)
4440 if (!isUndefOrEqual(Mask[i], i+1) ||
4441 !isUndefOrEqual(Mask[i+1], i+1))
4447 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4448 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4449 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4450 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4451 const X86Subtarget *Subtarget) {
4452 if (!Subtarget->hasSSE3())
4455 unsigned NumElems = VT.getVectorNumElements();
4457 if ((VT.is128BitVector() && NumElems != 4) ||
4458 (VT.is256BitVector() && NumElems != 8) ||
4459 (VT.is512BitVector() && NumElems != 16))
4462 // "i" is the value the indexed mask element must have
4463 for (unsigned i = 0; i != NumElems; i += 2)
4464 if (!isUndefOrEqual(Mask[i], i) ||
4465 !isUndefOrEqual(Mask[i+1], i))
4471 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4472 /// specifies a shuffle of elements that is suitable for input to 256-bit
4473 /// version of MOVDDUP.
4474 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4475 if (!HasFp256 || !VT.is256BitVector())
4478 unsigned NumElts = VT.getVectorNumElements();
4482 for (unsigned i = 0; i != NumElts/2; ++i)
4483 if (!isUndefOrEqual(Mask[i], 0))
4485 for (unsigned i = NumElts/2; i != NumElts; ++i)
4486 if (!isUndefOrEqual(Mask[i], NumElts/2))
4491 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4492 /// specifies a shuffle of elements that is suitable for input to 128-bit
4493 /// version of MOVDDUP.
4494 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4495 if (!VT.is128BitVector())
4498 unsigned e = VT.getVectorNumElements() / 2;
4499 for (unsigned i = 0; i != e; ++i)
4500 if (!isUndefOrEqual(Mask[i], i))
4502 for (unsigned i = 0; i != e; ++i)
4503 if (!isUndefOrEqual(Mask[e+i], i))
4508 /// isVEXTRACTIndex - Return true if the specified
4509 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4510 /// suitable for instruction that extract 128 or 256 bit vectors
4511 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4512 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4513 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4516 // The index should be aligned on a vecWidth-bit boundary.
4518 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4520 MVT VT = N->getSimpleValueType(0);
4521 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4522 bool Result = (Index * ElSize) % vecWidth == 0;
4527 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4528 /// operand specifies a subvector insert that is suitable for input to
4529 /// insertion of 128 or 256-bit subvectors
4530 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4531 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4532 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4534 // The index should be aligned on a vecWidth-bit boundary.
4536 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4538 MVT VT = N->getSimpleValueType(0);
4539 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4540 bool Result = (Index * ElSize) % vecWidth == 0;
4545 bool X86::isVINSERT128Index(SDNode *N) {
4546 return isVINSERTIndex(N, 128);
4549 bool X86::isVINSERT256Index(SDNode *N) {
4550 return isVINSERTIndex(N, 256);
4553 bool X86::isVEXTRACT128Index(SDNode *N) {
4554 return isVEXTRACTIndex(N, 128);
4557 bool X86::isVEXTRACT256Index(SDNode *N) {
4558 return isVEXTRACTIndex(N, 256);
4561 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4562 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4563 /// Handles 128-bit and 256-bit.
4564 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4565 MVT VT = N->getSimpleValueType(0);
4567 assert((VT.getSizeInBits() >= 128) &&
4568 "Unsupported vector type for PSHUF/SHUFP");
4570 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4571 // independently on 128-bit lanes.
4572 unsigned NumElts = VT.getVectorNumElements();
4573 unsigned NumLanes = VT.getSizeInBits()/128;
4574 unsigned NumLaneElts = NumElts/NumLanes;
4576 assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4577 "Only supports 2, 4 or 8 elements per lane");
4579 unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4581 for (unsigned i = 0; i != NumElts; ++i) {
4582 int Elt = N->getMaskElt(i);
4583 if (Elt < 0) continue;
4584 Elt &= NumLaneElts - 1;
4585 unsigned ShAmt = (i << Shift) % 8;
4586 Mask |= Elt << ShAmt;
4592 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4593 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4594 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4595 MVT VT = N->getSimpleValueType(0);
4597 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4598 "Unsupported vector type for PSHUFHW");
4600 unsigned NumElts = VT.getVectorNumElements();
4603 for (unsigned l = 0; l != NumElts; l += 8) {
4604 // 8 nodes per lane, but we only care about the last 4.
4605 for (unsigned i = 0; i < 4; ++i) {
4606 int Elt = N->getMaskElt(l+i+4);
4607 if (Elt < 0) continue;
4608 Elt &= 0x3; // only 2-bits.
4609 Mask |= Elt << (i * 2);
4616 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4617 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4618 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4619 MVT VT = N->getSimpleValueType(0);
4621 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4622 "Unsupported vector type for PSHUFHW");
4624 unsigned NumElts = VT.getVectorNumElements();
4627 for (unsigned l = 0; l != NumElts; l += 8) {
4628 // 8 nodes per lane, but we only care about the first 4.
4629 for (unsigned i = 0; i < 4; ++i) {
4630 int Elt = N->getMaskElt(l+i);
4631 if (Elt < 0) continue;
4632 Elt &= 0x3; // only 2-bits
4633 Mask |= Elt << (i * 2);
4640 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4641 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4642 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4643 MVT VT = SVOp->getSimpleValueType(0);
4644 unsigned EltSize = VT.is512BitVector() ? 1 :
4645 VT.getVectorElementType().getSizeInBits() >> 3;
4647 unsigned NumElts = VT.getVectorNumElements();
4648 unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4649 unsigned NumLaneElts = NumElts/NumLanes;
4653 for (i = 0; i != NumElts; ++i) {
4654 Val = SVOp->getMaskElt(i);
4658 if (Val >= (int)NumElts)
4659 Val -= NumElts - NumLaneElts;
4661 assert(Val - i > 0 && "PALIGNR imm should be positive");
4662 return (Val - i) * EltSize;
4665 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4666 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4667 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4668 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4671 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4673 MVT VecVT = N->getOperand(0).getSimpleValueType();
4674 MVT ElVT = VecVT.getVectorElementType();
4676 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4677 return Index / NumElemsPerChunk;
4680 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4681 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4682 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4683 llvm_unreachable("Illegal insert subvector for VINSERT");
4686 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4688 MVT VecVT = N->getSimpleValueType(0);
4689 MVT ElVT = VecVT.getVectorElementType();
4691 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4692 return Index / NumElemsPerChunk;
4695 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4696 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4697 /// and VINSERTI128 instructions.
4698 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4699 return getExtractVEXTRACTImmediate(N, 128);
4702 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4703 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4704 /// and VINSERTI64x4 instructions.
4705 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4706 return getExtractVEXTRACTImmediate(N, 256);
4709 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4710 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4711 /// and VINSERTI128 instructions.
4712 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4713 return getInsertVINSERTImmediate(N, 128);
4716 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4717 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4718 /// and VINSERTI64x4 instructions.
4719 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4720 return getInsertVINSERTImmediate(N, 256);
4723 /// isZero - Returns true if Elt is a constant integer zero
4724 static bool isZero(SDValue V) {
4725 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4726 return C && C->isNullValue();
4729 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4731 bool X86::isZeroNode(SDValue Elt) {
4734 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4735 return CFP->getValueAPF().isPosZero();
4739 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4740 /// their permute mask.
4741 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4742 SelectionDAG &DAG) {
4743 MVT VT = SVOp->getSimpleValueType(0);
4744 unsigned NumElems = VT.getVectorNumElements();
4745 SmallVector<int, 8> MaskVec;
4747 for (unsigned i = 0; i != NumElems; ++i) {
4748 int Idx = SVOp->getMaskElt(i);
4750 if (Idx < (int)NumElems)
4755 MaskVec.push_back(Idx);
4757 return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4758 SVOp->getOperand(0), &MaskVec[0]);
4761 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4762 /// match movhlps. The lower half elements should come from upper half of
4763 /// V1 (and in order), and the upper half elements should come from the upper
4764 /// half of V2 (and in order).
4765 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4766 if (!VT.is128BitVector())
4768 if (VT.getVectorNumElements() != 4)
4770 for (unsigned i = 0, e = 2; i != e; ++i)
4771 if (!isUndefOrEqual(Mask[i], i+2))
4773 for (unsigned i = 2; i != 4; ++i)
4774 if (!isUndefOrEqual(Mask[i], i+4))
4779 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4780 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4782 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4783 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4785 N = N->getOperand(0).getNode();
4786 if (!ISD::isNON_EXTLoad(N))
4789 *LD = cast<LoadSDNode>(N);
4793 // Test whether the given value is a vector value which will be legalized
4795 static bool WillBeConstantPoolLoad(SDNode *N) {
4796 if (N->getOpcode() != ISD::BUILD_VECTOR)
4799 // Check for any non-constant elements.
4800 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4801 switch (N->getOperand(i).getNode()->getOpcode()) {
4803 case ISD::ConstantFP:
4810 // Vectors of all-zeros and all-ones are materialized with special
4811 // instructions rather than being loaded.
4812 return !ISD::isBuildVectorAllZeros(N) &&
4813 !ISD::isBuildVectorAllOnes(N);
4816 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4817 /// match movlp{s|d}. The lower half elements should come from lower half of
4818 /// V1 (and in order), and the upper half elements should come from the upper
4819 /// half of V2 (and in order). And since V1 will become the source of the
4820 /// MOVLP, it must be either a vector load or a scalar load to vector.
4821 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4822 ArrayRef<int> Mask, MVT VT) {
4823 if (!VT.is128BitVector())
4826 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4828 // Is V2 is a vector load, don't do this transformation. We will try to use
4829 // load folding shufps op.
4830 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4833 unsigned NumElems = VT.getVectorNumElements();
4835 if (NumElems != 2 && NumElems != 4)
4837 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4838 if (!isUndefOrEqual(Mask[i], i))
4840 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4841 if (!isUndefOrEqual(Mask[i], i+NumElems))
4846 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4848 static bool isSplatVector(SDNode *N) {
4849 if (N->getOpcode() != ISD::BUILD_VECTOR)
4852 SDValue SplatValue = N->getOperand(0);
4853 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4854 if (N->getOperand(i) != SplatValue)
4859 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4860 /// to an zero vector.
4861 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4862 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4863 SDValue V1 = N->getOperand(0);
4864 SDValue V2 = N->getOperand(1);
4865 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4866 for (unsigned i = 0; i != NumElems; ++i) {
4867 int Idx = N->getMaskElt(i);
4868 if (Idx >= (int)NumElems) {
4869 unsigned Opc = V2.getOpcode();
4870 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4872 if (Opc != ISD::BUILD_VECTOR ||
4873 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4875 } else if (Idx >= 0) {
4876 unsigned Opc = V1.getOpcode();
4877 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4879 if (Opc != ISD::BUILD_VECTOR ||
4880 !X86::isZeroNode(V1.getOperand(Idx)))
4887 /// getZeroVector - Returns a vector of specified type with all zero elements.
4889 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4890 SelectionDAG &DAG, SDLoc dl) {
4891 assert(VT.isVector() && "Expected a vector type");
4893 // Always build SSE zero vectors as <4 x i32> bitcasted
4894 // to their dest type. This ensures they get CSE'd.
4896 if (VT.is128BitVector()) { // SSE
4897 if (Subtarget->hasSSE2()) { // SSE2
4898 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4899 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4901 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4902 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4904 } else if (VT.is256BitVector()) { // AVX
4905 if (Subtarget->hasInt256()) { // AVX2
4906 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4907 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4908 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4910 // 256-bit logic and arithmetic instructions in AVX are all
4911 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4912 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4913 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4914 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4916 } else if (VT.is512BitVector()) { // AVX-512
4917 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4918 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4919 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4920 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4921 } else if (VT.getScalarType() == MVT::i1) {
4922 assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4923 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4924 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4925 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4927 llvm_unreachable("Unexpected vector type");
4929 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4932 /// getOnesVector - Returns a vector of specified type with all bits set.
4933 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4934 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4935 /// Then bitcast to their original type, ensuring they get CSE'd.
4936 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4938 assert(VT.isVector() && "Expected a vector type");
4940 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4942 if (VT.is256BitVector()) {
4943 if (HasInt256) { // AVX2
4944 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4945 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4947 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4948 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4950 } else if (VT.is128BitVector()) {
4951 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4953 llvm_unreachable("Unexpected vector type");
4955 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4958 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4959 /// that point to V2 points to its first element.
4960 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4961 for (unsigned i = 0; i != NumElems; ++i) {
4962 if (Mask[i] > (int)NumElems) {
4968 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4969 /// operation of specified width.
4970 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4972 unsigned NumElems = VT.getVectorNumElements();
4973 SmallVector<int, 8> Mask;
4974 Mask.push_back(NumElems);
4975 for (unsigned i = 1; i != NumElems; ++i)
4977 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4980 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4981 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4983 unsigned NumElems = VT.getVectorNumElements();
4984 SmallVector<int, 8> Mask;
4985 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4987 Mask.push_back(i + NumElems);
4989 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4992 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4993 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4995 unsigned NumElems = VT.getVectorNumElements();
4996 SmallVector<int, 8> Mask;
4997 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4998 Mask.push_back(i + Half);
4999 Mask.push_back(i + NumElems + Half);
5001 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5004 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
5005 // a generic shuffle instruction because the target has no such instructions.
5006 // Generate shuffles which repeat i16 and i8 several times until they can be
5007 // represented by v4f32 and then be manipulated by target suported shuffles.
5008 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5009 MVT VT = V.getSimpleValueType();
5010 int NumElems = VT.getVectorNumElements();
5013 while (NumElems > 4) {
5014 if (EltNo < NumElems/2) {
5015 V = getUnpackl(DAG, dl, VT, V, V);
5017 V = getUnpackh(DAG, dl, VT, V, V);
5018 EltNo -= NumElems/2;
5025 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5026 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5027 MVT VT = V.getSimpleValueType();
5030 if (VT.is128BitVector()) {
5031 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5032 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5033 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5035 } else if (VT.is256BitVector()) {
5036 // To use VPERMILPS to splat scalars, the second half of indicies must
5037 // refer to the higher part, which is a duplication of the lower one,
5038 // because VPERMILPS can only handle in-lane permutations.
5039 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5040 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5042 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5043 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5046 llvm_unreachable("Vector size not supported");
5048 return DAG.getNode(ISD::BITCAST, dl, VT, V);
5051 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5052 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5053 MVT SrcVT = SV->getSimpleValueType(0);
5054 SDValue V1 = SV->getOperand(0);
5057 int EltNo = SV->getSplatIndex();
5058 int NumElems = SrcVT.getVectorNumElements();
5059 bool Is256BitVec = SrcVT.is256BitVector();
5061 assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5062 "Unknown how to promote splat for type");
5064 // Extract the 128-bit part containing the splat element and update
5065 // the splat element index when it refers to the higher register.
5067 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5068 if (EltNo >= NumElems/2)
5069 EltNo -= NumElems/2;
5072 // All i16 and i8 vector types can't be used directly by a generic shuffle
5073 // instruction because the target has no such instruction. Generate shuffles
5074 // which repeat i16 and i8 several times until they fit in i32, and then can
5075 // be manipulated by target suported shuffles.
5076 MVT EltVT = SrcVT.getVectorElementType();
5077 if (EltVT == MVT::i8 || EltVT == MVT::i16)
5078 V1 = PromoteSplati8i16(V1, DAG, EltNo);
5080 // Recreate the 256-bit vector and place the same 128-bit vector
5081 // into the low and high part. This is necessary because we want
5082 // to use VPERM* to shuffle the vectors
5084 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5087 return getLegalSplat(DAG, V1, EltNo);
5090 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5091 /// vector of zero or undef vector. This produces a shuffle where the low
5092 /// element of V2 is swizzled into the zero/undef vector, landing at element
5093 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
5094 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5096 const X86Subtarget *Subtarget,
5097 SelectionDAG &DAG) {
5098 MVT VT = V2.getSimpleValueType();
5100 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5101 unsigned NumElems = VT.getVectorNumElements();
5102 SmallVector<int, 16> MaskVec;
5103 for (unsigned i = 0; i != NumElems; ++i)
5104 // If this is the insertion idx, put the low elt of V2 here.
5105 MaskVec.push_back(i == Idx ? NumElems : i);
5106 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5109 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5110 /// target specific opcode. Returns true if the Mask could be calculated.
5111 /// Sets IsUnary to true if only uses one source.
5112 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5113 SmallVectorImpl<int> &Mask, bool &IsUnary) {
5114 unsigned NumElems = VT.getVectorNumElements();
5118 switch(N->getOpcode()) {
5120 ImmN = N->getOperand(N->getNumOperands()-1);
5121 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5123 case X86ISD::UNPCKH:
5124 DecodeUNPCKHMask(VT, Mask);
5126 case X86ISD::UNPCKL:
5127 DecodeUNPCKLMask(VT, Mask);
5129 case X86ISD::MOVHLPS:
5130 DecodeMOVHLPSMask(NumElems, Mask);
5132 case X86ISD::MOVLHPS:
5133 DecodeMOVLHPSMask(NumElems, Mask);
5135 case X86ISD::PALIGNR:
5136 ImmN = N->getOperand(N->getNumOperands()-1);
5137 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5139 case X86ISD::PSHUFD:
5140 case X86ISD::VPERMILP:
5141 ImmN = N->getOperand(N->getNumOperands()-1);
5142 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5145 case X86ISD::PSHUFHW:
5146 ImmN = N->getOperand(N->getNumOperands()-1);
5147 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5150 case X86ISD::PSHUFLW:
5151 ImmN = N->getOperand(N->getNumOperands()-1);
5152 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5155 case X86ISD::VPERMI:
5156 ImmN = N->getOperand(N->getNumOperands()-1);
5157 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5161 case X86ISD::MOVSD: {
5162 // The index 0 always comes from the first element of the second source,
5163 // this is why MOVSS and MOVSD are used in the first place. The other
5164 // elements come from the other positions of the first source vector
5165 Mask.push_back(NumElems);
5166 for (unsigned i = 1; i != NumElems; ++i) {
5171 case X86ISD::VPERM2X128:
5172 ImmN = N->getOperand(N->getNumOperands()-1);
5173 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5174 if (Mask.empty()) return false;
5176 case X86ISD::MOVDDUP:
5177 case X86ISD::MOVLHPD:
5178 case X86ISD::MOVLPD:
5179 case X86ISD::MOVLPS:
5180 case X86ISD::MOVSHDUP:
5181 case X86ISD::MOVSLDUP:
5182 // Not yet implemented
5184 default: llvm_unreachable("unknown target shuffle node");
5190 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5191 /// element of the result of the vector shuffle.
5192 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5195 return SDValue(); // Limit search depth.
5197 SDValue V = SDValue(N, 0);
5198 EVT VT = V.getValueType();
5199 unsigned Opcode = V.getOpcode();
5201 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5202 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5203 int Elt = SV->getMaskElt(Index);
5206 return DAG.getUNDEF(VT.getVectorElementType());
5208 unsigned NumElems = VT.getVectorNumElements();
5209 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5210 : SV->getOperand(1);
5211 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5214 // Recurse into target specific vector shuffles to find scalars.
5215 if (isTargetShuffle(Opcode)) {
5216 MVT ShufVT = V.getSimpleValueType();
5217 unsigned NumElems = ShufVT.getVectorNumElements();
5218 SmallVector<int, 16> ShuffleMask;
5221 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5224 int Elt = ShuffleMask[Index];
5226 return DAG.getUNDEF(ShufVT.getVectorElementType());
5228 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5230 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5234 // Actual nodes that may contain scalar elements
5235 if (Opcode == ISD::BITCAST) {
5236 V = V.getOperand(0);
5237 EVT SrcVT = V.getValueType();
5238 unsigned NumElems = VT.getVectorNumElements();
5240 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5244 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5245 return (Index == 0) ? V.getOperand(0)
5246 : DAG.getUNDEF(VT.getVectorElementType());
5248 if (V.getOpcode() == ISD::BUILD_VECTOR)
5249 return V.getOperand(Index);
5254 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5255 /// shuffle operation which come from a consecutively from a zero. The
5256 /// search can start in two different directions, from left or right.
5257 /// We count undefs as zeros until PreferredNum is reached.
5258 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5259 unsigned NumElems, bool ZerosFromLeft,
5261 unsigned PreferredNum = -1U) {
5262 unsigned NumZeros = 0;
5263 for (unsigned i = 0; i != NumElems; ++i) {
5264 unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5265 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5269 if (X86::isZeroNode(Elt))
5271 else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5272 NumZeros = std::min(NumZeros + 1, PreferredNum);
5280 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5281 /// correspond consecutively to elements from one of the vector operands,
5282 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5284 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5285 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5286 unsigned NumElems, unsigned &OpNum) {
5287 bool SeenV1 = false;
5288 bool SeenV2 = false;
5290 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5291 int Idx = SVOp->getMaskElt(i);
5292 // Ignore undef indicies
5296 if (Idx < (int)NumElems)
5301 // Only accept consecutive elements from the same vector
5302 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5306 OpNum = SeenV1 ? 0 : 1;
5310 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5311 /// logical left shift of a vector.
5312 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5313 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5315 SVOp->getSimpleValueType(0).getVectorNumElements();
5316 unsigned NumZeros = getNumOfConsecutiveZeros(
5317 SVOp, NumElems, false /* check zeros from right */, DAG,
5318 SVOp->getMaskElt(0));
5324 // Considering the elements in the mask that are not consecutive zeros,
5325 // check if they consecutively come from only one of the source vectors.
5327 // V1 = {X, A, B, C} 0
5329 // vector_shuffle V1, V2 <1, 2, 3, X>
5331 if (!isShuffleMaskConsecutive(SVOp,
5332 0, // Mask Start Index
5333 NumElems-NumZeros, // Mask End Index(exclusive)
5334 NumZeros, // Where to start looking in the src vector
5335 NumElems, // Number of elements in vector
5336 OpSrc)) // Which source operand ?
5341 ShVal = SVOp->getOperand(OpSrc);
5345 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5346 /// logical left shift of a vector.
5347 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5348 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5350 SVOp->getSimpleValueType(0).getVectorNumElements();
5351 unsigned NumZeros = getNumOfConsecutiveZeros(
5352 SVOp, NumElems, true /* check zeros from left */, DAG,
5353 NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5359 // Considering the elements in the mask that are not consecutive zeros,
5360 // check if they consecutively come from only one of the source vectors.
5362 // 0 { A, B, X, X } = V2
5364 // vector_shuffle V1, V2 <X, X, 4, 5>
5366 if (!isShuffleMaskConsecutive(SVOp,
5367 NumZeros, // Mask Start Index
5368 NumElems, // Mask End Index(exclusive)
5369 0, // Where to start looking in the src vector
5370 NumElems, // Number of elements in vector
5371 OpSrc)) // Which source operand ?
5376 ShVal = SVOp->getOperand(OpSrc);
5380 /// isVectorShift - Returns true if the shuffle can be implemented as a
5381 /// logical left or right shift of a vector.
5382 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5383 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5384 // Although the logic below support any bitwidth size, there are no
5385 // shift instructions which handle more than 128-bit vectors.
5386 if (!SVOp->getSimpleValueType(0).is128BitVector())
5389 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5390 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5396 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5398 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5399 unsigned NumNonZero, unsigned NumZero,
5401 const X86Subtarget* Subtarget,
5402 const TargetLowering &TLI) {
5409 for (unsigned i = 0; i < 16; ++i) {
5410 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5411 if (ThisIsNonZero && First) {
5413 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5415 V = DAG.getUNDEF(MVT::v8i16);
5420 SDValue ThisElt, LastElt;
5421 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5422 if (LastIsNonZero) {
5423 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5424 MVT::i16, Op.getOperand(i-1));
5426 if (ThisIsNonZero) {
5427 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5428 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5429 ThisElt, DAG.getConstant(8, MVT::i8));
5431 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5435 if (ThisElt.getNode())
5436 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5437 DAG.getIntPtrConstant(i/2));
5441 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5444 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5446 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5447 unsigned NumNonZero, unsigned NumZero,
5449 const X86Subtarget* Subtarget,
5450 const TargetLowering &TLI) {
5457 for (unsigned i = 0; i < 8; ++i) {
5458 bool isNonZero = (NonZeros & (1 << i)) != 0;
5462 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5464 V = DAG.getUNDEF(MVT::v8i16);
5467 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5468 MVT::v8i16, V, Op.getOperand(i),
5469 DAG.getIntPtrConstant(i));
5476 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5477 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5478 unsigned NonZeros, unsigned NumNonZero,
5479 unsigned NumZero, SelectionDAG &DAG,
5480 const X86Subtarget *Subtarget,
5481 const TargetLowering &TLI) {
5482 // We know there's at least one non-zero element
5483 unsigned FirstNonZeroIdx = 0;
5484 SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5485 while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5486 X86::isZeroNode(FirstNonZero)) {
5488 FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5491 if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5492 !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5495 SDValue V = FirstNonZero.getOperand(0);
5496 MVT VVT = V.getSimpleValueType();
5497 if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5500 unsigned FirstNonZeroDst =
5501 cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5502 unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5503 unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5504 unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5506 for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5507 SDValue Elem = Op.getOperand(Idx);
5508 if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5511 // TODO: What else can be here? Deal with it.
5512 if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5515 // TODO: Some optimizations are still possible here
5516 // ex: Getting one element from a vector, and the rest from another.
5517 if (Elem.getOperand(0) != V)
5520 unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5523 else if (IncorrectIdx == -1U) {
5527 // There was already one element with an incorrect index.
5528 // We can't optimize this case to an insertps.
5532 if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5534 EVT VT = Op.getSimpleValueType();
5535 unsigned ElementMoveMask = 0;
5536 if (IncorrectIdx == -1U)
5537 ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5539 ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5541 SDValue InsertpsMask =
5542 DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5543 return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5549 /// getVShift - Return a vector logical shift node.
5551 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5552 unsigned NumBits, SelectionDAG &DAG,
5553 const TargetLowering &TLI, SDLoc dl) {
5554 assert(VT.is128BitVector() && "Unknown type for VShift");
5555 EVT ShVT = MVT::v2i64;
5556 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5557 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5558 return DAG.getNode(ISD::BITCAST, dl, VT,
5559 DAG.getNode(Opc, dl, ShVT, SrcOp,
5560 DAG.getConstant(NumBits,
5561 TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5565 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5567 // Check if the scalar load can be widened into a vector load. And if
5568 // the address is "base + cst" see if the cst can be "absorbed" into
5569 // the shuffle mask.
5570 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5571 SDValue Ptr = LD->getBasePtr();
5572 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5574 EVT PVT = LD->getValueType(0);
5575 if (PVT != MVT::i32 && PVT != MVT::f32)
5580 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5581 FI = FINode->getIndex();
5583 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5584 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5585 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5586 Offset = Ptr.getConstantOperandVal(1);
5587 Ptr = Ptr.getOperand(0);
5592 // FIXME: 256-bit vector instructions don't require a strict alignment,
5593 // improve this code to support it better.
5594 unsigned RequiredAlign = VT.getSizeInBits()/8;
5595 SDValue Chain = LD->getChain();
5596 // Make sure the stack object alignment is at least 16 or 32.
5597 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5598 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5599 if (MFI->isFixedObjectIndex(FI)) {
5600 // Can't change the alignment. FIXME: It's possible to compute
5601 // the exact stack offset and reference FI + adjust offset instead.
5602 // If someone *really* cares about this. That's the way to implement it.
5605 MFI->setObjectAlignment(FI, RequiredAlign);
5609 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5610 // Ptr + (Offset & ~15).
5613 if ((Offset % RequiredAlign) & 3)
5615 int64_t StartOffset = Offset & ~(RequiredAlign-1);
5617 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5618 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5620 int EltNo = (Offset - StartOffset) >> 2;
5621 unsigned NumElems = VT.getVectorNumElements();
5623 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5624 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5625 LD->getPointerInfo().getWithOffset(StartOffset),
5626 false, false, false, 0);
5628 SmallVector<int, 8> Mask;
5629 for (unsigned i = 0; i != NumElems; ++i)
5630 Mask.push_back(EltNo);
5632 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5638 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5639 /// vector of type 'VT', see if the elements can be replaced by a single large
5640 /// load which has the same value as a build_vector whose operands are 'elts'.
5642 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5644 /// FIXME: we'd also like to handle the case where the last elements are zero
5645 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5646 /// There's even a handy isZeroNode for that purpose.
5647 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5648 SDLoc &DL, SelectionDAG &DAG,
5649 bool isAfterLegalize) {
5650 EVT EltVT = VT.getVectorElementType();
5651 unsigned NumElems = Elts.size();
5653 LoadSDNode *LDBase = nullptr;
5654 unsigned LastLoadedElt = -1U;
5656 // For each element in the initializer, see if we've found a load or an undef.
5657 // If we don't find an initial load element, or later load elements are
5658 // non-consecutive, bail out.
5659 for (unsigned i = 0; i < NumElems; ++i) {
5660 SDValue Elt = Elts[i];
5662 if (!Elt.getNode() ||
5663 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5666 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5668 LDBase = cast<LoadSDNode>(Elt.getNode());
5672 if (Elt.getOpcode() == ISD::UNDEF)
5675 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5676 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5681 // If we have found an entire vector of loads and undefs, then return a large
5682 // load of the entire vector width starting at the base pointer. If we found
5683 // consecutive loads for the low half, generate a vzext_load node.
5684 if (LastLoadedElt == NumElems - 1) {
5686 if (isAfterLegalize &&
5687 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5690 SDValue NewLd = SDValue();
5692 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5693 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5694 LDBase->getPointerInfo(),
5695 LDBase->isVolatile(), LDBase->isNonTemporal(),
5696 LDBase->isInvariant(), 0);
5697 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5698 LDBase->getPointerInfo(),
5699 LDBase->isVolatile(), LDBase->isNonTemporal(),
5700 LDBase->isInvariant(), LDBase->getAlignment());
5702 if (LDBase->hasAnyUseOfValue(1)) {
5703 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5705 SDValue(NewLd.getNode(), 1));
5706 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5707 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5708 SDValue(NewLd.getNode(), 1));
5713 if (NumElems == 4 && LastLoadedElt == 1 &&
5714 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5715 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5716 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5718 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5719 LDBase->getPointerInfo(),
5720 LDBase->getAlignment(),
5721 false/*isVolatile*/, true/*ReadMem*/,
5724 // Make sure the newly-created LOAD is in the same position as LDBase in
5725 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5726 // update uses of LDBase's output chain to use the TokenFactor.
5727 if (LDBase->hasAnyUseOfValue(1)) {
5728 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5729 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5730 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5731 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5732 SDValue(ResNode.getNode(), 1));
5735 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5740 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5741 /// to generate a splat value for the following cases:
5742 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5743 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5744 /// a scalar load, or a constant.
5745 /// The VBROADCAST node is returned when a pattern is found,
5746 /// or SDValue() otherwise.
5747 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5748 SelectionDAG &DAG) {
5749 if (!Subtarget->hasFp256())
5752 MVT VT = Op.getSimpleValueType();
5755 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5756 "Unsupported vector type for broadcast.");
5761 switch (Op.getOpcode()) {
5763 // Unknown pattern found.
5766 case ISD::BUILD_VECTOR: {
5767 // The BUILD_VECTOR node must be a splat.
5768 if (!isSplatVector(Op.getNode()))
5771 Ld = Op.getOperand(0);
5772 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5773 Ld.getOpcode() == ISD::ConstantFP);
5775 // The suspected load node has several users. Make sure that all
5776 // of its users are from the BUILD_VECTOR node.
5777 // Constants may have multiple users.
5778 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5783 case ISD::VECTOR_SHUFFLE: {
5784 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5786 // Shuffles must have a splat mask where the first element is
5788 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5791 SDValue Sc = Op.getOperand(0);
5792 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5793 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5795 if (!Subtarget->hasInt256())
5798 // Use the register form of the broadcast instruction available on AVX2.
5799 if (VT.getSizeInBits() >= 256)
5800 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5801 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5804 Ld = Sc.getOperand(0);
5805 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5806 Ld.getOpcode() == ISD::ConstantFP);
5808 // The scalar_to_vector node and the suspected
5809 // load node must have exactly one user.
5810 // Constants may have multiple users.
5812 // AVX-512 has register version of the broadcast
5813 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5814 Ld.getValueType().getSizeInBits() >= 32;
5815 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5822 bool IsGE256 = (VT.getSizeInBits() >= 256);
5824 // Handle the broadcasting a single constant scalar from the constant pool
5825 // into a vector. On Sandybridge it is still better to load a constant vector
5826 // from the constant pool and not to broadcast it from a scalar.
5827 if (ConstSplatVal && Subtarget->hasInt256()) {
5828 EVT CVT = Ld.getValueType();
5829 assert(!CVT.isVector() && "Must not broadcast a vector type");
5830 unsigned ScalarSize = CVT.getSizeInBits();
5832 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5833 const Constant *C = nullptr;
5834 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5835 C = CI->getConstantIntValue();
5836 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5837 C = CF->getConstantFPValue();
5839 assert(C && "Invalid constant type");
5841 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5842 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5843 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5844 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5845 MachinePointerInfo::getConstantPool(),
5846 false, false, false, Alignment);
5848 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5852 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5853 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5855 // Handle AVX2 in-register broadcasts.
5856 if (!IsLoad && Subtarget->hasInt256() &&
5857 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5858 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5860 // The scalar source must be a normal load.
5864 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5865 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5867 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5868 // double since there is no vbroadcastsd xmm
5869 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5870 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5871 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5874 // Unsupported broadcast.
5878 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5879 /// underlying vector and index.
5881 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5883 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5885 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5886 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5889 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5891 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5893 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5894 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5897 // In this case the vector is the extract_subvector expression and the index
5898 // is 2, as specified by the shuffle.
5899 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5900 SDValue ShuffleVec = SVOp->getOperand(0);
5901 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5902 assert(ShuffleVecVT.getVectorElementType() ==
5903 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5905 int ShuffleIdx = SVOp->getMaskElt(Idx);
5906 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5907 ExtractedFromVec = ShuffleVec;
5913 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5914 MVT VT = Op.getSimpleValueType();
5916 // Skip if insert_vec_elt is not supported.
5917 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5918 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5922 unsigned NumElems = Op.getNumOperands();
5926 SmallVector<unsigned, 4> InsertIndices;
5927 SmallVector<int, 8> Mask(NumElems, -1);
5929 for (unsigned i = 0; i != NumElems; ++i) {
5930 unsigned Opc = Op.getOperand(i).getOpcode();
5932 if (Opc == ISD::UNDEF)
5935 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5936 // Quit if more than 1 elements need inserting.
5937 if (InsertIndices.size() > 1)
5940 InsertIndices.push_back(i);
5944 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5945 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5946 // Quit if non-constant index.
5947 if (!isa<ConstantSDNode>(ExtIdx))
5949 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5951 // Quit if extracted from vector of different type.
5952 if (ExtractedFromVec.getValueType() != VT)
5955 if (!VecIn1.getNode())
5956 VecIn1 = ExtractedFromVec;
5957 else if (VecIn1 != ExtractedFromVec) {
5958 if (!VecIn2.getNode())
5959 VecIn2 = ExtractedFromVec;
5960 else if (VecIn2 != ExtractedFromVec)
5961 // Quit if more than 2 vectors to shuffle
5965 if (ExtractedFromVec == VecIn1)
5967 else if (ExtractedFromVec == VecIn2)
5968 Mask[i] = Idx + NumElems;
5971 if (!VecIn1.getNode())
5974 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5975 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5976 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5977 unsigned Idx = InsertIndices[i];
5978 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5979 DAG.getIntPtrConstant(Idx));
5985 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5987 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5989 MVT VT = Op.getSimpleValueType();
5990 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5991 "Unexpected type in LowerBUILD_VECTORvXi1!");
5994 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5995 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5996 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5997 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6000 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
6001 SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
6002 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6003 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6006 bool AllContants = true;
6007 uint64_t Immediate = 0;
6008 int NonConstIdx = -1;
6009 bool IsSplat = true;
6010 unsigned NumNonConsts = 0;
6011 unsigned NumConsts = 0;
6012 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6013 SDValue In = Op.getOperand(idx);
6014 if (In.getOpcode() == ISD::UNDEF)
6016 if (!isa<ConstantSDNode>(In)) {
6017 AllContants = false;
6023 if (cast<ConstantSDNode>(In)->getZExtValue())
6024 Immediate |= (1ULL << idx);
6026 if (In != Op.getOperand(0))
6031 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6032 DAG.getConstant(Immediate, MVT::i16));
6033 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6034 DAG.getIntPtrConstant(0));
6037 if (NumNonConsts == 1 && NonConstIdx != 0) {
6040 SDValue VecAsImm = DAG.getConstant(Immediate,
6041 MVT::getIntegerVT(VT.getSizeInBits()));
6042 DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6045 DstVec = DAG.getUNDEF(VT);
6046 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6047 Op.getOperand(NonConstIdx),
6048 DAG.getIntPtrConstant(NonConstIdx));
6050 if (!IsSplat && (NonConstIdx != 0))
6051 llvm_unreachable("Unsupported BUILD_VECTOR operation");
6052 MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6055 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6056 DAG.getConstant(-1, SelectVT),
6057 DAG.getConstant(0, SelectVT));
6059 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6060 DAG.getConstant((Immediate | 1), SelectVT),
6061 DAG.getConstant(Immediate, SelectVT));
6062 return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6065 /// \brief Return true if \p N implements a horizontal binop and return the
6066 /// operands for the horizontal binop into V0 and V1.
6068 /// This is a helper function of PerformBUILD_VECTORCombine.
6069 /// This function checks that the build_vector \p N in input implements a
6070 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
6071 /// operation to match.
6072 /// For example, if \p Opcode is equal to ISD::ADD, then this function
6073 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
6074 /// is equal to ISD::SUB, then this function checks if this is a horizontal
6077 /// This function only analyzes elements of \p N whose indices are
6078 /// in range [BaseIdx, LastIdx).
6079 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
6081 unsigned BaseIdx, unsigned LastIdx,
6082 SDValue &V0, SDValue &V1) {
6083 EVT VT = N->getValueType(0);
6085 assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
6086 assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
6087 "Invalid Vector in input!");
6089 bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
6090 bool CanFold = true;
6091 unsigned ExpectedVExtractIdx = BaseIdx;
6092 unsigned NumElts = LastIdx - BaseIdx;
6093 V0 = DAG.getUNDEF(VT);
6094 V1 = DAG.getUNDEF(VT);
6096 // Check if N implements a horizontal binop.
6097 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
6098 SDValue Op = N->getOperand(i + BaseIdx);
6101 if (Op->getOpcode() == ISD::UNDEF) {
6102 // Update the expected vector extract index.
6103 if (i * 2 == NumElts)
6104 ExpectedVExtractIdx = BaseIdx;
6105 ExpectedVExtractIdx += 2;
6109 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6114 SDValue Op0 = Op.getOperand(0);
6115 SDValue Op1 = Op.getOperand(1);
6117 // Try to match the following pattern:
6118 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6119 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6120 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6121 Op0.getOperand(0) == Op1.getOperand(0) &&
6122 isa<ConstantSDNode>(Op0.getOperand(1)) &&
6123 isa<ConstantSDNode>(Op1.getOperand(1)));
6127 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6128 unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6130 if (i * 2 < NumElts) {
6131 if (V0.getOpcode() == ISD::UNDEF)
6132 V0 = Op0.getOperand(0);
6134 if (V1.getOpcode() == ISD::UNDEF)
6135 V1 = Op0.getOperand(0);
6136 if (i * 2 == NumElts)
6137 ExpectedVExtractIdx = BaseIdx;
6140 SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
6141 if (I0 == ExpectedVExtractIdx)
6142 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6143 else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6144 // Try to match the following dag sequence:
6145 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6146 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6150 ExpectedVExtractIdx += 2;
6156 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6157 /// a concat_vector.
6159 /// This is a helper function of PerformBUILD_VECTORCombine.
6160 /// This function expects two 256-bit vectors called V0 and V1.
6161 /// At first, each vector is split into two separate 128-bit vectors.
6162 /// Then, the resulting 128-bit vectors are used to implement two
6163 /// horizontal binary operations.
6165 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6167 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6168 /// the two new horizontal binop.
6169 /// When Mode is set, the first horizontal binop dag node would take as input
6170 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6171 /// horizontal binop dag node would take as input the lower 128-bit of V1
6172 /// and the upper 128-bit of V1.
6174 /// HADD V0_LO, V0_HI
6175 /// HADD V1_LO, V1_HI
6177 /// Otherwise, the first horizontal binop dag node takes as input the lower
6178 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6179 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
6181 /// HADD V0_LO, V1_LO
6182 /// HADD V0_HI, V1_HI
6184 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6185 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6186 /// the upper 128-bits of the result.
6187 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6188 SDLoc DL, SelectionDAG &DAG,
6189 unsigned X86Opcode, bool Mode,
6190 bool isUndefLO, bool isUndefHI) {
6191 EVT VT = V0.getValueType();
6192 assert(VT.is256BitVector() && VT == V1.getValueType() &&
6193 "Invalid nodes in input!");
6195 unsigned NumElts = VT.getVectorNumElements();
6196 SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6197 SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6198 SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6199 SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6200 EVT NewVT = V0_LO.getValueType();
6202 SDValue LO = DAG.getUNDEF(NewVT);
6203 SDValue HI = DAG.getUNDEF(NewVT);
6206 // Don't emit a horizontal binop if the result is expected to be UNDEF.
6207 if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6208 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6209 if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6210 HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6212 // Don't emit a horizontal binop if the result is expected to be UNDEF.
6213 if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6214 V1_LO->getOpcode() != ISD::UNDEF))
6215 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6217 if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6218 V1_HI->getOpcode() != ISD::UNDEF))
6219 HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6222 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6225 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6226 const X86Subtarget *Subtarget) {
6228 EVT VT = N->getValueType(0);
6229 unsigned NumElts = VT.getVectorNumElements();
6230 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
6231 SDValue InVec0, InVec1;
6233 // Try to match horizontal ADD/SUB.
6234 unsigned NumUndefsLO = 0;
6235 unsigned NumUndefsHI = 0;
6236 unsigned Half = NumElts/2;
6238 // Count the number of UNDEF operands in the build_vector in input.
6239 for (unsigned i = 0, e = Half; i != e; ++i)
6240 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6243 for (unsigned i = Half, e = NumElts; i != e; ++i)
6244 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6247 // Early exit if this is either a build_vector of all UNDEFs or all the
6248 // operands but one are UNDEF.
6249 if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6252 if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6253 // Try to match an SSE3 float HADD/HSUB.
6254 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6255 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6257 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6258 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6259 } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6260 // Try to match an SSSE3 integer HADD/HSUB.
6261 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6262 return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6264 if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6265 return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6268 if (!Subtarget->hasAVX())
6271 if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6272 // Try to match an AVX horizontal add/sub of packed single/double
6273 // precision floating point values from 256-bit vectors.
6274 SDValue InVec2, InVec3;
6275 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6276 isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6277 ((InVec0.getOpcode() == ISD::UNDEF ||
6278 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6279 ((InVec1.getOpcode() == ISD::UNDEF ||
6280 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6281 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6283 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6284 isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6285 ((InVec0.getOpcode() == ISD::UNDEF ||
6286 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6287 ((InVec1.getOpcode() == ISD::UNDEF ||
6288 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6289 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6290 } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6291 // Try to match an AVX2 horizontal add/sub of signed integers.
6292 SDValue InVec2, InVec3;
6294 bool CanFold = true;
6296 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6297 isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6298 ((InVec0.getOpcode() == ISD::UNDEF ||
6299 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6300 ((InVec1.getOpcode() == ISD::UNDEF ||
6301 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6302 X86Opcode = X86ISD::HADD;
6303 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6304 isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6305 ((InVec0.getOpcode() == ISD::UNDEF ||
6306 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6307 ((InVec1.getOpcode() == ISD::UNDEF ||
6308 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6309 X86Opcode = X86ISD::HSUB;
6314 // Fold this build_vector into a single horizontal add/sub.
6315 // Do this only if the target has AVX2.
6316 if (Subtarget->hasAVX2())
6317 return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6319 // Do not try to expand this build_vector into a pair of horizontal
6320 // add/sub if we can emit a pair of scalar add/sub.
6321 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6324 // Convert this build_vector into a pair of horizontal binop followed by
6326 bool isUndefLO = NumUndefsLO == Half;
6327 bool isUndefHI = NumUndefsHI == Half;
6328 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6329 isUndefLO, isUndefHI);
6333 if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6334 VT == MVT::v16i16) && Subtarget->hasAVX()) {
6336 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6337 X86Opcode = X86ISD::HADD;
6338 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6339 X86Opcode = X86ISD::HSUB;
6340 else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6341 X86Opcode = X86ISD::FHADD;
6342 else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6343 X86Opcode = X86ISD::FHSUB;
6347 // Don't try to expand this build_vector into a pair of horizontal add/sub
6348 // if we can simply emit a pair of scalar add/sub.
6349 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6352 // Convert this build_vector into two horizontal add/sub followed by
6354 bool isUndefLO = NumUndefsLO == Half;
6355 bool isUndefHI = NumUndefsHI == Half;
6356 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6357 isUndefLO, isUndefHI);
6364 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6367 MVT VT = Op.getSimpleValueType();
6368 MVT ExtVT = VT.getVectorElementType();
6369 unsigned NumElems = Op.getNumOperands();
6371 // Generate vectors for predicate vectors.
6372 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6373 return LowerBUILD_VECTORvXi1(Op, DAG);
6375 // Vectors containing all zeros can be matched by pxor and xorps later
6376 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6377 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6378 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6379 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6382 return getZeroVector(VT, Subtarget, DAG, dl);
6385 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6386 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6387 // vpcmpeqd on 256-bit vectors.
6388 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6389 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6392 if (!VT.is512BitVector())
6393 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6396 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6397 if (Broadcast.getNode())
6400 unsigned EVTBits = ExtVT.getSizeInBits();
6402 unsigned NumZero = 0;
6403 unsigned NumNonZero = 0;
6404 unsigned NonZeros = 0;
6405 bool IsAllConstants = true;
6406 SmallSet<SDValue, 8> Values;
6407 for (unsigned i = 0; i < NumElems; ++i) {
6408 SDValue Elt = Op.getOperand(i);
6409 if (Elt.getOpcode() == ISD::UNDEF)
6412 if (Elt.getOpcode() != ISD::Constant &&
6413 Elt.getOpcode() != ISD::ConstantFP)
6414 IsAllConstants = false;
6415 if (X86::isZeroNode(Elt))
6418 NonZeros |= (1 << i);
6423 // All undef vector. Return an UNDEF. All zero vectors were handled above.
6424 if (NumNonZero == 0)
6425 return DAG.getUNDEF(VT);
6427 // Special case for single non-zero, non-undef, element.
6428 if (NumNonZero == 1) {
6429 unsigned Idx = countTrailingZeros(NonZeros);
6430 SDValue Item = Op.getOperand(Idx);
6432 // If this is an insertion of an i64 value on x86-32, and if the top bits of
6433 // the value are obviously zero, truncate the value to i32 and do the
6434 // insertion that way. Only do this if the value is non-constant or if the
6435 // value is a constant being inserted into element 0. It is cheaper to do
6436 // a constant pool load than it is to do a movd + shuffle.
6437 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6438 (!IsAllConstants || Idx == 0)) {
6439 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6441 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6442 EVT VecVT = MVT::v4i32;
6443 unsigned VecElts = 4;
6445 // Truncate the value (which may itself be a constant) to i32, and
6446 // convert it to a vector with movd (S2V+shuffle to zero extend).
6447 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6448 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6449 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6451 // Now we have our 32-bit value zero extended in the low element of
6452 // a vector. If Idx != 0, swizzle it into place.
6454 SmallVector<int, 4> Mask;
6455 Mask.push_back(Idx);
6456 for (unsigned i = 1; i != VecElts; ++i)
6458 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6461 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6465 // If we have a constant or non-constant insertion into the low element of
6466 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6467 // the rest of the elements. This will be matched as movd/movq/movss/movsd
6468 // depending on what the source datatype is.
6471 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6473 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6474 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6475 if (VT.is256BitVector() || VT.is512BitVector()) {
6476 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6477 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6478 Item, DAG.getIntPtrConstant(0));
6480 assert(VT.is128BitVector() && "Expected an SSE value type!");
6481 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6482 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6483 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6486 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6487 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6488 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6489 if (VT.is256BitVector()) {
6490 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6491 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6493 assert(VT.is128BitVector() && "Expected an SSE value type!");
6494 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6496 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6500 // Is it a vector logical left shift?
6501 if (NumElems == 2 && Idx == 1 &&
6502 X86::isZeroNode(Op.getOperand(0)) &&
6503 !X86::isZeroNode(Op.getOperand(1))) {
6504 unsigned NumBits = VT.getSizeInBits();
6505 return getVShift(true, VT,
6506 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6507 VT, Op.getOperand(1)),
6508 NumBits/2, DAG, *this, dl);
6511 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6514 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6515 // is a non-constant being inserted into an element other than the low one,
6516 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6517 // movd/movss) to move this into the low element, then shuffle it into
6519 if (EVTBits == 32) {
6520 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6522 // Turn it into a shuffle of zero and zero-extended scalar to vector.
6523 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6524 SmallVector<int, 8> MaskVec;
6525 for (unsigned i = 0; i != NumElems; ++i)
6526 MaskVec.push_back(i == Idx ? 0 : 1);
6527 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6531 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6532 if (Values.size() == 1) {
6533 if (EVTBits == 32) {
6534 // Instead of a shuffle like this:
6535 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6536 // Check if it's possible to issue this instead.
6537 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6538 unsigned Idx = countTrailingZeros(NonZeros);
6539 SDValue Item = Op.getOperand(Idx);
6540 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6541 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6546 // A vector full of immediates; various special cases are already
6547 // handled, so this is best done with a single constant-pool load.
6551 // For AVX-length vectors, build the individual 128-bit pieces and use
6552 // shuffles to put them in place.
6553 if (VT.is256BitVector() || VT.is512BitVector()) {
6554 SmallVector<SDValue, 64> V;
6555 for (unsigned i = 0; i != NumElems; ++i)
6556 V.push_back(Op.getOperand(i));
6558 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6560 // Build both the lower and upper subvector.
6561 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6562 makeArrayRef(&V[0], NumElems/2));
6563 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6564 makeArrayRef(&V[NumElems / 2], NumElems/2));
6566 // Recreate the wider vector with the lower and upper part.
6567 if (VT.is256BitVector())
6568 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6569 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6572 // Let legalizer expand 2-wide build_vectors.
6573 if (EVTBits == 64) {
6574 if (NumNonZero == 1) {
6575 // One half is zero or undef.
6576 unsigned Idx = countTrailingZeros(NonZeros);
6577 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6578 Op.getOperand(Idx));
6579 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6584 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6585 if (EVTBits == 8 && NumElems == 16) {
6586 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6588 if (V.getNode()) return V;
6591 if (EVTBits == 16 && NumElems == 8) {
6592 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6594 if (V.getNode()) return V;
6597 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6598 if (EVTBits == 32 && NumElems == 4) {
6599 SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6600 NumZero, DAG, Subtarget, *this);
6605 // If element VT is == 32 bits, turn it into a number of shuffles.
6606 SmallVector<SDValue, 8> V(NumElems);
6607 if (NumElems == 4 && NumZero > 0) {
6608 for (unsigned i = 0; i < 4; ++i) {
6609 bool isZero = !(NonZeros & (1 << i));
6611 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6613 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6616 for (unsigned i = 0; i < 2; ++i) {
6617 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6620 V[i] = V[i*2]; // Must be a zero vector.
6623 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6626 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6629 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6634 bool Reverse1 = (NonZeros & 0x3) == 2;
6635 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6639 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6640 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6642 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6645 if (Values.size() > 1 && VT.is128BitVector()) {
6646 // Check for a build vector of consecutive loads.
6647 for (unsigned i = 0; i < NumElems; ++i)
6648 V[i] = Op.getOperand(i);
6650 // Check for elements which are consecutive loads.
6651 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6655 // Check for a build vector from mostly shuffle plus few inserting.
6656 SDValue Sh = buildFromShuffleMostly(Op, DAG);
6660 // For SSE 4.1, use insertps to put the high elements into the low element.
6661 if (getSubtarget()->hasSSE41()) {
6663 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6664 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6666 Result = DAG.getUNDEF(VT);
6668 for (unsigned i = 1; i < NumElems; ++i) {
6669 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6670 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6671 Op.getOperand(i), DAG.getIntPtrConstant(i));
6676 // Otherwise, expand into a number of unpckl*, start by extending each of
6677 // our (non-undef) elements to the full vector width with the element in the
6678 // bottom slot of the vector (which generates no code for SSE).
6679 for (unsigned i = 0; i < NumElems; ++i) {
6680 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6681 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6683 V[i] = DAG.getUNDEF(VT);
6686 // Next, we iteratively mix elements, e.g. for v4f32:
6687 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6688 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6689 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6690 unsigned EltStride = NumElems >> 1;
6691 while (EltStride != 0) {
6692 for (unsigned i = 0; i < EltStride; ++i) {
6693 // If V[i+EltStride] is undef and this is the first round of mixing,
6694 // then it is safe to just drop this shuffle: V[i] is already in the
6695 // right place, the one element (since it's the first round) being
6696 // inserted as undef can be dropped. This isn't safe for successive
6697 // rounds because they will permute elements within both vectors.
6698 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6699 EltStride == NumElems/2)
6702 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6711 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6712 // to create 256-bit vectors from two other 128-bit ones.
6713 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6715 MVT ResVT = Op.getSimpleValueType();
6717 assert((ResVT.is256BitVector() ||
6718 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6720 SDValue V1 = Op.getOperand(0);
6721 SDValue V2 = Op.getOperand(1);
6722 unsigned NumElems = ResVT.getVectorNumElements();
6723 if(ResVT.is256BitVector())
6724 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6726 if (Op.getNumOperands() == 4) {
6727 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6728 ResVT.getVectorNumElements()/2);
6729 SDValue V3 = Op.getOperand(2);
6730 SDValue V4 = Op.getOperand(3);
6731 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6732 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6734 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6737 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6738 MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6739 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6740 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6741 Op.getNumOperands() == 4)));
6743 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6744 // from two other 128-bit ones.
6746 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6747 return LowerAVXCONCAT_VECTORS(Op, DAG);
6750 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
6751 bool hasInt256, unsigned *MaskOut = nullptr) {
6752 MVT EltVT = VT.getVectorElementType();
6754 // There is no blend with immediate in AVX-512.
6755 if (VT.is512BitVector())
6758 if (!hasSSE41 || EltVT == MVT::i8)
6760 if (!hasInt256 && VT == MVT::v16i16)
6763 unsigned MaskValue = 0;
6764 unsigned NumElems = VT.getVectorNumElements();
6765 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6766 unsigned NumLanes = (NumElems - 1) / 8 + 1;
6767 unsigned NumElemsInLane = NumElems / NumLanes;
6769 // Blend for v16i16 should be symetric for the both lanes.
6770 for (unsigned i = 0; i < NumElemsInLane; ++i) {
6772 int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
6773 int EltIdx = MaskVals[i];
6775 if ((EltIdx < 0 || EltIdx == (int)i) &&
6776 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6779 if (((unsigned)EltIdx == (i + NumElems)) &&
6780 (SndLaneEltIdx < 0 ||
6781 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6782 MaskValue |= (1 << i);
6788 *MaskOut = MaskValue;
6792 // Try to lower a shuffle node into a simple blend instruction.
6793 // This function assumes isBlendMask returns true for this
6794 // SuffleVectorSDNode
6795 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6797 const X86Subtarget *Subtarget,
6798 SelectionDAG &DAG) {
6799 MVT VT = SVOp->getSimpleValueType(0);
6800 MVT EltVT = VT.getVectorElementType();
6801 assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
6802 Subtarget->hasInt256() && "Trying to lower a "
6803 "VECTOR_SHUFFLE to a Blend but "
6804 "with the wrong mask"));
6805 SDValue V1 = SVOp->getOperand(0);
6806 SDValue V2 = SVOp->getOperand(1);
6808 unsigned NumElems = VT.getVectorNumElements();
6810 // Convert i32 vectors to floating point if it is not AVX2.
6811 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6813 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6814 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6816 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6817 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6820 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6821 DAG.getConstant(MaskValue, MVT::i32));
6822 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6825 /// In vector type \p VT, return true if the element at index \p InputIdx
6826 /// falls on a different 128-bit lane than \p OutputIdx.
6827 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
6828 unsigned OutputIdx) {
6829 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6830 return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
6833 /// Generate a PSHUFB if possible. Selects elements from \p V1 according to
6834 /// \p MaskVals. MaskVals[OutputIdx] = InputIdx specifies that we want to
6835 /// shuffle the element at InputIdx in V1 to OutputIdx in the result. If \p
6836 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
6838 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
6839 SelectionDAG &DAG) {
6840 MVT VT = V1.getSimpleValueType();
6841 assert(VT.is128BitVector() || VT.is256BitVector());
6843 MVT EltVT = VT.getVectorElementType();
6844 unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
6845 unsigned NumElts = VT.getVectorNumElements();
6847 SmallVector<SDValue, 32> PshufbMask;
6848 for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
6849 int InputIdx = MaskVals[OutputIdx];
6850 unsigned InputByteIdx;
6852 if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
6853 InputByteIdx = 0x80;
6855 // Cross lane is not allowed.
6856 if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
6858 InputByteIdx = InputIdx * EltSizeInBytes;
6859 // Index is an byte offset within the 128-bit lane.
6860 InputByteIdx &= 0xf;
6863 for (unsigned j = 0; j < EltSizeInBytes; ++j) {
6864 PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
6865 if (InputByteIdx != 0x80)
6870 MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
6872 V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
6873 return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
6874 DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
6877 // v8i16 shuffles - Prefer shuffles in the following order:
6878 // 1. [all] pshuflw, pshufhw, optional move
6879 // 2. [ssse3] 1 x pshufb
6880 // 3. [ssse3] 2 x pshufb + 1 x por
6881 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6883 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6884 SelectionDAG &DAG) {
6885 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6886 SDValue V1 = SVOp->getOperand(0);
6887 SDValue V2 = SVOp->getOperand(1);
6889 SmallVector<int, 8> MaskVals;
6891 // Determine if more than 1 of the words in each of the low and high quadwords
6892 // of the result come from the same quadword of one of the two inputs. Undef
6893 // mask values count as coming from any quadword, for better codegen.
6895 // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
6896 // feeds this quad. For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
6897 unsigned LoQuad[] = { 0, 0, 0, 0 };
6898 unsigned HiQuad[] = { 0, 0, 0, 0 };
6899 // Indices of quads used.
6900 std::bitset<4> InputQuads;
6901 for (unsigned i = 0; i < 8; ++i) {
6902 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6903 int EltIdx = SVOp->getMaskElt(i);
6904 MaskVals.push_back(EltIdx);
6913 InputQuads.set(EltIdx / 4);
6916 int BestLoQuad = -1;
6917 unsigned MaxQuad = 1;
6918 for (unsigned i = 0; i < 4; ++i) {
6919 if (LoQuad[i] > MaxQuad) {
6921 MaxQuad = LoQuad[i];
6925 int BestHiQuad = -1;
6927 for (unsigned i = 0; i < 4; ++i) {
6928 if (HiQuad[i] > MaxQuad) {
6930 MaxQuad = HiQuad[i];
6934 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6935 // of the two input vectors, shuffle them into one input vector so only a
6936 // single pshufb instruction is necessary. If there are more than 2 input
6937 // quads, disable the next transformation since it does not help SSSE3.
6938 bool V1Used = InputQuads[0] || InputQuads[1];
6939 bool V2Used = InputQuads[2] || InputQuads[3];
6940 if (Subtarget->hasSSSE3()) {
6941 if (InputQuads.count() == 2 && V1Used && V2Used) {
6942 BestLoQuad = InputQuads[0] ? 0 : 1;
6943 BestHiQuad = InputQuads[2] ? 2 : 3;
6945 if (InputQuads.count() > 2) {
6951 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6952 // the shuffle mask. If a quad is scored as -1, that means that it contains
6953 // words from all 4 input quadwords.
6955 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6957 BestLoQuad < 0 ? 0 : BestLoQuad,
6958 BestHiQuad < 0 ? 1 : BestHiQuad
6960 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6961 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6962 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6963 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6965 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6966 // source words for the shuffle, to aid later transformations.
6967 bool AllWordsInNewV = true;
6968 bool InOrder[2] = { true, true };
6969 for (unsigned i = 0; i != 8; ++i) {
6970 int idx = MaskVals[i];
6972 InOrder[i/4] = false;
6973 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6975 AllWordsInNewV = false;
6979 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6980 if (AllWordsInNewV) {
6981 for (int i = 0; i != 8; ++i) {
6982 int idx = MaskVals[i];
6985 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6986 if ((idx != i) && idx < 4)
6988 if ((idx != i) && idx > 3)
6997 // If we've eliminated the use of V2, and the new mask is a pshuflw or
6998 // pshufhw, that's as cheap as it gets. Return the new shuffle.
6999 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
7000 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
7001 unsigned TargetMask = 0;
7002 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
7003 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
7004 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
7005 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
7006 getShufflePSHUFLWImmediate(SVOp);
7007 V1 = NewV.getOperand(0);
7008 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
7012 // Promote splats to a larger type which usually leads to more efficient code.
7013 // FIXME: Is this true if pshufb is available?
7014 if (SVOp->isSplat())
7015 return PromoteSplat(SVOp, DAG);
7017 // If we have SSSE3, and all words of the result are from 1 input vector,
7018 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
7019 // is present, fall back to case 4.
7020 if (Subtarget->hasSSSE3()) {
7021 SmallVector<SDValue,16> pshufbMask;
7023 // If we have elements from both input vectors, set the high bit of the
7024 // shuffle mask element to zero out elements that come from V2 in the V1
7025 // mask, and elements that come from V1 in the V2 mask, so that the two
7026 // results can be OR'd together.
7027 bool TwoInputs = V1Used && V2Used;
7028 V1 = getPSHUFB(MaskVals, V1, dl, DAG);
7030 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
7032 // Calculate the shuffle mask for the second input, shuffle it, and
7033 // OR it with the first shuffled input.
7034 CommuteVectorShuffleMask(MaskVals, 8);
7035 V2 = getPSHUFB(MaskVals, V2, dl, DAG);
7036 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
7037 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
7040 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
7041 // and update MaskVals with new element order.
7042 std::bitset<8> InOrder;
7043 if (BestLoQuad >= 0) {
7044 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
7045 for (int i = 0; i != 4; ++i) {
7046 int idx = MaskVals[i];
7049 } else if ((idx / 4) == BestLoQuad) {
7054 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
7057 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
7058 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
7059 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
7061 getShufflePSHUFLWImmediate(SVOp), DAG);
7065 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
7066 // and update MaskVals with the new element order.
7067 if (BestHiQuad >= 0) {
7068 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
7069 for (unsigned i = 4; i != 8; ++i) {
7070 int idx = MaskVals[i];
7073 } else if ((idx / 4) == BestHiQuad) {
7074 MaskV[i] = (idx & 3) + 4;
7078 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
7081 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
7082 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
7083 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
7085 getShufflePSHUFHWImmediate(SVOp), DAG);
7089 // In case BestHi & BestLo were both -1, which means each quadword has a word
7090 // from each of the four input quadwords, calculate the InOrder bitvector now
7091 // before falling through to the insert/extract cleanup.
7092 if (BestLoQuad == -1 && BestHiQuad == -1) {
7094 for (int i = 0; i != 8; ++i)
7095 if (MaskVals[i] < 0 || MaskVals[i] == i)
7099 // The other elements are put in the right place using pextrw and pinsrw.
7100 for (unsigned i = 0; i != 8; ++i) {
7103 int EltIdx = MaskVals[i];
7106 SDValue ExtOp = (EltIdx < 8) ?
7107 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
7108 DAG.getIntPtrConstant(EltIdx)) :
7109 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
7110 DAG.getIntPtrConstant(EltIdx - 8));
7111 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
7112 DAG.getIntPtrConstant(i));
7117 /// \brief v16i16 shuffles
7119 /// FIXME: We only support generation of a single pshufb currently. We can
7120 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
7121 /// well (e.g 2 x pshufb + 1 x por).
7123 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
7124 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7125 SDValue V1 = SVOp->getOperand(0);
7126 SDValue V2 = SVOp->getOperand(1);
7129 if (V2.getOpcode() != ISD::UNDEF)
7132 SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
7133 return getPSHUFB(MaskVals, V1, dl, DAG);
7136 // v16i8 shuffles - Prefer shuffles in the following order:
7137 // 1. [ssse3] 1 x pshufb
7138 // 2. [ssse3] 2 x pshufb + 1 x por
7139 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
7140 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
7141 const X86Subtarget* Subtarget,
7142 SelectionDAG &DAG) {
7143 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7144 SDValue V1 = SVOp->getOperand(0);
7145 SDValue V2 = SVOp->getOperand(1);
7147 ArrayRef<int> MaskVals = SVOp->getMask();
7149 // Promote splats to a larger type which usually leads to more efficient code.
7150 // FIXME: Is this true if pshufb is available?
7151 if (SVOp->isSplat())
7152 return PromoteSplat(SVOp, DAG);
7154 // If we have SSSE3, case 1 is generated when all result bytes come from
7155 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
7156 // present, fall back to case 3.
7158 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
7159 if (Subtarget->hasSSSE3()) {
7160 SmallVector<SDValue,16> pshufbMask;
7162 // If all result elements are from one input vector, then only translate
7163 // undef mask values to 0x80 (zero out result) in the pshufb mask.
7165 // Otherwise, we have elements from both input vectors, and must zero out
7166 // elements that come from V2 in the first mask, and V1 in the second mask
7167 // so that we can OR them together.
7168 for (unsigned i = 0; i != 16; ++i) {
7169 int EltIdx = MaskVals[i];
7170 if (EltIdx < 0 || EltIdx >= 16)
7172 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
7174 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
7175 DAG.getNode(ISD::BUILD_VECTOR, dl,
7176 MVT::v16i8, pshufbMask));
7178 // As PSHUFB will zero elements with negative indices, it's safe to ignore
7179 // the 2nd operand if it's undefined or zero.
7180 if (V2.getOpcode() == ISD::UNDEF ||
7181 ISD::isBuildVectorAllZeros(V2.getNode()))
7184 // Calculate the shuffle mask for the second input, shuffle it, and
7185 // OR it with the first shuffled input.
7187 for (unsigned i = 0; i != 16; ++i) {
7188 int EltIdx = MaskVals[i];
7189 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
7190 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
7192 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
7193 DAG.getNode(ISD::BUILD_VECTOR, dl,
7194 MVT::v16i8, pshufbMask));
7195 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
7198 // No SSSE3 - Calculate in place words and then fix all out of place words
7199 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
7200 // the 16 different words that comprise the two doublequadword input vectors.
7201 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
7202 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
7204 for (int i = 0; i != 8; ++i) {
7205 int Elt0 = MaskVals[i*2];
7206 int Elt1 = MaskVals[i*2+1];
7208 // This word of the result is all undef, skip it.
7209 if (Elt0 < 0 && Elt1 < 0)
7212 // This word of the result is already in the correct place, skip it.
7213 if ((Elt0 == i*2) && (Elt1 == i*2+1))
7216 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
7217 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
7220 // If Elt0 and Elt1 are defined, are consecutive, and can be load
7221 // using a single extract together, load it and store it.
7222 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
7223 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
7224 DAG.getIntPtrConstant(Elt1 / 2));
7225 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
7226 DAG.getIntPtrConstant(i));
7230 // If Elt1 is defined, extract it from the appropriate source. If the
7231 // source byte is not also odd, shift the extracted word left 8 bits
7232 // otherwise clear the bottom 8 bits if we need to do an or.
7234 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
7235 DAG.getIntPtrConstant(Elt1 / 2));
7236 if ((Elt1 & 1) == 0)
7237 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
7239 TLI.getShiftAmountTy(InsElt.getValueType())));
7241 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
7242 DAG.getConstant(0xFF00, MVT::i16));
7244 // If Elt0 is defined, extract it from the appropriate source. If the
7245 // source byte is not also even, shift the extracted word right 8 bits. If
7246 // Elt1 was also defined, OR the extracted values together before
7247 // inserting them in the result.
7249 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
7250 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
7251 if ((Elt0 & 1) != 0)
7252 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
7254 TLI.getShiftAmountTy(InsElt0.getValueType())));
7256 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
7257 DAG.getConstant(0x00FF, MVT::i16));
7258 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
7261 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
7262 DAG.getIntPtrConstant(i));
7264 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
7267 // v32i8 shuffles - Translate to VPSHUFB if possible.
7269 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
7270 const X86Subtarget *Subtarget,
7271 SelectionDAG &DAG) {
7272 MVT VT = SVOp->getSimpleValueType(0);
7273 SDValue V1 = SVOp->getOperand(0);
7274 SDValue V2 = SVOp->getOperand(1);
7276 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
7278 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7279 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
7280 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
7282 // VPSHUFB may be generated if
7283 // (1) one of input vector is undefined or zeroinitializer.
7284 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
7285 // And (2) the mask indexes don't cross the 128-bit lane.
7286 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
7287 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
7290 if (V1IsAllZero && !V2IsAllZero) {
7291 CommuteVectorShuffleMask(MaskVals, 32);
7294 return getPSHUFB(MaskVals, V1, dl, DAG);
7297 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
7298 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
7299 /// done when every pair / quad of shuffle mask elements point to elements in
7300 /// the right sequence. e.g.
7301 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
7303 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
7304 SelectionDAG &DAG) {
7305 MVT VT = SVOp->getSimpleValueType(0);
7307 unsigned NumElems = VT.getVectorNumElements();
7310 switch (VT.SimpleTy) {
7311 default: llvm_unreachable("Unexpected!");
7314 return SDValue(SVOp, 0);
7315 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
7316 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
7317 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
7318 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
7319 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
7320 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
7323 SmallVector<int, 8> MaskVec;
7324 for (unsigned i = 0; i != NumElems; i += Scale) {
7326 for (unsigned j = 0; j != Scale; ++j) {
7327 int EltIdx = SVOp->getMaskElt(i+j);
7331 StartIdx = (EltIdx / Scale);
7332 if (EltIdx != (int)(StartIdx*Scale + j))
7335 MaskVec.push_back(StartIdx);
7338 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
7339 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
7340 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
7343 /// getVZextMovL - Return a zero-extending vector move low node.
7345 static SDValue getVZextMovL(MVT VT, MVT OpVT,
7346 SDValue SrcOp, SelectionDAG &DAG,
7347 const X86Subtarget *Subtarget, SDLoc dl) {
7348 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
7349 LoadSDNode *LD = nullptr;
7350 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
7351 LD = dyn_cast<LoadSDNode>(SrcOp);
7353 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
7355 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
7356 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
7357 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
7358 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
7359 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
7361 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
7362 return DAG.getNode(ISD::BITCAST, dl, VT,
7363 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
7364 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7372 return DAG.getNode(ISD::BITCAST, dl, VT,
7373 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
7374 DAG.getNode(ISD::BITCAST, dl,
7378 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
7379 /// which could not be matched by any known target speficic shuffle
7381 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7383 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
7384 if (NewOp.getNode())
7387 MVT VT = SVOp->getSimpleValueType(0);
7389 unsigned NumElems = VT.getVectorNumElements();
7390 unsigned NumLaneElems = NumElems / 2;
7393 MVT EltVT = VT.getVectorElementType();
7394 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
7397 SmallVector<int, 16> Mask;
7398 for (unsigned l = 0; l < 2; ++l) {
7399 // Build a shuffle mask for the output, discovering on the fly which
7400 // input vectors to use as shuffle operands (recorded in InputUsed).
7401 // If building a suitable shuffle vector proves too hard, then bail
7402 // out with UseBuildVector set.
7403 bool UseBuildVector = false;
7404 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
7405 unsigned LaneStart = l * NumLaneElems;
7406 for (unsigned i = 0; i != NumLaneElems; ++i) {
7407 // The mask element. This indexes into the input.
7408 int Idx = SVOp->getMaskElt(i+LaneStart);
7410 // the mask element does not index into any input vector.
7415 // The input vector this mask element indexes into.
7416 int Input = Idx / NumLaneElems;
7418 // Turn the index into an offset from the start of the input vector.
7419 Idx -= Input * NumLaneElems;
7421 // Find or create a shuffle vector operand to hold this input.
7423 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
7424 if (InputUsed[OpNo] == Input)
7425 // This input vector is already an operand.
7427 if (InputUsed[OpNo] < 0) {
7428 // Create a new operand for this input vector.
7429 InputUsed[OpNo] = Input;
7434 if (OpNo >= array_lengthof(InputUsed)) {
7435 // More than two input vectors used! Give up on trying to create a
7436 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
7437 UseBuildVector = true;
7441 // Add the mask index for the new shuffle vector.
7442 Mask.push_back(Idx + OpNo * NumLaneElems);
7445 if (UseBuildVector) {
7446 SmallVector<SDValue, 16> SVOps;
7447 for (unsigned i = 0; i != NumLaneElems; ++i) {
7448 // The mask element. This indexes into the input.
7449 int Idx = SVOp->getMaskElt(i+LaneStart);
7451 SVOps.push_back(DAG.getUNDEF(EltVT));
7455 // The input vector this mask element indexes into.
7456 int Input = Idx / NumElems;
7458 // Turn the index into an offset from the start of the input vector.
7459 Idx -= Input * NumElems;
7461 // Extract the vector element by hand.
7462 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
7463 SVOp->getOperand(Input),
7464 DAG.getIntPtrConstant(Idx)));
7467 // Construct the output using a BUILD_VECTOR.
7468 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
7469 } else if (InputUsed[0] < 0) {
7470 // No input vectors were used! The result is undefined.
7471 Output[l] = DAG.getUNDEF(NVT);
7473 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
7474 (InputUsed[0] % 2) * NumLaneElems,
7476 // If only one input was used, use an undefined vector for the other.
7477 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
7478 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
7479 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
7480 // At least one input vector was used. Create a new shuffle vector.
7481 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
7487 // Concatenate the result back
7488 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
7491 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
7492 /// 4 elements, and match them with several different shuffle types.
7494 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7495 SDValue V1 = SVOp->getOperand(0);
7496 SDValue V2 = SVOp->getOperand(1);
7498 MVT VT = SVOp->getSimpleValueType(0);
7500 assert(VT.is128BitVector() && "Unsupported vector size");
7502 std::pair<int, int> Locs[4];
7503 int Mask1[] = { -1, -1, -1, -1 };
7504 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
7508 for (unsigned i = 0; i != 4; ++i) {
7509 int Idx = PermMask[i];
7511 Locs[i] = std::make_pair(-1, -1);
7513 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
7515 Locs[i] = std::make_pair(0, NumLo);
7519 Locs[i] = std::make_pair(1, NumHi);
7521 Mask1[2+NumHi] = Idx;
7527 if (NumLo <= 2 && NumHi <= 2) {
7528 // If no more than two elements come from either vector. This can be
7529 // implemented with two shuffles. First shuffle gather the elements.
7530 // The second shuffle, which takes the first shuffle as both of its
7531 // vector operands, put the elements into the right order.
7532 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7534 int Mask2[] = { -1, -1, -1, -1 };
7536 for (unsigned i = 0; i != 4; ++i)
7537 if (Locs[i].first != -1) {
7538 unsigned Idx = (i < 2) ? 0 : 4;
7539 Idx += Locs[i].first * 2 + Locs[i].second;
7543 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
7546 if (NumLo == 3 || NumHi == 3) {
7547 // Otherwise, we must have three elements from one vector, call it X, and
7548 // one element from the other, call it Y. First, use a shufps to build an
7549 // intermediate vector with the one element from Y and the element from X
7550 // that will be in the same half in the final destination (the indexes don't
7551 // matter). Then, use a shufps to build the final vector, taking the half
7552 // containing the element from Y from the intermediate, and the other half
7555 // Normalize it so the 3 elements come from V1.
7556 CommuteVectorShuffleMask(PermMask, 4);
7560 // Find the element from V2.
7562 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
7563 int Val = PermMask[HiIndex];
7570 Mask1[0] = PermMask[HiIndex];
7572 Mask1[2] = PermMask[HiIndex^1];
7574 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7577 Mask1[0] = PermMask[0];
7578 Mask1[1] = PermMask[1];
7579 Mask1[2] = HiIndex & 1 ? 6 : 4;
7580 Mask1[3] = HiIndex & 1 ? 4 : 6;
7581 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7584 Mask1[0] = HiIndex & 1 ? 2 : 0;
7585 Mask1[1] = HiIndex & 1 ? 0 : 2;
7586 Mask1[2] = PermMask[2];
7587 Mask1[3] = PermMask[3];
7592 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7595 // Break it into (shuffle shuffle_hi, shuffle_lo).
7596 int LoMask[] = { -1, -1, -1, -1 };
7597 int HiMask[] = { -1, -1, -1, -1 };
7599 int *MaskPtr = LoMask;
7600 unsigned MaskIdx = 0;
7603 for (unsigned i = 0; i != 4; ++i) {
7610 int Idx = PermMask[i];
7612 Locs[i] = std::make_pair(-1, -1);
7613 } else if (Idx < 4) {
7614 Locs[i] = std::make_pair(MaskIdx, LoIdx);
7615 MaskPtr[LoIdx] = Idx;
7618 Locs[i] = std::make_pair(MaskIdx, HiIdx);
7619 MaskPtr[HiIdx] = Idx;
7624 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7625 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7626 int MaskOps[] = { -1, -1, -1, -1 };
7627 for (unsigned i = 0; i != 4; ++i)
7628 if (Locs[i].first != -1)
7629 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7630 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7633 static bool MayFoldVectorLoad(SDValue V) {
7634 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7635 V = V.getOperand(0);
7637 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7638 V = V.getOperand(0);
7639 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7640 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7641 // BUILD_VECTOR (load), undef
7642 V = V.getOperand(0);
7644 return MayFoldLoad(V);
7648 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7649 MVT VT = Op.getSimpleValueType();
7651 // Canonizalize to v2f64.
7652 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7653 return DAG.getNode(ISD::BITCAST, dl, VT,
7654 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7659 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7661 SDValue V1 = Op.getOperand(0);
7662 SDValue V2 = Op.getOperand(1);
7663 MVT VT = Op.getSimpleValueType();
7665 assert(VT != MVT::v2i64 && "unsupported shuffle type");
7667 if (HasSSE2 && VT == MVT::v2f64)
7668 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7670 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7671 return DAG.getNode(ISD::BITCAST, dl, VT,
7672 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7673 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7674 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7678 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7679 SDValue V1 = Op.getOperand(0);
7680 SDValue V2 = Op.getOperand(1);
7681 MVT VT = Op.getSimpleValueType();
7683 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7684 "unsupported shuffle type");
7686 if (V2.getOpcode() == ISD::UNDEF)
7690 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7694 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7695 SDValue V1 = Op.getOperand(0);
7696 SDValue V2 = Op.getOperand(1);
7697 MVT VT = Op.getSimpleValueType();
7698 unsigned NumElems = VT.getVectorNumElements();
7700 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7701 // operand of these instructions is only memory, so check if there's a
7702 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7704 bool CanFoldLoad = false;
7706 // Trivial case, when V2 comes from a load.
7707 if (MayFoldVectorLoad(V2))
7710 // When V1 is a load, it can be folded later into a store in isel, example:
7711 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7713 // (MOVLPSmr addr:$src1, VR128:$src2)
7714 // So, recognize this potential and also use MOVLPS or MOVLPD
7715 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7718 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7720 if (HasSSE2 && NumElems == 2)
7721 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7724 // If we don't care about the second element, proceed to use movss.
7725 if (SVOp->getMaskElt(1) != -1)
7726 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7729 // movl and movlp will both match v2i64, but v2i64 is never matched by
7730 // movl earlier because we make it strict to avoid messing with the movlp load
7731 // folding logic (see the code above getMOVLP call). Match it here then,
7732 // this is horrible, but will stay like this until we move all shuffle
7733 // matching to x86 specific nodes. Note that for the 1st condition all
7734 // types are matched with movsd.
7736 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7737 // as to remove this logic from here, as much as possible
7738 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7739 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7740 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7743 assert(VT != MVT::v4i32 && "unsupported shuffle type");
7745 // Invert the operand order and use SHUFPS to match it.
7746 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7747 getShuffleSHUFImmediate(SVOp), DAG);
7750 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
7751 SelectionDAG &DAG) {
7753 MVT VT = Load->getSimpleValueType(0);
7754 MVT EVT = VT.getVectorElementType();
7755 SDValue Addr = Load->getOperand(1);
7756 SDValue NewAddr = DAG.getNode(
7757 ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
7758 DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
7761 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
7762 DAG.getMachineFunction().getMachineMemOperand(
7763 Load->getMemOperand(), 0, EVT.getStoreSize()));
7767 // It is only safe to call this function if isINSERTPSMask is true for
7768 // this shufflevector mask.
7769 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
7770 SelectionDAG &DAG) {
7771 // Generate an insertps instruction when inserting an f32 from memory onto a
7772 // v4f32 or when copying a member from one v4f32 to another.
7773 // We also use it for transferring i32 from one register to another,
7774 // since it simply copies the same bits.
7775 // If we're transferring an i32 from memory to a specific element in a
7776 // register, we output a generic DAG that will match the PINSRD
7778 MVT VT = SVOp->getSimpleValueType(0);
7779 MVT EVT = VT.getVectorElementType();
7780 SDValue V1 = SVOp->getOperand(0);
7781 SDValue V2 = SVOp->getOperand(1);
7782 auto Mask = SVOp->getMask();
7783 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
7784 "unsupported vector type for insertps/pinsrd");
7786 auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
7787 auto FromV2Predicate = [](const int &i) { return i >= 4; };
7788 int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
7796 DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
7799 assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
7800 "More than one element from V1 and from V2, or no elements from one "
7801 "of the vectors. This case should not have returned true from "
7806 std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
7809 unsigned SrcIndex = Mask[DestIndex] % 4;
7810 if (MayFoldLoad(From)) {
7811 // Trivial case, when From comes from a load and is only used by the
7812 // shuffle. Make it use insertps from the vector that we need from that
7815 NarrowVectorLoadToElement(cast<LoadSDNode>(From), SrcIndex, DAG);
7816 if (!NewLoad.getNode())
7819 if (EVT == MVT::f32) {
7820 // Create this as a scalar to vector to match the instruction pattern.
7821 SDValue LoadScalarToVector =
7822 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
7823 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
7824 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
7826 } else { // EVT == MVT::i32
7827 // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
7828 // instruction, to match the PINSRD instruction, which loads an i32 to a
7829 // certain vector element.
7830 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
7831 DAG.getConstant(DestIndex, MVT::i32));
7835 // Vector-element-to-vector
7836 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
7837 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
7840 // Reduce a vector shuffle to zext.
7841 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7842 SelectionDAG &DAG) {
7843 // PMOVZX is only available from SSE41.
7844 if (!Subtarget->hasSSE41())
7847 MVT VT = Op.getSimpleValueType();
7849 // Only AVX2 support 256-bit vector integer extending.
7850 if (!Subtarget->hasInt256() && VT.is256BitVector())
7853 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7855 SDValue V1 = Op.getOperand(0);
7856 SDValue V2 = Op.getOperand(1);
7857 unsigned NumElems = VT.getVectorNumElements();
7859 // Extending is an unary operation and the element type of the source vector
7860 // won't be equal to or larger than i64.
7861 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7862 VT.getVectorElementType() == MVT::i64)
7865 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7866 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7867 while ((1U << Shift) < NumElems) {
7868 if (SVOp->getMaskElt(1U << Shift) == 1)
7871 // The maximal ratio is 8, i.e. from i8 to i64.
7876 // Check the shuffle mask.
7877 unsigned Mask = (1U << Shift) - 1;
7878 for (unsigned i = 0; i != NumElems; ++i) {
7879 int EltIdx = SVOp->getMaskElt(i);
7880 if ((i & Mask) != 0 && EltIdx != -1)
7882 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7886 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7887 MVT NeVT = MVT::getIntegerVT(NBits);
7888 MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7890 if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7893 // Simplify the operand as it's prepared to be fed into shuffle.
7894 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7895 if (V1.getOpcode() == ISD::BITCAST &&
7896 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7897 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7898 V1.getOperand(0).getOperand(0)
7899 .getSimpleValueType().getSizeInBits() == SignificantBits) {
7900 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7901 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7902 ConstantSDNode *CIdx =
7903 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7904 // If it's foldable, i.e. normal load with single use, we will let code
7905 // selection to fold it. Otherwise, we will short the conversion sequence.
7906 if (CIdx && CIdx->getZExtValue() == 0 &&
7907 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7908 MVT FullVT = V.getSimpleValueType();
7909 MVT V1VT = V1.getSimpleValueType();
7910 if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7911 // The "ext_vec_elt" node is wider than the result node.
7912 // In this case we should extract subvector from V.
7913 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7914 unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7915 MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7916 FullVT.getVectorNumElements()/Ratio);
7917 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7918 DAG.getIntPtrConstant(0));
7920 V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7924 return DAG.getNode(ISD::BITCAST, DL, VT,
7925 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7928 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7929 SelectionDAG &DAG) {
7930 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7931 MVT VT = Op.getSimpleValueType();
7933 SDValue V1 = Op.getOperand(0);
7934 SDValue V2 = Op.getOperand(1);
7936 if (isZeroShuffle(SVOp))
7937 return getZeroVector(VT, Subtarget, DAG, dl);
7939 // Handle splat operations
7940 if (SVOp->isSplat()) {
7941 // Use vbroadcast whenever the splat comes from a foldable load
7942 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7943 if (Broadcast.getNode())
7947 // Check integer expanding shuffles.
7948 SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7949 if (NewOp.getNode())
7952 // If the shuffle can be profitably rewritten as a narrower shuffle, then
7954 if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
7956 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7957 if (NewOp.getNode())
7958 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7959 } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
7960 // FIXME: Figure out a cleaner way to do this.
7961 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7962 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7963 if (NewOp.getNode()) {
7964 MVT NewVT = NewOp.getSimpleValueType();
7965 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7966 NewVT, true, false))
7967 return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
7970 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7971 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7972 if (NewOp.getNode()) {
7973 MVT NewVT = NewOp.getSimpleValueType();
7974 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7975 return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
7984 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7985 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7986 SDValue V1 = Op.getOperand(0);
7987 SDValue V2 = Op.getOperand(1);
7988 MVT VT = Op.getSimpleValueType();
7990 unsigned NumElems = VT.getVectorNumElements();
7991 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7992 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7993 bool V1IsSplat = false;
7994 bool V2IsSplat = false;
7995 bool HasSSE2 = Subtarget->hasSSE2();
7996 bool HasFp256 = Subtarget->hasFp256();
7997 bool HasInt256 = Subtarget->hasInt256();
7998 MachineFunction &MF = DAG.getMachineFunction();
7999 bool OptForSize = MF.getFunction()->getAttributes().
8000 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
8002 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
8004 if (V1IsUndef && V2IsUndef)
8005 return DAG.getUNDEF(VT);
8007 // When we create a shuffle node we put the UNDEF node to second operand,
8008 // but in some cases the first operand may be transformed to UNDEF.
8009 // In this case we should just commute the node.
8011 return CommuteVectorShuffle(SVOp, DAG);
8013 // Vector shuffle lowering takes 3 steps:
8015 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
8016 // narrowing and commutation of operands should be handled.
8017 // 2) Matching of shuffles with known shuffle masks to x86 target specific
8019 // 3) Rewriting of unmatched masks into new generic shuffle operations,
8020 // so the shuffle can be broken into other shuffles and the legalizer can
8021 // try the lowering again.
8023 // The general idea is that no vector_shuffle operation should be left to
8024 // be matched during isel, all of them must be converted to a target specific
8027 // Normalize the input vectors. Here splats, zeroed vectors, profitable
8028 // narrowing and commutation of operands should be handled. The actual code
8029 // doesn't include all of those, work in progress...
8030 SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
8031 if (NewOp.getNode())
8034 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
8036 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
8037 // unpckh_undef). Only use pshufd if speed is more important than size.
8038 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
8039 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
8040 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
8041 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
8043 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
8044 V2IsUndef && MayFoldVectorLoad(V1))
8045 return getMOVDDup(Op, dl, V1, DAG);
8047 if (isMOVHLPS_v_undef_Mask(M, VT))
8048 return getMOVHighToLow(Op, dl, DAG);
8050 // Use to match splats
8051 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
8052 (VT == MVT::v2f64 || VT == MVT::v2i64))
8053 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
8055 if (isPSHUFDMask(M, VT)) {
8056 // The actual implementation will match the mask in the if above and then
8057 // during isel it can match several different instructions, not only pshufd
8058 // as its name says, sad but true, emulate the behavior for now...
8059 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
8060 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
8062 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
8064 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
8065 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
8067 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
8068 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
8071 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
8075 if (isPALIGNRMask(M, VT, Subtarget))
8076 return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
8077 getShufflePALIGNRImmediate(SVOp),
8080 // Check if this can be converted into a logical shift.
8081 bool isLeft = false;
8084 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
8085 if (isShift && ShVal.hasOneUse()) {
8086 // If the shifted value has multiple uses, it may be cheaper to use
8087 // v_set0 + movlhps or movhlps, etc.
8088 MVT EltVT = VT.getVectorElementType();
8089 ShAmt *= EltVT.getSizeInBits();
8090 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
8093 if (isMOVLMask(M, VT)) {
8094 if (ISD::isBuildVectorAllZeros(V1.getNode()))
8095 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
8096 if (!isMOVLPMask(M, VT)) {
8097 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
8098 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
8100 if (VT == MVT::v4i32 || VT == MVT::v4f32)
8101 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
8105 // FIXME: fold these into legal mask.
8106 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
8107 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
8109 if (isMOVHLPSMask(M, VT))
8110 return getMOVHighToLow(Op, dl, DAG);
8112 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
8113 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
8115 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
8116 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
8118 if (isMOVLPMask(M, VT))
8119 return getMOVLP(Op, dl, DAG, HasSSE2);
8121 if (ShouldXformToMOVHLPS(M, VT) ||
8122 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
8123 return CommuteVectorShuffle(SVOp, DAG);
8126 // No better options. Use a vshldq / vsrldq.
8127 MVT EltVT = VT.getVectorElementType();
8128 ShAmt *= EltVT.getSizeInBits();
8129 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
8132 bool Commuted = false;
8133 // FIXME: This should also accept a bitcast of a splat? Be careful, not
8134 // 1,1,1,1 -> v8i16 though.
8135 V1IsSplat = isSplatVector(V1.getNode());
8136 V2IsSplat = isSplatVector(V2.getNode());
8138 // Canonicalize the splat or undef, if present, to be on the RHS.
8139 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
8140 CommuteVectorShuffleMask(M, NumElems);
8142 std::swap(V1IsSplat, V2IsSplat);
8146 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
8147 // Shuffling low element of v1 into undef, just return v1.
8150 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
8151 // the instruction selector will not match, so get a canonical MOVL with
8152 // swapped operands to undo the commute.
8153 return getMOVL(DAG, dl, VT, V2, V1);
8156 if (isUNPCKLMask(M, VT, HasInt256))
8157 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
8159 if (isUNPCKHMask(M, VT, HasInt256))
8160 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
8163 // Normalize mask so all entries that point to V2 points to its first
8164 // element then try to match unpck{h|l} again. If match, return a
8165 // new vector_shuffle with the corrected mask.p
8166 SmallVector<int, 8> NewMask(M.begin(), M.end());
8167 NormalizeMask(NewMask, NumElems);
8168 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
8169 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
8170 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
8171 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
8175 // Commute is back and try unpck* again.
8176 // FIXME: this seems wrong.
8177 CommuteVectorShuffleMask(M, NumElems);
8179 std::swap(V1IsSplat, V2IsSplat);
8181 if (isUNPCKLMask(M, VT, HasInt256))
8182 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
8184 if (isUNPCKHMask(M, VT, HasInt256))
8185 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
8188 // Normalize the node to match x86 shuffle ops if needed
8189 if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
8190 return CommuteVectorShuffle(SVOp, DAG);
8192 // The checks below are all present in isShuffleMaskLegal, but they are
8193 // inlined here right now to enable us to directly emit target specific
8194 // nodes, and remove one by one until they don't return Op anymore.
8196 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
8197 SVOp->getSplatIndex() == 0 && V2IsUndef) {
8198 if (VT == MVT::v2f64 || VT == MVT::v2i64)
8199 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
8202 if (isPSHUFHWMask(M, VT, HasInt256))
8203 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
8204 getShufflePSHUFHWImmediate(SVOp),
8207 if (isPSHUFLWMask(M, VT, HasInt256))
8208 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
8209 getShufflePSHUFLWImmediate(SVOp),
8212 if (isSHUFPMask(M, VT))
8213 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
8214 getShuffleSHUFImmediate(SVOp), DAG);
8216 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
8217 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
8218 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
8219 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
8221 //===--------------------------------------------------------------------===//
8222 // Generate target specific nodes for 128 or 256-bit shuffles only
8223 // supported in the AVX instruction set.
8226 // Handle VMOVDDUPY permutations
8227 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
8228 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
8230 // Handle VPERMILPS/D* permutations
8231 if (isVPERMILPMask(M, VT)) {
8232 if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
8233 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
8234 getShuffleSHUFImmediate(SVOp), DAG);
8235 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
8236 getShuffleSHUFImmediate(SVOp), DAG);
8240 if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
8241 return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
8242 Idx*(NumElems/2), DAG, dl);
8244 // Handle VPERM2F128/VPERM2I128 permutations
8245 if (isVPERM2X128Mask(M, VT, HasFp256))
8246 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
8247 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
8250 if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
8252 return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
8254 if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
8255 return getINSERTPS(SVOp, dl, DAG);
8258 if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
8259 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
8261 if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
8262 VT.is512BitVector()) {
8263 MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
8264 MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
8265 SmallVector<SDValue, 16> permclMask;
8266 for (unsigned i = 0; i != NumElems; ++i) {
8267 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
8270 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
8272 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
8273 return DAG.getNode(X86ISD::VPERMV, dl, VT,
8274 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
8275 return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
8276 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
8279 //===--------------------------------------------------------------------===//
8280 // Since no target specific shuffle was selected for this generic one,
8281 // lower it into other known shuffles. FIXME: this isn't true yet, but
8282 // this is the plan.
8285 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
8286 if (VT == MVT::v8i16) {
8287 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
8288 if (NewOp.getNode())
8292 if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
8293 SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
8294 if (NewOp.getNode())
8298 if (VT == MVT::v16i8) {
8299 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
8300 if (NewOp.getNode())
8304 if (VT == MVT::v32i8) {
8305 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
8306 if (NewOp.getNode())
8310 // Handle all 128-bit wide vectors with 4 elements, and match them with
8311 // several different shuffle types.
8312 if (NumElems == 4 && VT.is128BitVector())
8313 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
8315 // Handle general 256-bit shuffles
8316 if (VT.is256BitVector())
8317 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
8322 // This function assumes its argument is a BUILD_VECTOR of constants or
8323 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
8325 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
8326 unsigned &MaskValue) {
8328 unsigned NumElems = BuildVector->getNumOperands();
8329 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
8330 unsigned NumLanes = (NumElems - 1) / 8 + 1;
8331 unsigned NumElemsInLane = NumElems / NumLanes;
8333 // Blend for v16i16 should be symetric for the both lanes.
8334 for (unsigned i = 0; i < NumElemsInLane; ++i) {
8335 SDValue EltCond = BuildVector->getOperand(i);
8336 SDValue SndLaneEltCond =
8337 (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
8339 int Lane1Cond = -1, Lane2Cond = -1;
8340 if (isa<ConstantSDNode>(EltCond))
8341 Lane1Cond = !isZero(EltCond);
8342 if (isa<ConstantSDNode>(SndLaneEltCond))
8343 Lane2Cond = !isZero(SndLaneEltCond);
8345 if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
8346 // Lane1Cond != 0, means we want the first argument.
8347 // Lane1Cond == 0, means we want the second argument.
8348 // The encoding of this argument is 0 for the first argument, 1
8349 // for the second. Therefore, invert the condition.
8350 MaskValue |= !Lane1Cond << i;
8351 else if (Lane1Cond < 0)
8352 MaskValue |= !Lane2Cond << i;
8359 // Try to lower a vselect node into a simple blend instruction.
8360 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
8361 SelectionDAG &DAG) {
8362 SDValue Cond = Op.getOperand(0);
8363 SDValue LHS = Op.getOperand(1);
8364 SDValue RHS = Op.getOperand(2);
8366 MVT VT = Op.getSimpleValueType();
8367 MVT EltVT = VT.getVectorElementType();
8368 unsigned NumElems = VT.getVectorNumElements();
8370 // There is no blend with immediate in AVX-512.
8371 if (VT.is512BitVector())
8374 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
8376 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
8379 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
8382 // Check the mask for BLEND and build the value.
8383 unsigned MaskValue = 0;
8384 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
8387 // Convert i32 vectors to floating point if it is not AVX2.
8388 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
8390 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
8391 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
8393 LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
8394 RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
8397 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
8398 DAG.getConstant(MaskValue, MVT::i32));
8399 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
8402 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
8403 SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
8404 if (BlendOp.getNode())
8407 // Some types for vselect were previously set to Expand, not Legal or
8408 // Custom. Return an empty SDValue so we fall-through to Expand, after
8409 // the Custom lowering phase.
8410 MVT VT = Op.getSimpleValueType();
8411 switch (VT.SimpleTy) {
8419 // We couldn't create a "Blend with immediate" node.
8420 // This node should still be legal, but we'll have to emit a blendv*
8425 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8426 MVT VT = Op.getSimpleValueType();
8429 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
8432 if (VT.getSizeInBits() == 8) {
8433 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
8434 Op.getOperand(0), Op.getOperand(1));
8435 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
8436 DAG.getValueType(VT));
8437 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8440 if (VT.getSizeInBits() == 16) {
8441 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8442 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
8444 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8445 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8446 DAG.getNode(ISD::BITCAST, dl,
8450 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
8451 Op.getOperand(0), Op.getOperand(1));
8452 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
8453 DAG.getValueType(VT));
8454 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8457 if (VT == MVT::f32) {
8458 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
8459 // the result back to FR32 register. It's only worth matching if the
8460 // result has a single use which is a store or a bitcast to i32. And in
8461 // the case of a store, it's not worth it if the index is a constant 0,
8462 // because a MOVSSmr can be used instead, which is smaller and faster.
8463 if (!Op.hasOneUse())
8465 SDNode *User = *Op.getNode()->use_begin();
8466 if ((User->getOpcode() != ISD::STORE ||
8467 (isa<ConstantSDNode>(Op.getOperand(1)) &&
8468 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
8469 (User->getOpcode() != ISD::BITCAST ||
8470 User->getValueType(0) != MVT::i32))
8472 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8473 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
8476 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
8479 if (VT == MVT::i32 || VT == MVT::i64) {
8480 // ExtractPS/pextrq works with constant index.
8481 if (isa<ConstantSDNode>(Op.getOperand(1)))
8487 /// Extract one bit from mask vector, like v16i1 or v8i1.
8488 /// AVX-512 feature.
8490 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
8491 SDValue Vec = Op.getOperand(0);
8493 MVT VecVT = Vec.getSimpleValueType();
8494 SDValue Idx = Op.getOperand(1);
8495 MVT EltVT = Op.getSimpleValueType();
8497 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
8499 // variable index can't be handled in mask registers,
8500 // extend vector to VR512
8501 if (!isa<ConstantSDNode>(Idx)) {
8502 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
8503 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
8504 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
8505 ExtVT.getVectorElementType(), Ext, Idx);
8506 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
8509 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8510 const TargetRegisterClass* rc = getRegClassFor(VecVT);
8511 unsigned MaxSift = rc->getSize()*8 - 1;
8512 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
8513 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8514 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
8515 DAG.getConstant(MaxSift, MVT::i8));
8516 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
8517 DAG.getIntPtrConstant(0));
8521 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
8522 SelectionDAG &DAG) const {
8524 SDValue Vec = Op.getOperand(0);
8525 MVT VecVT = Vec.getSimpleValueType();
8526 SDValue Idx = Op.getOperand(1);
8528 if (Op.getSimpleValueType() == MVT::i1)
8529 return ExtractBitFromMaskVector(Op, DAG);
8531 if (!isa<ConstantSDNode>(Idx)) {
8532 if (VecVT.is512BitVector() ||
8533 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
8534 VecVT.getVectorElementType().getSizeInBits() == 32)) {
8537 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
8538 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
8539 MaskEltVT.getSizeInBits());
8541 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
8542 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
8543 getZeroVector(MaskVT, Subtarget, DAG, dl),
8544 Idx, DAG.getConstant(0, getPointerTy()));
8545 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
8546 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
8547 Perm, DAG.getConstant(0, getPointerTy()));
8552 // If this is a 256-bit vector result, first extract the 128-bit vector and
8553 // then extract the element from the 128-bit vector.
8554 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
8556 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8557 // Get the 128-bit vector.
8558 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
8559 MVT EltVT = VecVT.getVectorElementType();
8561 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
8563 //if (IdxVal >= NumElems/2)
8564 // IdxVal -= NumElems/2;
8565 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
8566 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
8567 DAG.getConstant(IdxVal, MVT::i32));
8570 assert(VecVT.is128BitVector() && "Unexpected vector length");
8572 if (Subtarget->hasSSE41()) {
8573 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
8578 MVT VT = Op.getSimpleValueType();
8579 // TODO: handle v16i8.
8580 if (VT.getSizeInBits() == 16) {
8581 SDValue Vec = Op.getOperand(0);
8582 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8584 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8585 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8586 DAG.getNode(ISD::BITCAST, dl,
8589 // Transform it so it match pextrw which produces a 32-bit result.
8590 MVT EltVT = MVT::i32;
8591 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
8592 Op.getOperand(0), Op.getOperand(1));
8593 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
8594 DAG.getValueType(VT));
8595 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8598 if (VT.getSizeInBits() == 32) {
8599 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8603 // SHUFPS the element to the lowest double word, then movss.
8604 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
8605 MVT VVT = Op.getOperand(0).getSimpleValueType();
8606 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8607 DAG.getUNDEF(VVT), Mask);
8608 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8609 DAG.getIntPtrConstant(0));
8612 if (VT.getSizeInBits() == 64) {
8613 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
8614 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
8615 // to match extract_elt for f64.
8616 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8620 // UNPCKHPD the element to the lowest double word, then movsd.
8621 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
8622 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
8623 int Mask[2] = { 1, -1 };
8624 MVT VVT = Op.getOperand(0).getSimpleValueType();
8625 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8626 DAG.getUNDEF(VVT), Mask);
8627 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8628 DAG.getIntPtrConstant(0));
8634 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8635 MVT VT = Op.getSimpleValueType();
8636 MVT EltVT = VT.getVectorElementType();
8639 SDValue N0 = Op.getOperand(0);
8640 SDValue N1 = Op.getOperand(1);
8641 SDValue N2 = Op.getOperand(2);
8643 if (!VT.is128BitVector())
8646 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
8647 isa<ConstantSDNode>(N2)) {
8649 if (VT == MVT::v8i16)
8650 Opc = X86ISD::PINSRW;
8651 else if (VT == MVT::v16i8)
8652 Opc = X86ISD::PINSRB;
8654 Opc = X86ISD::PINSRB;
8656 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
8658 if (N1.getValueType() != MVT::i32)
8659 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8660 if (N2.getValueType() != MVT::i32)
8661 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8662 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
8665 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
8666 // Bits [7:6] of the constant are the source select. This will always be
8667 // zero here. The DAG Combiner may combine an extract_elt index into these
8668 // bits. For example (insert (extract, 3), 2) could be matched by putting
8669 // the '3' into bits [7:6] of X86ISD::INSERTPS.
8670 // Bits [5:4] of the constant are the destination select. This is the
8671 // value of the incoming immediate.
8672 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
8673 // combine either bitwise AND or insert of float 0.0 to set these bits.
8674 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
8675 // Create this as a scalar to vector..
8676 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
8677 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
8680 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
8681 // PINSR* works with constant index.
8687 /// Insert one bit to mask vector, like v16i1 or v8i1.
8688 /// AVX-512 feature.
8690 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
8692 SDValue Vec = Op.getOperand(0);
8693 SDValue Elt = Op.getOperand(1);
8694 SDValue Idx = Op.getOperand(2);
8695 MVT VecVT = Vec.getSimpleValueType();
8697 if (!isa<ConstantSDNode>(Idx)) {
8698 // Non constant index. Extend source and destination,
8699 // insert element and then truncate the result.
8700 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
8701 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
8702 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
8703 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
8704 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
8705 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
8708 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8709 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
8710 if (Vec.getOpcode() == ISD::UNDEF)
8711 return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8712 DAG.getConstant(IdxVal, MVT::i8));
8713 const TargetRegisterClass* rc = getRegClassFor(VecVT);
8714 unsigned MaxSift = rc->getSize()*8 - 1;
8715 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8716 DAG.getConstant(MaxSift, MVT::i8));
8717 EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
8718 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8719 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
8722 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
8723 MVT VT = Op.getSimpleValueType();
8724 MVT EltVT = VT.getVectorElementType();
8726 if (EltVT == MVT::i1)
8727 return InsertBitToMaskVector(Op, DAG);
8730 SDValue N0 = Op.getOperand(0);
8731 SDValue N1 = Op.getOperand(1);
8732 SDValue N2 = Op.getOperand(2);
8734 // If this is a 256-bit vector result, first extract the 128-bit vector,
8735 // insert the element into the extracted half and then place it back.
8736 if (VT.is256BitVector() || VT.is512BitVector()) {
8737 if (!isa<ConstantSDNode>(N2))
8740 // Get the desired 128-bit vector half.
8741 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
8742 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
8744 // Insert the element into the desired half.
8745 unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
8746 unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
8748 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
8749 DAG.getConstant(IdxIn128, MVT::i32));
8751 // Insert the changed part back to the 256-bit vector
8752 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
8755 if (Subtarget->hasSSE41())
8756 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
8758 if (EltVT == MVT::i8)
8761 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
8762 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
8763 // as its second argument.
8764 if (N1.getValueType() != MVT::i32)
8765 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8766 if (N2.getValueType() != MVT::i32)
8767 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8768 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
8773 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
8775 MVT OpVT = Op.getSimpleValueType();
8777 // If this is a 256-bit vector result, first insert into a 128-bit
8778 // vector and then insert into the 256-bit vector.
8779 if (!OpVT.is128BitVector()) {
8780 // Insert into a 128-bit vector.
8781 unsigned SizeFactor = OpVT.getSizeInBits()/128;
8782 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
8783 OpVT.getVectorNumElements() / SizeFactor);
8785 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
8787 // Insert the 128-bit vector.
8788 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
8791 if (OpVT == MVT::v1i64 &&
8792 Op.getOperand(0).getValueType() == MVT::i64)
8793 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
8795 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
8796 assert(OpVT.is128BitVector() && "Expected an SSE type!");
8797 return DAG.getNode(ISD::BITCAST, dl, OpVT,
8798 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
8801 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
8802 // a simple subregister reference or explicit instructions to grab
8803 // upper bits of a vector.
8804 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8805 SelectionDAG &DAG) {
8807 SDValue In = Op.getOperand(0);
8808 SDValue Idx = Op.getOperand(1);
8809 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8810 MVT ResVT = Op.getSimpleValueType();
8811 MVT InVT = In.getSimpleValueType();
8813 if (Subtarget->hasFp256()) {
8814 if (ResVT.is128BitVector() &&
8815 (InVT.is256BitVector() || InVT.is512BitVector()) &&
8816 isa<ConstantSDNode>(Idx)) {
8817 return Extract128BitVector(In, IdxVal, DAG, dl);
8819 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
8820 isa<ConstantSDNode>(Idx)) {
8821 return Extract256BitVector(In, IdxVal, DAG, dl);
8827 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
8828 // simple superregister reference or explicit instructions to insert
8829 // the upper bits of a vector.
8830 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8831 SelectionDAG &DAG) {
8832 if (Subtarget->hasFp256()) {
8833 SDLoc dl(Op.getNode());
8834 SDValue Vec = Op.getNode()->getOperand(0);
8835 SDValue SubVec = Op.getNode()->getOperand(1);
8836 SDValue Idx = Op.getNode()->getOperand(2);
8838 if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8839 Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8840 SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8841 isa<ConstantSDNode>(Idx)) {
8842 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8843 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8846 if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8847 SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8848 isa<ConstantSDNode>(Idx)) {
8849 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8850 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8856 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8857 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8858 // one of the above mentioned nodes. It has to be wrapped because otherwise
8859 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8860 // be used to form addressing mode. These wrapped nodes will be selected
8863 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8864 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8866 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8868 unsigned char OpFlag = 0;
8869 unsigned WrapperKind = X86ISD::Wrapper;
8870 CodeModel::Model M = DAG.getTarget().getCodeModel();
8872 if (Subtarget->isPICStyleRIPRel() &&
8873 (M == CodeModel::Small || M == CodeModel::Kernel))
8874 WrapperKind = X86ISD::WrapperRIP;
8875 else if (Subtarget->isPICStyleGOT())
8876 OpFlag = X86II::MO_GOTOFF;
8877 else if (Subtarget->isPICStyleStubPIC())
8878 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8880 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8882 CP->getOffset(), OpFlag);
8884 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8885 // With PIC, the address is actually $g + Offset.
8887 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8888 DAG.getNode(X86ISD::GlobalBaseReg,
8889 SDLoc(), getPointerTy()),
8896 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8897 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8899 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8901 unsigned char OpFlag = 0;
8902 unsigned WrapperKind = X86ISD::Wrapper;
8903 CodeModel::Model M = DAG.getTarget().getCodeModel();
8905 if (Subtarget->isPICStyleRIPRel() &&
8906 (M == CodeModel::Small || M == CodeModel::Kernel))
8907 WrapperKind = X86ISD::WrapperRIP;
8908 else if (Subtarget->isPICStyleGOT())
8909 OpFlag = X86II::MO_GOTOFF;
8910 else if (Subtarget->isPICStyleStubPIC())
8911 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8913 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8916 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8918 // With PIC, the address is actually $g + Offset.
8920 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8921 DAG.getNode(X86ISD::GlobalBaseReg,
8922 SDLoc(), getPointerTy()),
8929 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8930 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8932 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8934 unsigned char OpFlag = 0;
8935 unsigned WrapperKind = X86ISD::Wrapper;
8936 CodeModel::Model M = DAG.getTarget().getCodeModel();
8938 if (Subtarget->isPICStyleRIPRel() &&
8939 (M == CodeModel::Small || M == CodeModel::Kernel)) {
8940 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8941 OpFlag = X86II::MO_GOTPCREL;
8942 WrapperKind = X86ISD::WrapperRIP;
8943 } else if (Subtarget->isPICStyleGOT()) {
8944 OpFlag = X86II::MO_GOT;
8945 } else if (Subtarget->isPICStyleStubPIC()) {
8946 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8947 } else if (Subtarget->isPICStyleStubNoDynamic()) {
8948 OpFlag = X86II::MO_DARWIN_NONLAZY;
8951 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8954 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8956 // With PIC, the address is actually $g + Offset.
8957 if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
8958 !Subtarget->is64Bit()) {
8959 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8960 DAG.getNode(X86ISD::GlobalBaseReg,
8961 SDLoc(), getPointerTy()),
8965 // For symbols that require a load from a stub to get the address, emit the
8967 if (isGlobalStubReference(OpFlag))
8968 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8969 MachinePointerInfo::getGOT(), false, false, false, 0);
8975 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8976 // Create the TargetBlockAddressAddress node.
8977 unsigned char OpFlags =
8978 Subtarget->ClassifyBlockAddressReference();
8979 CodeModel::Model M = DAG.getTarget().getCodeModel();
8980 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8981 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8983 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8986 if (Subtarget->isPICStyleRIPRel() &&
8987 (M == CodeModel::Small || M == CodeModel::Kernel))
8988 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8990 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8992 // With PIC, the address is actually $g + Offset.
8993 if (isGlobalRelativeToPICBase(OpFlags)) {
8994 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8995 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
9003 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
9004 int64_t Offset, SelectionDAG &DAG) const {
9005 // Create the TargetGlobalAddress node, folding in the constant
9006 // offset if it is legal.
9007 unsigned char OpFlags =
9008 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
9009 CodeModel::Model M = DAG.getTarget().getCodeModel();
9011 if (OpFlags == X86II::MO_NO_FLAG &&
9012 X86::isOffsetSuitableForCodeModel(Offset, M)) {
9013 // A direct static reference to a global.
9014 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
9017 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
9020 if (Subtarget->isPICStyleRIPRel() &&
9021 (M == CodeModel::Small || M == CodeModel::Kernel))
9022 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
9024 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
9026 // With PIC, the address is actually $g + Offset.
9027 if (isGlobalRelativeToPICBase(OpFlags)) {
9028 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
9029 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
9033 // For globals that require a load from a stub to get the address, emit the
9035 if (isGlobalStubReference(OpFlags))
9036 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
9037 MachinePointerInfo::getGOT(), false, false, false, 0);
9039 // If there was a non-zero offset that we didn't fold, create an explicit
9042 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
9043 DAG.getConstant(Offset, getPointerTy()));
9049 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
9050 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
9051 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
9052 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
9056 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
9057 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
9058 unsigned char OperandFlags, bool LocalDynamic = false) {
9059 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9060 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9062 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
9063 GA->getValueType(0),
9067 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
9071 SDValue Ops[] = { Chain, TGA, *InFlag };
9072 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
9074 SDValue Ops[] = { Chain, TGA };
9075 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
9078 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
9079 MFI->setAdjustsStack(true);
9081 SDValue Flag = Chain.getValue(1);
9082 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
9085 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
9087 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
9090 SDLoc dl(GA); // ? function entry point might be better
9091 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
9092 DAG.getNode(X86ISD::GlobalBaseReg,
9093 SDLoc(), PtrVT), InFlag);
9094 InFlag = Chain.getValue(1);
9096 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
9099 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
9101 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
9103 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
9104 X86::RAX, X86II::MO_TLSGD);
9107 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
9113 // Get the start address of the TLS block for this module.
9114 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
9115 .getInfo<X86MachineFunctionInfo>();
9116 MFI->incNumLocalDynamicTLSAccesses();
9120 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
9121 X86II::MO_TLSLD, /*LocalDynamic=*/true);
9124 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
9125 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
9126 InFlag = Chain.getValue(1);
9127 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
9128 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
9131 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
9135 unsigned char OperandFlags = X86II::MO_DTPOFF;
9136 unsigned WrapperKind = X86ISD::Wrapper;
9137 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
9138 GA->getValueType(0),
9139 GA->getOffset(), OperandFlags);
9140 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
9142 // Add x@dtpoff with the base.
9143 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
9146 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
9147 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
9148 const EVT PtrVT, TLSModel::Model model,
9149 bool is64Bit, bool isPIC) {
9152 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
9153 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
9154 is64Bit ? 257 : 256));
9156 SDValue ThreadPointer =
9157 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
9158 MachinePointerInfo(Ptr), false, false, false, 0);
9160 unsigned char OperandFlags = 0;
9161 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
9163 unsigned WrapperKind = X86ISD::Wrapper;
9164 if (model == TLSModel::LocalExec) {
9165 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
9166 } else if (model == TLSModel::InitialExec) {
9168 OperandFlags = X86II::MO_GOTTPOFF;
9169 WrapperKind = X86ISD::WrapperRIP;
9171 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
9174 llvm_unreachable("Unexpected model");
9177 // emit "addl x@ntpoff,%eax" (local exec)
9178 // or "addl x@indntpoff,%eax" (initial exec)
9179 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
9181 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
9182 GA->getOffset(), OperandFlags);
9183 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
9185 if (model == TLSModel::InitialExec) {
9186 if (isPIC && !is64Bit) {
9187 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
9188 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
9192 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
9193 MachinePointerInfo::getGOT(), false, false, false, 0);
9196 // The address of the thread local variable is the add of the thread
9197 // pointer with the offset of the variable.
9198 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
9202 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
9204 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
9205 const GlobalValue *GV = GA->getGlobal();
9207 if (Subtarget->isTargetELF()) {
9208 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
9211 case TLSModel::GeneralDynamic:
9212 if (Subtarget->is64Bit())
9213 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
9214 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
9215 case TLSModel::LocalDynamic:
9216 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
9217 Subtarget->is64Bit());
9218 case TLSModel::InitialExec:
9219 case TLSModel::LocalExec:
9220 return LowerToTLSExecModel(
9221 GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
9222 DAG.getTarget().getRelocationModel() == Reloc::PIC_);
9224 llvm_unreachable("Unknown TLS model.");
9227 if (Subtarget->isTargetDarwin()) {
9228 // Darwin only has one model of TLS. Lower to that.
9229 unsigned char OpFlag = 0;
9230 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
9231 X86ISD::WrapperRIP : X86ISD::Wrapper;
9233 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
9235 bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
9236 !Subtarget->is64Bit();
9238 OpFlag = X86II::MO_TLVP_PIC_BASE;
9240 OpFlag = X86II::MO_TLVP;
9242 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
9243 GA->getValueType(0),
9244 GA->getOffset(), OpFlag);
9245 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
9247 // With PIC32, the address is actually $g + Offset.
9249 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9250 DAG.getNode(X86ISD::GlobalBaseReg,
9251 SDLoc(), getPointerTy()),
9254 // Lowering the machine isd will make sure everything is in the right
9256 SDValue Chain = DAG.getEntryNode();
9257 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9258 SDValue Args[] = { Chain, Offset };
9259 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
9261 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
9262 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9263 MFI->setAdjustsStack(true);
9265 // And our return value (tls address) is in the standard call return value
9267 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
9268 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
9272 if (Subtarget->isTargetKnownWindowsMSVC() ||
9273 Subtarget->isTargetWindowsGNU()) {
9274 // Just use the implicit TLS architecture
9275 // Need to generate someting similar to:
9276 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
9278 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
9279 // mov rcx, qword [rdx+rcx*8]
9280 // mov eax, .tls$:tlsvar
9281 // [rax+rcx] contains the address
9282 // Windows 64bit: gs:0x58
9283 // Windows 32bit: fs:__tls_array
9286 SDValue Chain = DAG.getEntryNode();
9288 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
9289 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
9290 // use its literal value of 0x2C.
9291 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
9292 ? Type::getInt8PtrTy(*DAG.getContext(),
9294 : Type::getInt32PtrTy(*DAG.getContext(),
9298 Subtarget->is64Bit()
9299 ? DAG.getIntPtrConstant(0x58)
9300 : (Subtarget->isTargetWindowsGNU()
9301 ? DAG.getIntPtrConstant(0x2C)
9302 : DAG.getExternalSymbol("_tls_array", getPointerTy()));
9304 SDValue ThreadPointer =
9305 DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
9306 MachinePointerInfo(Ptr), false, false, false, 0);
9308 // Load the _tls_index variable
9309 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
9310 if (Subtarget->is64Bit())
9311 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
9312 IDX, MachinePointerInfo(), MVT::i32,
9315 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
9316 false, false, false, 0);
9318 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
9320 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
9322 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
9323 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
9324 false, false, false, 0);
9326 // Get the offset of start of .tls section
9327 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
9328 GA->getValueType(0),
9329 GA->getOffset(), X86II::MO_SECREL);
9330 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
9332 // The address of the thread local variable is the add of the thread
9333 // pointer with the offset of the variable.
9334 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
9337 llvm_unreachable("TLS not implemented for this target.");
9340 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
9341 /// and take a 2 x i32 value to shift plus a shift amount.
9342 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
9343 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
9344 MVT VT = Op.getSimpleValueType();
9345 unsigned VTBits = VT.getSizeInBits();
9347 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
9348 SDValue ShOpLo = Op.getOperand(0);
9349 SDValue ShOpHi = Op.getOperand(1);
9350 SDValue ShAmt = Op.getOperand(2);
9351 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
9352 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
9354 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
9355 DAG.getConstant(VTBits - 1, MVT::i8));
9356 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
9357 DAG.getConstant(VTBits - 1, MVT::i8))
9358 : DAG.getConstant(0, VT);
9361 if (Op.getOpcode() == ISD::SHL_PARTS) {
9362 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
9363 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
9365 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
9366 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
9369 // If the shift amount is larger or equal than the width of a part we can't
9370 // rely on the results of shld/shrd. Insert a test and select the appropriate
9371 // values for large shift amounts.
9372 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
9373 DAG.getConstant(VTBits, MVT::i8));
9374 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9375 AndNode, DAG.getConstant(0, MVT::i8));
9378 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9379 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
9380 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
9382 if (Op.getOpcode() == ISD::SHL_PARTS) {
9383 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
9384 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
9386 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
9387 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
9390 SDValue Ops[2] = { Lo, Hi };
9391 return DAG.getMergeValues(Ops, dl);
9394 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
9395 SelectionDAG &DAG) const {
9396 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
9398 if (SrcVT.isVector())
9401 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
9402 "Unknown SINT_TO_FP to lower!");
9404 // These are really Legal; return the operand so the caller accepts it as
9406 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
9408 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
9409 Subtarget->is64Bit()) {
9414 unsigned Size = SrcVT.getSizeInBits()/8;
9415 MachineFunction &MF = DAG.getMachineFunction();
9416 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
9417 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9418 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9420 MachinePointerInfo::getFixedStack(SSFI),
9422 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
9425 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
9427 SelectionDAG &DAG) const {
9431 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
9433 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
9435 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
9437 unsigned ByteSize = SrcVT.getSizeInBits()/8;
9439 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
9440 MachineMemOperand *MMO;
9442 int SSFI = FI->getIndex();
9444 DAG.getMachineFunction()
9445 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9446 MachineMemOperand::MOLoad, ByteSize, ByteSize);
9448 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
9449 StackSlot = StackSlot.getOperand(1);
9451 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
9452 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
9454 Tys, Ops, SrcVT, MMO);
9457 Chain = Result.getValue(1);
9458 SDValue InFlag = Result.getValue(2);
9460 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
9461 // shouldn't be necessary except that RFP cannot be live across
9462 // multiple blocks. When stackifier is fixed, they can be uncoupled.
9463 MachineFunction &MF = DAG.getMachineFunction();
9464 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
9465 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
9466 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9467 Tys = DAG.getVTList(MVT::Other);
9469 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
9471 MachineMemOperand *MMO =
9472 DAG.getMachineFunction()
9473 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9474 MachineMemOperand::MOStore, SSFISize, SSFISize);
9476 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
9477 Ops, Op.getValueType(), MMO);
9478 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
9479 MachinePointerInfo::getFixedStack(SSFI),
9480 false, false, false, 0);
9486 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
9487 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
9488 SelectionDAG &DAG) const {
9489 // This algorithm is not obvious. Here it is what we're trying to output:
9492 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
9493 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
9497 pshufd $0x4e, %xmm0, %xmm1
9503 LLVMContext *Context = DAG.getContext();
9505 // Build some magic constants.
9506 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
9507 Constant *C0 = ConstantDataVector::get(*Context, CV0);
9508 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
9510 SmallVector<Constant*,2> CV1;
9512 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9513 APInt(64, 0x4330000000000000ULL))));
9515 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9516 APInt(64, 0x4530000000000000ULL))));
9517 Constant *C1 = ConstantVector::get(CV1);
9518 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
9520 // Load the 64-bit value into an XMM register.
9521 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
9523 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
9524 MachinePointerInfo::getConstantPool(),
9525 false, false, false, 16);
9526 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
9527 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
9530 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
9531 MachinePointerInfo::getConstantPool(),
9532 false, false, false, 16);
9533 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
9534 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
9537 if (Subtarget->hasSSE3()) {
9538 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
9539 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
9541 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
9542 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
9544 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
9545 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
9549 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
9550 DAG.getIntPtrConstant(0));
9553 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
9554 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
9555 SelectionDAG &DAG) const {
9557 // FP constant to bias correct the final result.
9558 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
9561 // Load the 32-bit value into an XMM register.
9562 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
9565 // Zero out the upper parts of the register.
9566 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
9568 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9569 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
9570 DAG.getIntPtrConstant(0));
9572 // Or the load with the bias.
9573 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
9574 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9575 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9577 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9578 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9579 MVT::v2f64, Bias)));
9580 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9581 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
9582 DAG.getIntPtrConstant(0));
9584 // Subtract the bias.
9585 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
9587 // Handle final rounding.
9588 EVT DestVT = Op.getValueType();
9590 if (DestVT.bitsLT(MVT::f64))
9591 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
9592 DAG.getIntPtrConstant(0));
9593 if (DestVT.bitsGT(MVT::f64))
9594 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
9596 // Handle final rounding.
9600 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
9601 SelectionDAG &DAG) const {
9602 SDValue N0 = Op.getOperand(0);
9603 MVT SVT = N0.getSimpleValueType();
9606 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
9607 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
9608 "Custom UINT_TO_FP is not supported!");
9610 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
9611 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
9612 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
9615 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
9616 SelectionDAG &DAG) const {
9617 SDValue N0 = Op.getOperand(0);
9620 if (Op.getValueType().isVector())
9621 return lowerUINT_TO_FP_vec(Op, DAG);
9623 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
9624 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
9625 // the optimization here.
9626 if (DAG.SignBitIsZero(N0))
9627 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
9629 MVT SrcVT = N0.getSimpleValueType();
9630 MVT DstVT = Op.getSimpleValueType();
9631 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
9632 return LowerUINT_TO_FP_i64(Op, DAG);
9633 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
9634 return LowerUINT_TO_FP_i32(Op, DAG);
9635 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
9638 // Make a 64-bit buffer, and use it to build an FILD.
9639 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
9640 if (SrcVT == MVT::i32) {
9641 SDValue WordOff = DAG.getConstant(4, getPointerTy());
9642 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
9643 getPointerTy(), StackSlot, WordOff);
9644 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9645 StackSlot, MachinePointerInfo(),
9647 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
9648 OffsetSlot, MachinePointerInfo(),
9650 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
9654 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
9655 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9656 StackSlot, MachinePointerInfo(),
9658 // For i64 source, we need to add the appropriate power of 2 if the input
9659 // was negative. This is the same as the optimization in
9660 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
9661 // we must be careful to do the computation in x87 extended precision, not
9662 // in SSE. (The generic code can't know it's OK to do this, or how to.)
9663 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
9664 MachineMemOperand *MMO =
9665 DAG.getMachineFunction()
9666 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9667 MachineMemOperand::MOLoad, 8, 8);
9669 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
9670 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
9671 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
9674 APInt FF(32, 0x5F800000ULL);
9676 // Check whether the sign bit is set.
9677 SDValue SignSet = DAG.getSetCC(dl,
9678 getSetCCResultType(*DAG.getContext(), MVT::i64),
9679 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
9682 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
9683 SDValue FudgePtr = DAG.getConstantPool(
9684 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
9687 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
9688 SDValue Zero = DAG.getIntPtrConstant(0);
9689 SDValue Four = DAG.getIntPtrConstant(4);
9690 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
9692 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
9694 // Load the value out, extending it from f32 to f80.
9695 // FIXME: Avoid the extend by constructing the right constant pool?
9696 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
9697 FudgePtr, MachinePointerInfo::getConstantPool(),
9698 MVT::f32, false, false, 4);
9699 // Extend everything to 80 bits to force it to be done on x87.
9700 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
9701 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
9704 std::pair<SDValue,SDValue>
9705 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
9706 bool IsSigned, bool IsReplace) const {
9709 EVT DstTy = Op.getValueType();
9711 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
9712 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
9716 assert(DstTy.getSimpleVT() <= MVT::i64 &&
9717 DstTy.getSimpleVT() >= MVT::i16 &&
9718 "Unknown FP_TO_INT to lower!");
9720 // These are really Legal.
9721 if (DstTy == MVT::i32 &&
9722 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9723 return std::make_pair(SDValue(), SDValue());
9724 if (Subtarget->is64Bit() &&
9725 DstTy == MVT::i64 &&
9726 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9727 return std::make_pair(SDValue(), SDValue());
9729 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
9730 // stack slot, or into the FTOL runtime function.
9731 MachineFunction &MF = DAG.getMachineFunction();
9732 unsigned MemSize = DstTy.getSizeInBits()/8;
9733 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9734 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9737 if (!IsSigned && isIntegerTypeFTOL(DstTy))
9738 Opc = X86ISD::WIN_FTOL;
9740 switch (DstTy.getSimpleVT().SimpleTy) {
9741 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
9742 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
9743 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
9744 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
9747 SDValue Chain = DAG.getEntryNode();
9748 SDValue Value = Op.getOperand(0);
9749 EVT TheVT = Op.getOperand(0).getValueType();
9750 // FIXME This causes a redundant load/store if the SSE-class value is already
9751 // in memory, such as if it is on the callstack.
9752 if (isScalarFPTypeInSSEReg(TheVT)) {
9753 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
9754 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
9755 MachinePointerInfo::getFixedStack(SSFI),
9757 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
9759 Chain, StackSlot, DAG.getValueType(TheVT)
9762 MachineMemOperand *MMO =
9763 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9764 MachineMemOperand::MOLoad, MemSize, MemSize);
9765 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
9766 Chain = Value.getValue(1);
9767 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9768 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9771 MachineMemOperand *MMO =
9772 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9773 MachineMemOperand::MOStore, MemSize, MemSize);
9775 if (Opc != X86ISD::WIN_FTOL) {
9776 // Build the FP_TO_INT*_IN_MEM
9777 SDValue Ops[] = { Chain, Value, StackSlot };
9778 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
9780 return std::make_pair(FIST, StackSlot);
9782 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
9783 DAG.getVTList(MVT::Other, MVT::Glue),
9785 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
9786 MVT::i32, ftol.getValue(1));
9787 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
9788 MVT::i32, eax.getValue(2));
9789 SDValue Ops[] = { eax, edx };
9790 SDValue pair = IsReplace
9791 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
9792 : DAG.getMergeValues(Ops, DL);
9793 return std::make_pair(pair, SDValue());
9797 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
9798 const X86Subtarget *Subtarget) {
9799 MVT VT = Op->getSimpleValueType(0);
9800 SDValue In = Op->getOperand(0);
9801 MVT InVT = In.getSimpleValueType();
9804 // Optimize vectors in AVX mode:
9807 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
9808 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
9809 // Concat upper and lower parts.
9812 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
9813 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
9814 // Concat upper and lower parts.
9817 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
9818 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
9819 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
9822 if (Subtarget->hasInt256())
9823 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
9825 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
9826 SDValue Undef = DAG.getUNDEF(InVT);
9827 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9828 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9829 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9831 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9832 VT.getVectorNumElements()/2);
9834 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9835 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9837 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9840 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9841 SelectionDAG &DAG) {
9842 MVT VT = Op->getSimpleValueType(0);
9843 SDValue In = Op->getOperand(0);
9844 MVT InVT = In.getSimpleValueType();
9846 unsigned int NumElts = VT.getVectorNumElements();
9847 if (NumElts != 8 && NumElts != 16)
9850 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9851 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9853 EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9854 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9855 // Now we have only mask extension
9856 assert(InVT.getVectorElementType() == MVT::i1);
9857 SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9858 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9859 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9860 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9861 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9862 MachinePointerInfo::getConstantPool(),
9863 false, false, false, Alignment);
9865 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9866 if (VT.is512BitVector())
9868 return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9871 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9872 SelectionDAG &DAG) {
9873 if (Subtarget->hasFp256()) {
9874 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9882 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9883 SelectionDAG &DAG) {
9885 MVT VT = Op.getSimpleValueType();
9886 SDValue In = Op.getOperand(0);
9887 MVT SVT = In.getSimpleValueType();
9889 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9890 return LowerZERO_EXTEND_AVX512(Op, DAG);
9892 if (Subtarget->hasFp256()) {
9893 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9898 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9899 VT.getVectorNumElements() != SVT.getVectorNumElements());
9903 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9905 MVT VT = Op.getSimpleValueType();
9906 SDValue In = Op.getOperand(0);
9907 MVT InVT = In.getSimpleValueType();
9909 if (VT == MVT::i1) {
9910 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9911 "Invalid scalar TRUNCATE operation");
9912 if (InVT == MVT::i32)
9914 if (InVT.getSizeInBits() == 64)
9915 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9916 else if (InVT.getSizeInBits() < 32)
9917 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9918 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
9920 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9921 "Invalid TRUNCATE operation");
9923 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9924 if (VT.getVectorElementType().getSizeInBits() >=8)
9925 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9927 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9928 unsigned NumElts = InVT.getVectorNumElements();
9929 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9930 if (InVT.getSizeInBits() < 512) {
9931 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9932 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9936 SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9937 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9938 SDValue CP = DAG.getConstantPool(C, getPointerTy());
9939 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9940 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9941 MachinePointerInfo::getConstantPool(),
9942 false, false, false, Alignment);
9943 SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9944 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9945 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9948 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9949 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9950 if (Subtarget->hasInt256()) {
9951 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9952 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9953 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9955 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9956 DAG.getIntPtrConstant(0));
9959 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9960 DAG.getIntPtrConstant(0));
9961 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9962 DAG.getIntPtrConstant(2));
9963 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9964 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9965 static const int ShufMask[] = {0, 2, 4, 6};
9966 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
9969 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9970 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9971 if (Subtarget->hasInt256()) {
9972 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9974 SmallVector<SDValue,32> pshufbMask;
9975 for (unsigned i = 0; i < 2; ++i) {
9976 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9977 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9978 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9979 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9980 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9981 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9982 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9983 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9984 for (unsigned j = 0; j < 8; ++j)
9985 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9987 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
9988 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9989 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9991 static const int ShufMask[] = {0, 2, -1, -1};
9992 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
9994 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9995 DAG.getIntPtrConstant(0));
9996 return DAG.getNode(ISD::BITCAST, DL, VT, In);
9999 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
10000 DAG.getIntPtrConstant(0));
10002 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
10003 DAG.getIntPtrConstant(4));
10005 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
10006 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
10008 // The PSHUFB mask:
10009 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
10010 -1, -1, -1, -1, -1, -1, -1, -1};
10012 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
10013 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
10014 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
10016 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
10017 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
10019 // The MOVLHPS Mask:
10020 static const int ShufMask2[] = {0, 1, 4, 5};
10021 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
10022 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
10025 // Handle truncation of V256 to V128 using shuffles.
10026 if (!VT.is128BitVector() || !InVT.is256BitVector())
10029 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
10031 unsigned NumElems = VT.getVectorNumElements();
10032 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
10034 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
10035 // Prepare truncation shuffle mask
10036 for (unsigned i = 0; i != NumElems; ++i)
10037 MaskVec[i] = i * 2;
10038 SDValue V = DAG.getVectorShuffle(NVT, DL,
10039 DAG.getNode(ISD::BITCAST, DL, NVT, In),
10040 DAG.getUNDEF(NVT), &MaskVec[0]);
10041 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
10042 DAG.getIntPtrConstant(0));
10045 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
10046 SelectionDAG &DAG) const {
10047 assert(!Op.getSimpleValueType().isVector());
10049 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
10050 /*IsSigned=*/ true, /*IsReplace=*/ false);
10051 SDValue FIST = Vals.first, StackSlot = Vals.second;
10052 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
10053 if (!FIST.getNode()) return Op;
10055 if (StackSlot.getNode())
10056 // Load the result.
10057 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
10058 FIST, StackSlot, MachinePointerInfo(),
10059 false, false, false, 0);
10061 // The node is the result.
10065 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
10066 SelectionDAG &DAG) const {
10067 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
10068 /*IsSigned=*/ false, /*IsReplace=*/ false);
10069 SDValue FIST = Vals.first, StackSlot = Vals.second;
10070 assert(FIST.getNode() && "Unexpected failure");
10072 if (StackSlot.getNode())
10073 // Load the result.
10074 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
10075 FIST, StackSlot, MachinePointerInfo(),
10076 false, false, false, 0);
10078 // The node is the result.
10082 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
10084 MVT VT = Op.getSimpleValueType();
10085 SDValue In = Op.getOperand(0);
10086 MVT SVT = In.getSimpleValueType();
10088 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
10090 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
10091 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
10092 In, DAG.getUNDEF(SVT)));
10095 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
10096 LLVMContext *Context = DAG.getContext();
10098 MVT VT = Op.getSimpleValueType();
10100 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
10101 if (VT.isVector()) {
10102 EltVT = VT.getVectorElementType();
10103 NumElts = VT.getVectorNumElements();
10106 if (EltVT == MVT::f64)
10107 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
10108 APInt(64, ~(1ULL << 63))));
10110 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
10111 APInt(32, ~(1U << 31))));
10112 C = ConstantVector::getSplat(NumElts, C);
10113 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10114 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
10115 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
10116 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10117 MachinePointerInfo::getConstantPool(),
10118 false, false, false, Alignment);
10119 if (VT.isVector()) {
10120 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
10121 return DAG.getNode(ISD::BITCAST, dl, VT,
10122 DAG.getNode(ISD::AND, dl, ANDVT,
10123 DAG.getNode(ISD::BITCAST, dl, ANDVT,
10125 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
10127 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
10130 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
10131 LLVMContext *Context = DAG.getContext();
10133 MVT VT = Op.getSimpleValueType();
10135 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
10136 if (VT.isVector()) {
10137 EltVT = VT.getVectorElementType();
10138 NumElts = VT.getVectorNumElements();
10141 if (EltVT == MVT::f64)
10142 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
10143 APInt(64, 1ULL << 63)));
10145 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
10146 APInt(32, 1U << 31)));
10147 C = ConstantVector::getSplat(NumElts, C);
10148 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10149 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
10150 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
10151 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10152 MachinePointerInfo::getConstantPool(),
10153 false, false, false, Alignment);
10154 if (VT.isVector()) {
10155 MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
10156 return DAG.getNode(ISD::BITCAST, dl, VT,
10157 DAG.getNode(ISD::XOR, dl, XORVT,
10158 DAG.getNode(ISD::BITCAST, dl, XORVT,
10160 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
10163 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
10166 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
10167 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10168 LLVMContext *Context = DAG.getContext();
10169 SDValue Op0 = Op.getOperand(0);
10170 SDValue Op1 = Op.getOperand(1);
10172 MVT VT = Op.getSimpleValueType();
10173 MVT SrcVT = Op1.getSimpleValueType();
10175 // If second operand is smaller, extend it first.
10176 if (SrcVT.bitsLT(VT)) {
10177 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
10180 // And if it is bigger, shrink it first.
10181 if (SrcVT.bitsGT(VT)) {
10182 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
10186 // At this point the operands and the result should have the same
10187 // type, and that won't be f80 since that is not custom lowered.
10189 // First get the sign bit of second operand.
10190 SmallVector<Constant*,4> CV;
10191 if (SrcVT == MVT::f64) {
10192 const fltSemantics &Sem = APFloat::IEEEdouble;
10193 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
10194 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
10196 const fltSemantics &Sem = APFloat::IEEEsingle;
10197 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
10198 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10199 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10200 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10202 Constant *C = ConstantVector::get(CV);
10203 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
10204 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
10205 MachinePointerInfo::getConstantPool(),
10206 false, false, false, 16);
10207 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
10209 // Shift sign bit right or left if the two operands have different types.
10210 if (SrcVT.bitsGT(VT)) {
10211 // Op0 is MVT::f32, Op1 is MVT::f64.
10212 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
10213 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
10214 DAG.getConstant(32, MVT::i32));
10215 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
10216 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
10217 DAG.getIntPtrConstant(0));
10220 // Clear first operand sign bit.
10222 if (VT == MVT::f64) {
10223 const fltSemantics &Sem = APFloat::IEEEdouble;
10224 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
10225 APInt(64, ~(1ULL << 63)))));
10226 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
10228 const fltSemantics &Sem = APFloat::IEEEsingle;
10229 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
10230 APInt(32, ~(1U << 31)))));
10231 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10232 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10233 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10235 C = ConstantVector::get(CV);
10236 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
10237 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10238 MachinePointerInfo::getConstantPool(),
10239 false, false, false, 16);
10240 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
10242 // Or the value with the sign bit.
10243 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
10246 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
10247 SDValue N0 = Op.getOperand(0);
10249 MVT VT = Op.getSimpleValueType();
10251 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
10252 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
10253 DAG.getConstant(1, VT));
10254 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
10257 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
10259 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
10260 SelectionDAG &DAG) {
10261 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
10263 if (!Subtarget->hasSSE41())
10266 if (!Op->hasOneUse())
10269 SDNode *N = Op.getNode();
10272 SmallVector<SDValue, 8> Opnds;
10273 DenseMap<SDValue, unsigned> VecInMap;
10274 SmallVector<SDValue, 8> VecIns;
10275 EVT VT = MVT::Other;
10277 // Recognize a special case where a vector is casted into wide integer to
10279 Opnds.push_back(N->getOperand(0));
10280 Opnds.push_back(N->getOperand(1));
10282 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
10283 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
10284 // BFS traverse all OR'd operands.
10285 if (I->getOpcode() == ISD::OR) {
10286 Opnds.push_back(I->getOperand(0));
10287 Opnds.push_back(I->getOperand(1));
10288 // Re-evaluate the number of nodes to be traversed.
10289 e += 2; // 2 more nodes (LHS and RHS) are pushed.
10293 // Quit if a non-EXTRACT_VECTOR_ELT
10294 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10297 // Quit if without a constant index.
10298 SDValue Idx = I->getOperand(1);
10299 if (!isa<ConstantSDNode>(Idx))
10302 SDValue ExtractedFromVec = I->getOperand(0);
10303 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
10304 if (M == VecInMap.end()) {
10305 VT = ExtractedFromVec.getValueType();
10306 // Quit if not 128/256-bit vector.
10307 if (!VT.is128BitVector() && !VT.is256BitVector())
10309 // Quit if not the same type.
10310 if (VecInMap.begin() != VecInMap.end() &&
10311 VT != VecInMap.begin()->first.getValueType())
10313 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
10314 VecIns.push_back(ExtractedFromVec);
10316 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
10319 assert((VT.is128BitVector() || VT.is256BitVector()) &&
10320 "Not extracted from 128-/256-bit vector.");
10322 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
10324 for (DenseMap<SDValue, unsigned>::const_iterator
10325 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
10326 // Quit if not all elements are used.
10327 if (I->second != FullMask)
10331 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
10333 // Cast all vectors into TestVT for PTEST.
10334 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
10335 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
10337 // If more than one full vectors are evaluated, OR them first before PTEST.
10338 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
10339 // Each iteration will OR 2 nodes and append the result until there is only
10340 // 1 node left, i.e. the final OR'd value of all vectors.
10341 SDValue LHS = VecIns[Slot];
10342 SDValue RHS = VecIns[Slot + 1];
10343 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
10346 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
10347 VecIns.back(), VecIns.back());
10350 /// \brief return true if \c Op has a use that doesn't just read flags.
10351 static bool hasNonFlagsUse(SDValue Op) {
10352 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
10354 SDNode *User = *UI;
10355 unsigned UOpNo = UI.getOperandNo();
10356 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
10357 // Look pass truncate.
10358 UOpNo = User->use_begin().getOperandNo();
10359 User = *User->use_begin();
10362 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
10363 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
10369 /// Emit nodes that will be selected as "test Op0,Op0", or something
10371 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
10372 SelectionDAG &DAG) const {
10373 if (Op.getValueType() == MVT::i1)
10374 // KORTEST instruction should be selected
10375 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10376 DAG.getConstant(0, Op.getValueType()));
10378 // CF and OF aren't always set the way we want. Determine which
10379 // of these we need.
10380 bool NeedCF = false;
10381 bool NeedOF = false;
10384 case X86::COND_A: case X86::COND_AE:
10385 case X86::COND_B: case X86::COND_BE:
10388 case X86::COND_G: case X86::COND_GE:
10389 case X86::COND_L: case X86::COND_LE:
10390 case X86::COND_O: case X86::COND_NO: {
10391 // Check if we really need to set the
10392 // Overflow flag. If NoSignedWrap is present
10393 // that is not actually needed.
10394 switch (Op->getOpcode()) {
10399 const BinaryWithFlagsSDNode *BinNode =
10400 cast<BinaryWithFlagsSDNode>(Op.getNode());
10401 if (BinNode->hasNoSignedWrap())
10411 // See if we can use the EFLAGS value from the operand instead of
10412 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
10413 // we prove that the arithmetic won't overflow, we can't use OF or CF.
10414 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
10415 // Emit a CMP with 0, which is the TEST pattern.
10416 //if (Op.getValueType() == MVT::i1)
10417 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
10418 // DAG.getConstant(0, MVT::i1));
10419 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10420 DAG.getConstant(0, Op.getValueType()));
10422 unsigned Opcode = 0;
10423 unsigned NumOperands = 0;
10425 // Truncate operations may prevent the merge of the SETCC instruction
10426 // and the arithmetic instruction before it. Attempt to truncate the operands
10427 // of the arithmetic instruction and use a reduced bit-width instruction.
10428 bool NeedTruncation = false;
10429 SDValue ArithOp = Op;
10430 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
10431 SDValue Arith = Op->getOperand(0);
10432 // Both the trunc and the arithmetic op need to have one user each.
10433 if (Arith->hasOneUse())
10434 switch (Arith.getOpcode()) {
10441 NeedTruncation = true;
10447 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
10448 // which may be the result of a CAST. We use the variable 'Op', which is the
10449 // non-casted variable when we check for possible users.
10450 switch (ArithOp.getOpcode()) {
10452 // Due to an isel shortcoming, be conservative if this add is likely to be
10453 // selected as part of a load-modify-store instruction. When the root node
10454 // in a match is a store, isel doesn't know how to remap non-chain non-flag
10455 // uses of other nodes in the match, such as the ADD in this case. This
10456 // leads to the ADD being left around and reselected, with the result being
10457 // two adds in the output. Alas, even if none our users are stores, that
10458 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
10459 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
10460 // climbing the DAG back to the root, and it doesn't seem to be worth the
10462 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
10463 UE = Op.getNode()->use_end(); UI != UE; ++UI)
10464 if (UI->getOpcode() != ISD::CopyToReg &&
10465 UI->getOpcode() != ISD::SETCC &&
10466 UI->getOpcode() != ISD::STORE)
10469 if (ConstantSDNode *C =
10470 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
10471 // An add of one will be selected as an INC.
10472 if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
10473 Opcode = X86ISD::INC;
10478 // An add of negative one (subtract of one) will be selected as a DEC.
10479 if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
10480 Opcode = X86ISD::DEC;
10486 // Otherwise use a regular EFLAGS-setting add.
10487 Opcode = X86ISD::ADD;
10492 // If we have a constant logical shift that's only used in a comparison
10493 // against zero turn it into an equivalent AND. This allows turning it into
10494 // a TEST instruction later.
10495 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
10496 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
10497 EVT VT = Op.getValueType();
10498 unsigned BitWidth = VT.getSizeInBits();
10499 unsigned ShAmt = Op->getConstantOperandVal(1);
10500 if (ShAmt >= BitWidth) // Avoid undefined shifts.
10502 APInt Mask = ArithOp.getOpcode() == ISD::SRL
10503 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
10504 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
10505 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
10507 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
10508 DAG.getConstant(Mask, VT));
10509 DAG.ReplaceAllUsesWith(Op, New);
10515 // If the primary and result isn't used, don't bother using X86ISD::AND,
10516 // because a TEST instruction will be better.
10517 if (!hasNonFlagsUse(Op))
10523 // Due to the ISEL shortcoming noted above, be conservative if this op is
10524 // likely to be selected as part of a load-modify-store instruction.
10525 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
10526 UE = Op.getNode()->use_end(); UI != UE; ++UI)
10527 if (UI->getOpcode() == ISD::STORE)
10530 // Otherwise use a regular EFLAGS-setting instruction.
10531 switch (ArithOp.getOpcode()) {
10532 default: llvm_unreachable("unexpected operator!");
10533 case ISD::SUB: Opcode = X86ISD::SUB; break;
10534 case ISD::XOR: Opcode = X86ISD::XOR; break;
10535 case ISD::AND: Opcode = X86ISD::AND; break;
10537 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
10538 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
10539 if (EFLAGS.getNode())
10542 Opcode = X86ISD::OR;
10556 return SDValue(Op.getNode(), 1);
10562 // If we found that truncation is beneficial, perform the truncation and
10564 if (NeedTruncation) {
10565 EVT VT = Op.getValueType();
10566 SDValue WideVal = Op->getOperand(0);
10567 EVT WideVT = WideVal.getValueType();
10568 unsigned ConvertedOp = 0;
10569 // Use a target machine opcode to prevent further DAGCombine
10570 // optimizations that may separate the arithmetic operations
10571 // from the setcc node.
10572 switch (WideVal.getOpcode()) {
10574 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
10575 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
10576 case ISD::AND: ConvertedOp = X86ISD::AND; break;
10577 case ISD::OR: ConvertedOp = X86ISD::OR; break;
10578 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
10582 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10583 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
10584 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
10585 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
10586 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
10592 // Emit a CMP with 0, which is the TEST pattern.
10593 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10594 DAG.getConstant(0, Op.getValueType()));
10596 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10597 SmallVector<SDValue, 4> Ops;
10598 for (unsigned i = 0; i != NumOperands; ++i)
10599 Ops.push_back(Op.getOperand(i));
10601 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
10602 DAG.ReplaceAllUsesWith(Op, New);
10603 return SDValue(New.getNode(), 1);
10606 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
10608 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
10609 SDLoc dl, SelectionDAG &DAG) const {
10610 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
10611 if (C->getAPIntValue() == 0)
10612 return EmitTest(Op0, X86CC, dl, DAG);
10614 if (Op0.getValueType() == MVT::i1)
10615 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
10618 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
10619 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
10620 // Do the comparison at i32 if it's smaller, besides the Atom case.
10621 // This avoids subregister aliasing issues. Keep the smaller reference
10622 // if we're optimizing for size, however, as that'll allow better folding
10623 // of memory operations.
10624 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
10625 !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
10626 AttributeSet::FunctionIndex, Attribute::MinSize) &&
10627 !Subtarget->isAtom()) {
10628 unsigned ExtendOp =
10629 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
10630 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
10631 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
10633 // Use SUB instead of CMP to enable CSE between SUB and CMP.
10634 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
10635 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
10637 return SDValue(Sub.getNode(), 1);
10639 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
10642 /// Convert a comparison if required by the subtarget.
10643 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
10644 SelectionDAG &DAG) const {
10645 // If the subtarget does not support the FUCOMI instruction, floating-point
10646 // comparisons have to be converted.
10647 if (Subtarget->hasCMov() ||
10648 Cmp.getOpcode() != X86ISD::CMP ||
10649 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
10650 !Cmp.getOperand(1).getValueType().isFloatingPoint())
10653 // The instruction selector will select an FUCOM instruction instead of
10654 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
10655 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
10656 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
10658 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
10659 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
10660 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
10661 DAG.getConstant(8, MVT::i8));
10662 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
10663 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
10666 static bool isAllOnes(SDValue V) {
10667 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10668 return C && C->isAllOnesValue();
10671 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
10672 /// if it's possible.
10673 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
10674 SDLoc dl, SelectionDAG &DAG) const {
10675 SDValue Op0 = And.getOperand(0);
10676 SDValue Op1 = And.getOperand(1);
10677 if (Op0.getOpcode() == ISD::TRUNCATE)
10678 Op0 = Op0.getOperand(0);
10679 if (Op1.getOpcode() == ISD::TRUNCATE)
10680 Op1 = Op1.getOperand(0);
10683 if (Op1.getOpcode() == ISD::SHL)
10684 std::swap(Op0, Op1);
10685 if (Op0.getOpcode() == ISD::SHL) {
10686 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
10687 if (And00C->getZExtValue() == 1) {
10688 // If we looked past a truncate, check that it's only truncating away
10690 unsigned BitWidth = Op0.getValueSizeInBits();
10691 unsigned AndBitWidth = And.getValueSizeInBits();
10692 if (BitWidth > AndBitWidth) {
10694 DAG.computeKnownBits(Op0, Zeros, Ones);
10695 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
10699 RHS = Op0.getOperand(1);
10701 } else if (Op1.getOpcode() == ISD::Constant) {
10702 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
10703 uint64_t AndRHSVal = AndRHS->getZExtValue();
10704 SDValue AndLHS = Op0;
10706 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
10707 LHS = AndLHS.getOperand(0);
10708 RHS = AndLHS.getOperand(1);
10711 // Use BT if the immediate can't be encoded in a TEST instruction.
10712 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
10714 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
10718 if (LHS.getNode()) {
10719 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
10720 // instruction. Since the shift amount is in-range-or-undefined, we know
10721 // that doing a bittest on the i32 value is ok. We extend to i32 because
10722 // the encoding for the i16 version is larger than the i32 version.
10723 // Also promote i16 to i32 for performance / code size reason.
10724 if (LHS.getValueType() == MVT::i8 ||
10725 LHS.getValueType() == MVT::i16)
10726 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
10728 // If the operand types disagree, extend the shift amount to match. Since
10729 // BT ignores high bits (like shifts) we can use anyextend.
10730 if (LHS.getValueType() != RHS.getValueType())
10731 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
10733 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
10734 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
10735 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10736 DAG.getConstant(Cond, MVT::i8), BT);
10742 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
10744 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
10749 // SSE Condition code mapping:
10758 switch (SetCCOpcode) {
10759 default: llvm_unreachable("Unexpected SETCC condition");
10761 case ISD::SETEQ: SSECC = 0; break;
10763 case ISD::SETGT: Swap = true; // Fallthrough
10765 case ISD::SETOLT: SSECC = 1; break;
10767 case ISD::SETGE: Swap = true; // Fallthrough
10769 case ISD::SETOLE: SSECC = 2; break;
10770 case ISD::SETUO: SSECC = 3; break;
10772 case ISD::SETNE: SSECC = 4; break;
10773 case ISD::SETULE: Swap = true; // Fallthrough
10774 case ISD::SETUGE: SSECC = 5; break;
10775 case ISD::SETULT: Swap = true; // Fallthrough
10776 case ISD::SETUGT: SSECC = 6; break;
10777 case ISD::SETO: SSECC = 7; break;
10779 case ISD::SETONE: SSECC = 8; break;
10782 std::swap(Op0, Op1);
10787 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
10788 // ones, and then concatenate the result back.
10789 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
10790 MVT VT = Op.getSimpleValueType();
10792 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
10793 "Unsupported value type for operation");
10795 unsigned NumElems = VT.getVectorNumElements();
10797 SDValue CC = Op.getOperand(2);
10799 // Extract the LHS vectors
10800 SDValue LHS = Op.getOperand(0);
10801 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10802 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10804 // Extract the RHS vectors
10805 SDValue RHS = Op.getOperand(1);
10806 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10807 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10809 // Issue the operation on the smaller types and concatenate the result back
10810 MVT EltVT = VT.getVectorElementType();
10811 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10812 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10813 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
10814 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
10817 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
10818 const X86Subtarget *Subtarget) {
10819 SDValue Op0 = Op.getOperand(0);
10820 SDValue Op1 = Op.getOperand(1);
10821 SDValue CC = Op.getOperand(2);
10822 MVT VT = Op.getSimpleValueType();
10825 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
10826 Op.getValueType().getScalarType() == MVT::i1 &&
10827 "Cannot set masked compare for this operation");
10829 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10831 bool Unsigned = false;
10834 switch (SetCCOpcode) {
10835 default: llvm_unreachable("Unexpected SETCC condition");
10836 case ISD::SETNE: SSECC = 4; break;
10837 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
10838 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
10839 case ISD::SETLT: Swap = true; //fall-through
10840 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
10841 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
10842 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
10843 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
10844 case ISD::SETULE: Unsigned = true; //fall-through
10845 case ISD::SETLE: SSECC = 2; break;
10849 std::swap(Op0, Op1);
10851 return DAG.getNode(Opc, dl, VT, Op0, Op1);
10852 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
10853 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10854 DAG.getConstant(SSECC, MVT::i8));
10857 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
10858 /// operand \p Op1. If non-trivial (for example because it's not constant)
10859 /// return an empty value.
10860 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
10862 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
10866 MVT VT = Op1.getSimpleValueType();
10867 MVT EVT = VT.getVectorElementType();
10868 unsigned n = VT.getVectorNumElements();
10869 SmallVector<SDValue, 8> ULTOp1;
10871 for (unsigned i = 0; i < n; ++i) {
10872 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
10873 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
10876 // Avoid underflow.
10877 APInt Val = Elt->getAPIntValue();
10881 ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
10884 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
10887 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
10888 SelectionDAG &DAG) {
10889 SDValue Op0 = Op.getOperand(0);
10890 SDValue Op1 = Op.getOperand(1);
10891 SDValue CC = Op.getOperand(2);
10892 MVT VT = Op.getSimpleValueType();
10893 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10894 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10899 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10900 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10903 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10904 unsigned Opc = X86ISD::CMPP;
10905 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10906 assert(VT.getVectorNumElements() <= 16);
10907 Opc = X86ISD::CMPM;
10909 // In the two special cases we can't handle, emit two comparisons.
10912 unsigned CombineOpc;
10913 if (SetCCOpcode == ISD::SETUEQ) {
10914 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10916 assert(SetCCOpcode == ISD::SETONE);
10917 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10920 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10921 DAG.getConstant(CC0, MVT::i8));
10922 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10923 DAG.getConstant(CC1, MVT::i8));
10924 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10926 // Handle all other FP comparisons here.
10927 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10928 DAG.getConstant(SSECC, MVT::i8));
10931 // Break 256-bit integer vector compare into smaller ones.
10932 if (VT.is256BitVector() && !Subtarget->hasInt256())
10933 return Lower256IntVSETCC(Op, DAG);
10935 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10936 EVT OpVT = Op1.getValueType();
10937 if (Subtarget->hasAVX512()) {
10938 if (Op1.getValueType().is512BitVector() ||
10939 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10940 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
10942 // In AVX-512 architecture setcc returns mask with i1 elements,
10943 // But there is no compare instruction for i8 and i16 elements.
10944 // We are not talking about 512-bit operands in this case, these
10945 // types are illegal.
10947 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10948 OpVT.getVectorElementType().getSizeInBits() >= 8))
10949 return DAG.getNode(ISD::TRUNCATE, dl, VT,
10950 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10953 // We are handling one of the integer comparisons here. Since SSE only has
10954 // GT and EQ comparisons for integer, swapping operands and multiple
10955 // operations may be required for some comparisons.
10957 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10958 bool Subus = false;
10960 switch (SetCCOpcode) {
10961 default: llvm_unreachable("Unexpected SETCC condition");
10962 case ISD::SETNE: Invert = true;
10963 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
10964 case ISD::SETLT: Swap = true;
10965 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
10966 case ISD::SETGE: Swap = true;
10967 case ISD::SETLE: Opc = X86ISD::PCMPGT;
10968 Invert = true; break;
10969 case ISD::SETULT: Swap = true;
10970 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
10971 FlipSigns = true; break;
10972 case ISD::SETUGE: Swap = true;
10973 case ISD::SETULE: Opc = X86ISD::PCMPGT;
10974 FlipSigns = true; Invert = true; break;
10977 // Special case: Use min/max operations for SETULE/SETUGE
10978 MVT VET = VT.getVectorElementType();
10980 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10981 || (Subtarget->hasSSE2() && (VET == MVT::i8));
10984 switch (SetCCOpcode) {
10986 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10987 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10990 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10993 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
10994 if (!MinMax && hasSubus) {
10995 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
10997 // t = psubus Op0, Op1
10998 // pcmpeq t, <0..0>
10999 switch (SetCCOpcode) {
11001 case ISD::SETULT: {
11002 // If the comparison is against a constant we can turn this into a
11003 // setule. With psubus, setule does not require a swap. This is
11004 // beneficial because the constant in the register is no longer
11005 // destructed as the destination so it can be hoisted out of a loop.
11006 // Only do this pre-AVX since vpcmp* is no longer destructive.
11007 if (Subtarget->hasAVX())
11009 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
11010 if (ULEOp1.getNode()) {
11012 Subus = true; Invert = false; Swap = false;
11016 // Psubus is better than flip-sign because it requires no inversion.
11017 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
11018 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
11022 Opc = X86ISD::SUBUS;
11028 std::swap(Op0, Op1);
11030 // Check that the operation in question is available (most are plain SSE2,
11031 // but PCMPGTQ and PCMPEQQ have different requirements).
11032 if (VT == MVT::v2i64) {
11033 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
11034 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
11036 // First cast everything to the right type.
11037 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
11038 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
11040 // Since SSE has no unsigned integer comparisons, we need to flip the sign
11041 // bits of the inputs before performing those operations. The lower
11042 // compare is always unsigned.
11045 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
11047 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
11048 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
11049 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
11050 Sign, Zero, Sign, Zero);
11052 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
11053 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
11055 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
11056 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
11057 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
11059 // Create masks for only the low parts/high parts of the 64 bit integers.
11060 static const int MaskHi[] = { 1, 1, 3, 3 };
11061 static const int MaskLo[] = { 0, 0, 2, 2 };
11062 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
11063 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
11064 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
11066 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
11067 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
11070 Result = DAG.getNOT(dl, Result, MVT::v4i32);
11072 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
11075 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
11076 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
11077 // pcmpeqd + pshufd + pand.
11078 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
11080 // First cast everything to the right type.
11081 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
11082 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
11085 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
11087 // Make sure the lower and upper halves are both all-ones.
11088 static const int Mask[] = { 1, 0, 3, 2 };
11089 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
11090 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
11093 Result = DAG.getNOT(dl, Result, MVT::v4i32);
11095 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
11099 // Since SSE has no unsigned integer comparisons, we need to flip the sign
11100 // bits of the inputs before performing those operations.
11102 EVT EltVT = VT.getVectorElementType();
11103 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
11104 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
11105 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
11108 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
11110 // If the logical-not of the result is required, perform that now.
11112 Result = DAG.getNOT(dl, Result, VT);
11115 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
11118 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
11119 getZeroVector(VT, Subtarget, DAG, dl));
11124 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
11126 MVT VT = Op.getSimpleValueType();
11128 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
11130 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
11131 && "SetCC type must be 8-bit or 1-bit integer");
11132 SDValue Op0 = Op.getOperand(0);
11133 SDValue Op1 = Op.getOperand(1);
11135 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
11137 // Optimize to BT if possible.
11138 // Lower (X & (1 << N)) == 0 to BT(X, N).
11139 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
11140 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
11141 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
11142 Op1.getOpcode() == ISD::Constant &&
11143 cast<ConstantSDNode>(Op1)->isNullValue() &&
11144 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
11145 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
11146 if (NewSetCC.getNode())
11150 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
11152 if (Op1.getOpcode() == ISD::Constant &&
11153 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
11154 cast<ConstantSDNode>(Op1)->isNullValue()) &&
11155 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
11157 // If the input is a setcc, then reuse the input setcc or use a new one with
11158 // the inverted condition.
11159 if (Op0.getOpcode() == X86ISD::SETCC) {
11160 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
11161 bool Invert = (CC == ISD::SETNE) ^
11162 cast<ConstantSDNode>(Op1)->isNullValue();
11166 CCode = X86::GetOppositeBranchCondition(CCode);
11167 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11168 DAG.getConstant(CCode, MVT::i8),
11169 Op0.getOperand(1));
11171 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
11175 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
11176 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
11177 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
11179 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
11180 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
11183 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
11184 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
11185 if (X86CC == X86::COND_INVALID)
11188 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
11189 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
11190 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11191 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
11193 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
11197 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
11198 static bool isX86LogicalCmp(SDValue Op) {
11199 unsigned Opc = Op.getNode()->getOpcode();
11200 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
11201 Opc == X86ISD::SAHF)
11203 if (Op.getResNo() == 1 &&
11204 (Opc == X86ISD::ADD ||
11205 Opc == X86ISD::SUB ||
11206 Opc == X86ISD::ADC ||
11207 Opc == X86ISD::SBB ||
11208 Opc == X86ISD::SMUL ||
11209 Opc == X86ISD::UMUL ||
11210 Opc == X86ISD::INC ||
11211 Opc == X86ISD::DEC ||
11212 Opc == X86ISD::OR ||
11213 Opc == X86ISD::XOR ||
11214 Opc == X86ISD::AND))
11217 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
11223 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
11224 if (V.getOpcode() != ISD::TRUNCATE)
11227 SDValue VOp0 = V.getOperand(0);
11228 unsigned InBits = VOp0.getValueSizeInBits();
11229 unsigned Bits = V.getValueSizeInBits();
11230 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
11233 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
11234 bool addTest = true;
11235 SDValue Cond = Op.getOperand(0);
11236 SDValue Op1 = Op.getOperand(1);
11237 SDValue Op2 = Op.getOperand(2);
11239 EVT VT = Op1.getValueType();
11242 // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
11243 // are available. Otherwise fp cmovs get lowered into a less efficient branch
11244 // sequence later on.
11245 if (Cond.getOpcode() == ISD::SETCC &&
11246 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
11247 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
11248 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
11249 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
11250 int SSECC = translateX86FSETCC(
11251 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
11254 if (Subtarget->hasAVX512()) {
11255 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
11256 DAG.getConstant(SSECC, MVT::i8));
11257 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
11259 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
11260 DAG.getConstant(SSECC, MVT::i8));
11261 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
11262 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
11263 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
11267 if (Cond.getOpcode() == ISD::SETCC) {
11268 SDValue NewCond = LowerSETCC(Cond, DAG);
11269 if (NewCond.getNode())
11273 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
11274 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
11275 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
11276 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
11277 if (Cond.getOpcode() == X86ISD::SETCC &&
11278 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
11279 isZero(Cond.getOperand(1).getOperand(1))) {
11280 SDValue Cmp = Cond.getOperand(1);
11282 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
11284 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
11285 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
11286 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
11288 SDValue CmpOp0 = Cmp.getOperand(0);
11289 // Apply further optimizations for special cases
11290 // (select (x != 0), -1, 0) -> neg & sbb
11291 // (select (x == 0), 0, -1) -> neg & sbb
11292 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
11293 if (YC->isNullValue() &&
11294 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
11295 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
11296 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
11297 DAG.getConstant(0, CmpOp0.getValueType()),
11299 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
11300 DAG.getConstant(X86::COND_B, MVT::i8),
11301 SDValue(Neg.getNode(), 1));
11305 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
11306 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
11307 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11309 SDValue Res = // Res = 0 or -1.
11310 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
11311 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
11313 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
11314 Res = DAG.getNOT(DL, Res, Res.getValueType());
11316 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
11317 if (!N2C || !N2C->isNullValue())
11318 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
11323 // Look past (and (setcc_carry (cmp ...)), 1).
11324 if (Cond.getOpcode() == ISD::AND &&
11325 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
11326 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11327 if (C && C->getAPIntValue() == 1)
11328 Cond = Cond.getOperand(0);
11331 // If condition flag is set by a X86ISD::CMP, then use it as the condition
11332 // setting operand in place of the X86ISD::SETCC.
11333 unsigned CondOpcode = Cond.getOpcode();
11334 if (CondOpcode == X86ISD::SETCC ||
11335 CondOpcode == X86ISD::SETCC_CARRY) {
11336 CC = Cond.getOperand(0);
11338 SDValue Cmp = Cond.getOperand(1);
11339 unsigned Opc = Cmp.getOpcode();
11340 MVT VT = Op.getSimpleValueType();
11342 bool IllegalFPCMov = false;
11343 if (VT.isFloatingPoint() && !VT.isVector() &&
11344 !isScalarFPTypeInSSEReg(VT)) // FPStack?
11345 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
11347 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
11348 Opc == X86ISD::BT) { // FIXME
11352 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11353 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11354 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11355 Cond.getOperand(0).getValueType() != MVT::i8)) {
11356 SDValue LHS = Cond.getOperand(0);
11357 SDValue RHS = Cond.getOperand(1);
11358 unsigned X86Opcode;
11361 switch (CondOpcode) {
11362 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11363 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11364 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11365 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11366 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11367 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11368 default: llvm_unreachable("unexpected overflowing operator");
11370 if (CondOpcode == ISD::UMULO)
11371 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11374 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11376 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
11378 if (CondOpcode == ISD::UMULO)
11379 Cond = X86Op.getValue(2);
11381 Cond = X86Op.getValue(1);
11383 CC = DAG.getConstant(X86Cond, MVT::i8);
11388 // Look pass the truncate if the high bits are known zero.
11389 if (isTruncWithZeroHighBitsInput(Cond, DAG))
11390 Cond = Cond.getOperand(0);
11392 // We know the result of AND is compared against zero. Try to match
11394 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11395 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
11396 if (NewSetCC.getNode()) {
11397 CC = NewSetCC.getOperand(0);
11398 Cond = NewSetCC.getOperand(1);
11405 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11406 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
11409 // a < b ? -1 : 0 -> RES = ~setcc_carry
11410 // a < b ? 0 : -1 -> RES = setcc_carry
11411 // a >= b ? -1 : 0 -> RES = setcc_carry
11412 // a >= b ? 0 : -1 -> RES = ~setcc_carry
11413 if (Cond.getOpcode() == X86ISD::SUB) {
11414 Cond = ConvertCmpIfNecessary(Cond, DAG);
11415 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
11417 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
11418 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
11419 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
11420 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
11421 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
11422 return DAG.getNOT(DL, Res, Res.getValueType());
11427 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
11428 // widen the cmov and push the truncate through. This avoids introducing a new
11429 // branch during isel and doesn't add any extensions.
11430 if (Op.getValueType() == MVT::i8 &&
11431 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
11432 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
11433 if (T1.getValueType() == T2.getValueType() &&
11434 // Blacklist CopyFromReg to avoid partial register stalls.
11435 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
11436 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
11437 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
11438 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
11442 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
11443 // condition is true.
11444 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
11445 SDValue Ops[] = { Op2, Op1, CC, Cond };
11446 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
11449 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
11450 MVT VT = Op->getSimpleValueType(0);
11451 SDValue In = Op->getOperand(0);
11452 MVT InVT = In.getSimpleValueType();
11455 unsigned int NumElts = VT.getVectorNumElements();
11456 if (NumElts != 8 && NumElts != 16)
11459 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11460 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
11462 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11463 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11465 MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
11466 Constant *C = ConstantInt::get(*DAG.getContext(),
11467 APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
11469 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11470 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11471 SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
11472 MachinePointerInfo::getConstantPool(),
11473 false, false, false, Alignment);
11474 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
11475 if (VT.is512BitVector())
11477 return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
11480 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11481 SelectionDAG &DAG) {
11482 MVT VT = Op->getSimpleValueType(0);
11483 SDValue In = Op->getOperand(0);
11484 MVT InVT = In.getSimpleValueType();
11487 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
11488 return LowerSIGN_EXTEND_AVX512(Op, DAG);
11490 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
11491 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
11492 (VT != MVT::v16i16 || InVT != MVT::v16i8))
11495 if (Subtarget->hasInt256())
11496 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
11498 // Optimize vectors in AVX mode
11499 // Sign extend v8i16 to v8i32 and
11502 // Divide input vector into two parts
11503 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
11504 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
11505 // concat the vectors to original VT
11507 unsigned NumElems = InVT.getVectorNumElements();
11508 SDValue Undef = DAG.getUNDEF(InVT);
11510 SmallVector<int,8> ShufMask1(NumElems, -1);
11511 for (unsigned i = 0; i != NumElems/2; ++i)
11514 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
11516 SmallVector<int,8> ShufMask2(NumElems, -1);
11517 for (unsigned i = 0; i != NumElems/2; ++i)
11518 ShufMask2[i] = i + NumElems/2;
11520 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
11522 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
11523 VT.getVectorNumElements()/2);
11525 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
11526 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
11528 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11531 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
11532 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
11533 // from the AND / OR.
11534 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
11535 Opc = Op.getOpcode();
11536 if (Opc != ISD::OR && Opc != ISD::AND)
11538 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
11539 Op.getOperand(0).hasOneUse() &&
11540 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
11541 Op.getOperand(1).hasOneUse());
11544 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
11545 // 1 and that the SETCC node has a single use.
11546 static bool isXor1OfSetCC(SDValue Op) {
11547 if (Op.getOpcode() != ISD::XOR)
11549 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
11550 if (N1C && N1C->getAPIntValue() == 1) {
11551 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
11552 Op.getOperand(0).hasOneUse();
11557 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
11558 bool addTest = true;
11559 SDValue Chain = Op.getOperand(0);
11560 SDValue Cond = Op.getOperand(1);
11561 SDValue Dest = Op.getOperand(2);
11564 bool Inverted = false;
11566 if (Cond.getOpcode() == ISD::SETCC) {
11567 // Check for setcc([su]{add,sub,mul}o == 0).
11568 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
11569 isa<ConstantSDNode>(Cond.getOperand(1)) &&
11570 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
11571 Cond.getOperand(0).getResNo() == 1 &&
11572 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
11573 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
11574 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
11575 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
11576 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
11577 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
11579 Cond = Cond.getOperand(0);
11581 SDValue NewCond = LowerSETCC(Cond, DAG);
11582 if (NewCond.getNode())
11587 // FIXME: LowerXALUO doesn't handle these!!
11588 else if (Cond.getOpcode() == X86ISD::ADD ||
11589 Cond.getOpcode() == X86ISD::SUB ||
11590 Cond.getOpcode() == X86ISD::SMUL ||
11591 Cond.getOpcode() == X86ISD::UMUL)
11592 Cond = LowerXALUO(Cond, DAG);
11595 // Look pass (and (setcc_carry (cmp ...)), 1).
11596 if (Cond.getOpcode() == ISD::AND &&
11597 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
11598 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11599 if (C && C->getAPIntValue() == 1)
11600 Cond = Cond.getOperand(0);
11603 // If condition flag is set by a X86ISD::CMP, then use it as the condition
11604 // setting operand in place of the X86ISD::SETCC.
11605 unsigned CondOpcode = Cond.getOpcode();
11606 if (CondOpcode == X86ISD::SETCC ||
11607 CondOpcode == X86ISD::SETCC_CARRY) {
11608 CC = Cond.getOperand(0);
11610 SDValue Cmp = Cond.getOperand(1);
11611 unsigned Opc = Cmp.getOpcode();
11612 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
11613 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
11617 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
11621 // These can only come from an arithmetic instruction with overflow,
11622 // e.g. SADDO, UADDO.
11623 Cond = Cond.getNode()->getOperand(1);
11629 CondOpcode = Cond.getOpcode();
11630 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11631 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11632 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11633 Cond.getOperand(0).getValueType() != MVT::i8)) {
11634 SDValue LHS = Cond.getOperand(0);
11635 SDValue RHS = Cond.getOperand(1);
11636 unsigned X86Opcode;
11639 // Keep this in sync with LowerXALUO, otherwise we might create redundant
11640 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
11642 switch (CondOpcode) {
11643 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11645 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11647 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
11650 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11651 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11653 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11655 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
11658 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11659 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11660 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11661 default: llvm_unreachable("unexpected overflowing operator");
11664 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
11665 if (CondOpcode == ISD::UMULO)
11666 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11669 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11671 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
11673 if (CondOpcode == ISD::UMULO)
11674 Cond = X86Op.getValue(2);
11676 Cond = X86Op.getValue(1);
11678 CC = DAG.getConstant(X86Cond, MVT::i8);
11682 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
11683 SDValue Cmp = Cond.getOperand(0).getOperand(1);
11684 if (CondOpc == ISD::OR) {
11685 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
11686 // two branches instead of an explicit OR instruction with a
11688 if (Cmp == Cond.getOperand(1).getOperand(1) &&
11689 isX86LogicalCmp(Cmp)) {
11690 CC = Cond.getOperand(0).getOperand(0);
11691 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11692 Chain, Dest, CC, Cmp);
11693 CC = Cond.getOperand(1).getOperand(0);
11697 } else { // ISD::AND
11698 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
11699 // two branches instead of an explicit AND instruction with a
11700 // separate test. However, we only do this if this block doesn't
11701 // have a fall-through edge, because this requires an explicit
11702 // jmp when the condition is false.
11703 if (Cmp == Cond.getOperand(1).getOperand(1) &&
11704 isX86LogicalCmp(Cmp) &&
11705 Op.getNode()->hasOneUse()) {
11706 X86::CondCode CCode =
11707 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11708 CCode = X86::GetOppositeBranchCondition(CCode);
11709 CC = DAG.getConstant(CCode, MVT::i8);
11710 SDNode *User = *Op.getNode()->use_begin();
11711 // Look for an unconditional branch following this conditional branch.
11712 // We need this because we need to reverse the successors in order
11713 // to implement FCMP_OEQ.
11714 if (User->getOpcode() == ISD::BR) {
11715 SDValue FalseBB = User->getOperand(1);
11717 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11718 assert(NewBR == User);
11722 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11723 Chain, Dest, CC, Cmp);
11724 X86::CondCode CCode =
11725 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
11726 CCode = X86::GetOppositeBranchCondition(CCode);
11727 CC = DAG.getConstant(CCode, MVT::i8);
11733 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
11734 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
11735 // It should be transformed during dag combiner except when the condition
11736 // is set by a arithmetics with overflow node.
11737 X86::CondCode CCode =
11738 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11739 CCode = X86::GetOppositeBranchCondition(CCode);
11740 CC = DAG.getConstant(CCode, MVT::i8);
11741 Cond = Cond.getOperand(0).getOperand(1);
11743 } else if (Cond.getOpcode() == ISD::SETCC &&
11744 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
11745 // For FCMP_OEQ, we can emit
11746 // two branches instead of an explicit AND instruction with a
11747 // separate test. However, we only do this if this block doesn't
11748 // have a fall-through edge, because this requires an explicit
11749 // jmp when the condition is false.
11750 if (Op.getNode()->hasOneUse()) {
11751 SDNode *User = *Op.getNode()->use_begin();
11752 // Look for an unconditional branch following this conditional branch.
11753 // We need this because we need to reverse the successors in order
11754 // to implement FCMP_OEQ.
11755 if (User->getOpcode() == ISD::BR) {
11756 SDValue FalseBB = User->getOperand(1);
11758 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11759 assert(NewBR == User);
11763 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11764 Cond.getOperand(0), Cond.getOperand(1));
11765 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11766 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11767 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11768 Chain, Dest, CC, Cmp);
11769 CC = DAG.getConstant(X86::COND_P, MVT::i8);
11774 } else if (Cond.getOpcode() == ISD::SETCC &&
11775 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
11776 // For FCMP_UNE, we can emit
11777 // two branches instead of an explicit AND instruction with a
11778 // separate test. However, we only do this if this block doesn't
11779 // have a fall-through edge, because this requires an explicit
11780 // jmp when the condition is false.
11781 if (Op.getNode()->hasOneUse()) {
11782 SDNode *User = *Op.getNode()->use_begin();
11783 // Look for an unconditional branch following this conditional branch.
11784 // We need this because we need to reverse the successors in order
11785 // to implement FCMP_UNE.
11786 if (User->getOpcode() == ISD::BR) {
11787 SDValue FalseBB = User->getOperand(1);
11789 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11790 assert(NewBR == User);
11793 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11794 Cond.getOperand(0), Cond.getOperand(1));
11795 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11796 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11797 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11798 Chain, Dest, CC, Cmp);
11799 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
11809 // Look pass the truncate if the high bits are known zero.
11810 if (isTruncWithZeroHighBitsInput(Cond, DAG))
11811 Cond = Cond.getOperand(0);
11813 // We know the result of AND is compared against zero. Try to match
11815 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11816 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
11817 if (NewSetCC.getNode()) {
11818 CC = NewSetCC.getOperand(0);
11819 Cond = NewSetCC.getOperand(1);
11826 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
11827 CC = DAG.getConstant(X86Cond, MVT::i8);
11828 Cond = EmitTest(Cond, X86Cond, dl, DAG);
11830 Cond = ConvertCmpIfNecessary(Cond, DAG);
11831 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11832 Chain, Dest, CC, Cond);
11835 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
11836 // Calls to _alloca is needed to probe the stack when allocating more than 4k
11837 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
11838 // that the guard pages used by the OS virtual memory manager are allocated in
11839 // correct sequence.
11841 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
11842 SelectionDAG &DAG) const {
11843 MachineFunction &MF = DAG.getMachineFunction();
11844 bool SplitStack = MF.shouldSplitStack();
11845 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
11850 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11851 SDNode* Node = Op.getNode();
11853 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
11854 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
11855 " not tell us which reg is the stack pointer!");
11856 EVT VT = Node->getValueType(0);
11857 SDValue Tmp1 = SDValue(Node, 0);
11858 SDValue Tmp2 = SDValue(Node, 1);
11859 SDValue Tmp3 = Node->getOperand(2);
11860 SDValue Chain = Tmp1.getOperand(0);
11862 // Chain the dynamic stack allocation so that it doesn't modify the stack
11863 // pointer when other instructions are using the stack.
11864 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
11867 SDValue Size = Tmp2.getOperand(1);
11868 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
11869 Chain = SP.getValue(1);
11870 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
11871 const TargetFrameLowering &TFI = *DAG.getTarget().getFrameLowering();
11872 unsigned StackAlign = TFI.getStackAlignment();
11873 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
11874 if (Align > StackAlign)
11875 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
11876 DAG.getConstant(-(uint64_t)Align, VT));
11877 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
11879 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
11880 DAG.getIntPtrConstant(0, true), SDValue(),
11883 SDValue Ops[2] = { Tmp1, Tmp2 };
11884 return DAG.getMergeValues(Ops, dl);
11888 SDValue Chain = Op.getOperand(0);
11889 SDValue Size = Op.getOperand(1);
11890 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11891 EVT VT = Op.getNode()->getValueType(0);
11893 bool Is64Bit = Subtarget->is64Bit();
11894 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
11897 MachineRegisterInfo &MRI = MF.getRegInfo();
11900 // The 64 bit implementation of segmented stacks needs to clobber both r10
11901 // r11. This makes it impossible to use it along with nested parameters.
11902 const Function *F = MF.getFunction();
11904 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
11906 if (I->hasNestAttr())
11907 report_fatal_error("Cannot use segmented stacks with functions that "
11908 "have nested arguments.");
11911 const TargetRegisterClass *AddrRegClass =
11912 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
11913 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
11914 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
11915 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
11916 DAG.getRegister(Vreg, SPTy));
11917 SDValue Ops1[2] = { Value, Chain };
11918 return DAG.getMergeValues(Ops1, dl);
11921 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
11923 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
11924 Flag = Chain.getValue(1);
11925 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11927 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
11929 const X86RegisterInfo *RegInfo =
11930 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
11931 unsigned SPReg = RegInfo->getStackRegister();
11932 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
11933 Chain = SP.getValue(1);
11936 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11937 DAG.getConstant(-(uint64_t)Align, VT));
11938 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
11941 SDValue Ops1[2] = { SP, Chain };
11942 return DAG.getMergeValues(Ops1, dl);
11946 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
11947 MachineFunction &MF = DAG.getMachineFunction();
11948 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
11950 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11953 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
11954 // vastart just stores the address of the VarArgsFrameIndex slot into the
11955 // memory location argument.
11956 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11958 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
11959 MachinePointerInfo(SV), false, false, 0);
11963 // gp_offset (0 - 6 * 8)
11964 // fp_offset (48 - 48 + 8 * 16)
11965 // overflow_arg_area (point to parameters coming in memory).
11967 SmallVector<SDValue, 8> MemOps;
11968 SDValue FIN = Op.getOperand(1);
11970 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
11971 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
11973 FIN, MachinePointerInfo(SV), false, false, 0);
11974 MemOps.push_back(Store);
11977 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11978 FIN, DAG.getIntPtrConstant(4));
11979 Store = DAG.getStore(Op.getOperand(0), DL,
11980 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
11982 FIN, MachinePointerInfo(SV, 4), false, false, 0);
11983 MemOps.push_back(Store);
11985 // Store ptr to overflow_arg_area
11986 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11987 FIN, DAG.getIntPtrConstant(4));
11988 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11990 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11991 MachinePointerInfo(SV, 8),
11993 MemOps.push_back(Store);
11995 // Store ptr to reg_save_area.
11996 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11997 FIN, DAG.getIntPtrConstant(8));
11998 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
12000 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
12001 MachinePointerInfo(SV, 16), false, false, 0);
12002 MemOps.push_back(Store);
12003 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
12006 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
12007 assert(Subtarget->is64Bit() &&
12008 "LowerVAARG only handles 64-bit va_arg!");
12009 assert((Subtarget->isTargetLinux() ||
12010 Subtarget->isTargetDarwin()) &&
12011 "Unhandled target in LowerVAARG");
12012 assert(Op.getNode()->getNumOperands() == 4);
12013 SDValue Chain = Op.getOperand(0);
12014 SDValue SrcPtr = Op.getOperand(1);
12015 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
12016 unsigned Align = Op.getConstantOperandVal(3);
12019 EVT ArgVT = Op.getNode()->getValueType(0);
12020 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
12021 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
12024 // Decide which area this value should be read from.
12025 // TODO: Implement the AMD64 ABI in its entirety. This simple
12026 // selection mechanism works only for the basic types.
12027 if (ArgVT == MVT::f80) {
12028 llvm_unreachable("va_arg for f80 not yet implemented");
12029 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
12030 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
12031 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
12032 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
12034 llvm_unreachable("Unhandled argument type in LowerVAARG");
12037 if (ArgMode == 2) {
12038 // Sanity Check: Make sure using fp_offset makes sense.
12039 assert(!DAG.getTarget().Options.UseSoftFloat &&
12040 !(DAG.getMachineFunction()
12041 .getFunction()->getAttributes()
12042 .hasAttribute(AttributeSet::FunctionIndex,
12043 Attribute::NoImplicitFloat)) &&
12044 Subtarget->hasSSE1());
12047 // Insert VAARG_64 node into the DAG
12048 // VAARG_64 returns two values: Variable Argument Address, Chain
12049 SmallVector<SDValue, 11> InstOps;
12050 InstOps.push_back(Chain);
12051 InstOps.push_back(SrcPtr);
12052 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
12053 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
12054 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
12055 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
12056 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
12057 VTs, InstOps, MVT::i64,
12058 MachinePointerInfo(SV),
12060 /*Volatile=*/false,
12062 /*WriteMem=*/true);
12063 Chain = VAARG.getValue(1);
12065 // Load the next argument and return it
12066 return DAG.getLoad(ArgVT, dl,
12069 MachinePointerInfo(),
12070 false, false, false, 0);
12073 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
12074 SelectionDAG &DAG) {
12075 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
12076 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
12077 SDValue Chain = Op.getOperand(0);
12078 SDValue DstPtr = Op.getOperand(1);
12079 SDValue SrcPtr = Op.getOperand(2);
12080 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
12081 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
12084 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
12085 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
12087 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
12090 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
12091 // amount is a constant. Takes immediate version of shift as input.
12092 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
12093 SDValue SrcOp, uint64_t ShiftAmt,
12094 SelectionDAG &DAG) {
12095 MVT ElementType = VT.getVectorElementType();
12097 // Fold this packed shift into its first operand if ShiftAmt is 0.
12101 // Check for ShiftAmt >= element width
12102 if (ShiftAmt >= ElementType.getSizeInBits()) {
12103 if (Opc == X86ISD::VSRAI)
12104 ShiftAmt = ElementType.getSizeInBits() - 1;
12106 return DAG.getConstant(0, VT);
12109 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
12110 && "Unknown target vector shift-by-constant node");
12112 // Fold this packed vector shift into a build vector if SrcOp is a
12113 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
12114 if (VT == SrcOp.getSimpleValueType() &&
12115 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
12116 SmallVector<SDValue, 8> Elts;
12117 unsigned NumElts = SrcOp->getNumOperands();
12118 ConstantSDNode *ND;
12121 default: llvm_unreachable(nullptr);
12122 case X86ISD::VSHLI:
12123 for (unsigned i=0; i!=NumElts; ++i) {
12124 SDValue CurrentOp = SrcOp->getOperand(i);
12125 if (CurrentOp->getOpcode() == ISD::UNDEF) {
12126 Elts.push_back(CurrentOp);
12129 ND = cast<ConstantSDNode>(CurrentOp);
12130 const APInt &C = ND->getAPIntValue();
12131 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
12134 case X86ISD::VSRLI:
12135 for (unsigned i=0; i!=NumElts; ++i) {
12136 SDValue CurrentOp = SrcOp->getOperand(i);
12137 if (CurrentOp->getOpcode() == ISD::UNDEF) {
12138 Elts.push_back(CurrentOp);
12141 ND = cast<ConstantSDNode>(CurrentOp);
12142 const APInt &C = ND->getAPIntValue();
12143 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
12146 case X86ISD::VSRAI:
12147 for (unsigned i=0; i!=NumElts; ++i) {
12148 SDValue CurrentOp = SrcOp->getOperand(i);
12149 if (CurrentOp->getOpcode() == ISD::UNDEF) {
12150 Elts.push_back(CurrentOp);
12153 ND = cast<ConstantSDNode>(CurrentOp);
12154 const APInt &C = ND->getAPIntValue();
12155 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
12160 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
12163 return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
12166 // getTargetVShiftNode - Handle vector element shifts where the shift amount
12167 // may or may not be a constant. Takes immediate version of shift as input.
12168 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
12169 SDValue SrcOp, SDValue ShAmt,
12170 SelectionDAG &DAG) {
12171 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
12173 // Catch shift-by-constant.
12174 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
12175 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
12176 CShAmt->getZExtValue(), DAG);
12178 // Change opcode to non-immediate version
12180 default: llvm_unreachable("Unknown target vector shift node");
12181 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
12182 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
12183 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
12186 // Need to build a vector containing shift amount
12187 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
12190 ShOps[1] = DAG.getConstant(0, MVT::i32);
12191 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
12192 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
12194 // The return type has to be a 128-bit type with the same element
12195 // type as the input type.
12196 MVT EltVT = VT.getVectorElementType();
12197 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
12199 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
12200 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
12203 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
12205 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12207 default: return SDValue(); // Don't custom lower most intrinsics.
12208 // Comparison intrinsics.
12209 case Intrinsic::x86_sse_comieq_ss:
12210 case Intrinsic::x86_sse_comilt_ss:
12211 case Intrinsic::x86_sse_comile_ss:
12212 case Intrinsic::x86_sse_comigt_ss:
12213 case Intrinsic::x86_sse_comige_ss:
12214 case Intrinsic::x86_sse_comineq_ss:
12215 case Intrinsic::x86_sse_ucomieq_ss:
12216 case Intrinsic::x86_sse_ucomilt_ss:
12217 case Intrinsic::x86_sse_ucomile_ss:
12218 case Intrinsic::x86_sse_ucomigt_ss:
12219 case Intrinsic::x86_sse_ucomige_ss:
12220 case Intrinsic::x86_sse_ucomineq_ss:
12221 case Intrinsic::x86_sse2_comieq_sd:
12222 case Intrinsic::x86_sse2_comilt_sd:
12223 case Intrinsic::x86_sse2_comile_sd:
12224 case Intrinsic::x86_sse2_comigt_sd:
12225 case Intrinsic::x86_sse2_comige_sd:
12226 case Intrinsic::x86_sse2_comineq_sd:
12227 case Intrinsic::x86_sse2_ucomieq_sd:
12228 case Intrinsic::x86_sse2_ucomilt_sd:
12229 case Intrinsic::x86_sse2_ucomile_sd:
12230 case Intrinsic::x86_sse2_ucomigt_sd:
12231 case Intrinsic::x86_sse2_ucomige_sd:
12232 case Intrinsic::x86_sse2_ucomineq_sd: {
12236 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12237 case Intrinsic::x86_sse_comieq_ss:
12238 case Intrinsic::x86_sse2_comieq_sd:
12239 Opc = X86ISD::COMI;
12242 case Intrinsic::x86_sse_comilt_ss:
12243 case Intrinsic::x86_sse2_comilt_sd:
12244 Opc = X86ISD::COMI;
12247 case Intrinsic::x86_sse_comile_ss:
12248 case Intrinsic::x86_sse2_comile_sd:
12249 Opc = X86ISD::COMI;
12252 case Intrinsic::x86_sse_comigt_ss:
12253 case Intrinsic::x86_sse2_comigt_sd:
12254 Opc = X86ISD::COMI;
12257 case Intrinsic::x86_sse_comige_ss:
12258 case Intrinsic::x86_sse2_comige_sd:
12259 Opc = X86ISD::COMI;
12262 case Intrinsic::x86_sse_comineq_ss:
12263 case Intrinsic::x86_sse2_comineq_sd:
12264 Opc = X86ISD::COMI;
12267 case Intrinsic::x86_sse_ucomieq_ss:
12268 case Intrinsic::x86_sse2_ucomieq_sd:
12269 Opc = X86ISD::UCOMI;
12272 case Intrinsic::x86_sse_ucomilt_ss:
12273 case Intrinsic::x86_sse2_ucomilt_sd:
12274 Opc = X86ISD::UCOMI;
12277 case Intrinsic::x86_sse_ucomile_ss:
12278 case Intrinsic::x86_sse2_ucomile_sd:
12279 Opc = X86ISD::UCOMI;
12282 case Intrinsic::x86_sse_ucomigt_ss:
12283 case Intrinsic::x86_sse2_ucomigt_sd:
12284 Opc = X86ISD::UCOMI;
12287 case Intrinsic::x86_sse_ucomige_ss:
12288 case Intrinsic::x86_sse2_ucomige_sd:
12289 Opc = X86ISD::UCOMI;
12292 case Intrinsic::x86_sse_ucomineq_ss:
12293 case Intrinsic::x86_sse2_ucomineq_sd:
12294 Opc = X86ISD::UCOMI;
12299 SDValue LHS = Op.getOperand(1);
12300 SDValue RHS = Op.getOperand(2);
12301 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
12302 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
12303 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
12304 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12305 DAG.getConstant(X86CC, MVT::i8), Cond);
12306 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12309 // Arithmetic intrinsics.
12310 case Intrinsic::x86_sse2_pmulu_dq:
12311 case Intrinsic::x86_avx2_pmulu_dq:
12312 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
12313 Op.getOperand(1), Op.getOperand(2));
12315 case Intrinsic::x86_sse41_pmuldq:
12316 case Intrinsic::x86_avx2_pmul_dq:
12317 return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
12318 Op.getOperand(1), Op.getOperand(2));
12320 case Intrinsic::x86_sse2_pmulhu_w:
12321 case Intrinsic::x86_avx2_pmulhu_w:
12322 return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
12323 Op.getOperand(1), Op.getOperand(2));
12325 case Intrinsic::x86_sse2_pmulh_w:
12326 case Intrinsic::x86_avx2_pmulh_w:
12327 return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
12328 Op.getOperand(1), Op.getOperand(2));
12330 // SSE2/AVX2 sub with unsigned saturation intrinsics
12331 case Intrinsic::x86_sse2_psubus_b:
12332 case Intrinsic::x86_sse2_psubus_w:
12333 case Intrinsic::x86_avx2_psubus_b:
12334 case Intrinsic::x86_avx2_psubus_w:
12335 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
12336 Op.getOperand(1), Op.getOperand(2));
12338 // SSE3/AVX horizontal add/sub intrinsics
12339 case Intrinsic::x86_sse3_hadd_ps:
12340 case Intrinsic::x86_sse3_hadd_pd:
12341 case Intrinsic::x86_avx_hadd_ps_256:
12342 case Intrinsic::x86_avx_hadd_pd_256:
12343 case Intrinsic::x86_sse3_hsub_ps:
12344 case Intrinsic::x86_sse3_hsub_pd:
12345 case Intrinsic::x86_avx_hsub_ps_256:
12346 case Intrinsic::x86_avx_hsub_pd_256:
12347 case Intrinsic::x86_ssse3_phadd_w_128:
12348 case Intrinsic::x86_ssse3_phadd_d_128:
12349 case Intrinsic::x86_avx2_phadd_w:
12350 case Intrinsic::x86_avx2_phadd_d:
12351 case Intrinsic::x86_ssse3_phsub_w_128:
12352 case Intrinsic::x86_ssse3_phsub_d_128:
12353 case Intrinsic::x86_avx2_phsub_w:
12354 case Intrinsic::x86_avx2_phsub_d: {
12357 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12358 case Intrinsic::x86_sse3_hadd_ps:
12359 case Intrinsic::x86_sse3_hadd_pd:
12360 case Intrinsic::x86_avx_hadd_ps_256:
12361 case Intrinsic::x86_avx_hadd_pd_256:
12362 Opcode = X86ISD::FHADD;
12364 case Intrinsic::x86_sse3_hsub_ps:
12365 case Intrinsic::x86_sse3_hsub_pd:
12366 case Intrinsic::x86_avx_hsub_ps_256:
12367 case Intrinsic::x86_avx_hsub_pd_256:
12368 Opcode = X86ISD::FHSUB;
12370 case Intrinsic::x86_ssse3_phadd_w_128:
12371 case Intrinsic::x86_ssse3_phadd_d_128:
12372 case Intrinsic::x86_avx2_phadd_w:
12373 case Intrinsic::x86_avx2_phadd_d:
12374 Opcode = X86ISD::HADD;
12376 case Intrinsic::x86_ssse3_phsub_w_128:
12377 case Intrinsic::x86_ssse3_phsub_d_128:
12378 case Intrinsic::x86_avx2_phsub_w:
12379 case Intrinsic::x86_avx2_phsub_d:
12380 Opcode = X86ISD::HSUB;
12383 return DAG.getNode(Opcode, dl, Op.getValueType(),
12384 Op.getOperand(1), Op.getOperand(2));
12387 // SSE2/SSE41/AVX2 integer max/min intrinsics.
12388 case Intrinsic::x86_sse2_pmaxu_b:
12389 case Intrinsic::x86_sse41_pmaxuw:
12390 case Intrinsic::x86_sse41_pmaxud:
12391 case Intrinsic::x86_avx2_pmaxu_b:
12392 case Intrinsic::x86_avx2_pmaxu_w:
12393 case Intrinsic::x86_avx2_pmaxu_d:
12394 case Intrinsic::x86_sse2_pminu_b:
12395 case Intrinsic::x86_sse41_pminuw:
12396 case Intrinsic::x86_sse41_pminud:
12397 case Intrinsic::x86_avx2_pminu_b:
12398 case Intrinsic::x86_avx2_pminu_w:
12399 case Intrinsic::x86_avx2_pminu_d:
12400 case Intrinsic::x86_sse41_pmaxsb:
12401 case Intrinsic::x86_sse2_pmaxs_w:
12402 case Intrinsic::x86_sse41_pmaxsd:
12403 case Intrinsic::x86_avx2_pmaxs_b:
12404 case Intrinsic::x86_avx2_pmaxs_w:
12405 case Intrinsic::x86_avx2_pmaxs_d:
12406 case Intrinsic::x86_sse41_pminsb:
12407 case Intrinsic::x86_sse2_pmins_w:
12408 case Intrinsic::x86_sse41_pminsd:
12409 case Intrinsic::x86_avx2_pmins_b:
12410 case Intrinsic::x86_avx2_pmins_w:
12411 case Intrinsic::x86_avx2_pmins_d: {
12414 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12415 case Intrinsic::x86_sse2_pmaxu_b:
12416 case Intrinsic::x86_sse41_pmaxuw:
12417 case Intrinsic::x86_sse41_pmaxud:
12418 case Intrinsic::x86_avx2_pmaxu_b:
12419 case Intrinsic::x86_avx2_pmaxu_w:
12420 case Intrinsic::x86_avx2_pmaxu_d:
12421 Opcode = X86ISD::UMAX;
12423 case Intrinsic::x86_sse2_pminu_b:
12424 case Intrinsic::x86_sse41_pminuw:
12425 case Intrinsic::x86_sse41_pminud:
12426 case Intrinsic::x86_avx2_pminu_b:
12427 case Intrinsic::x86_avx2_pminu_w:
12428 case Intrinsic::x86_avx2_pminu_d:
12429 Opcode = X86ISD::UMIN;
12431 case Intrinsic::x86_sse41_pmaxsb:
12432 case Intrinsic::x86_sse2_pmaxs_w:
12433 case Intrinsic::x86_sse41_pmaxsd:
12434 case Intrinsic::x86_avx2_pmaxs_b:
12435 case Intrinsic::x86_avx2_pmaxs_w:
12436 case Intrinsic::x86_avx2_pmaxs_d:
12437 Opcode = X86ISD::SMAX;
12439 case Intrinsic::x86_sse41_pminsb:
12440 case Intrinsic::x86_sse2_pmins_w:
12441 case Intrinsic::x86_sse41_pminsd:
12442 case Intrinsic::x86_avx2_pmins_b:
12443 case Intrinsic::x86_avx2_pmins_w:
12444 case Intrinsic::x86_avx2_pmins_d:
12445 Opcode = X86ISD::SMIN;
12448 return DAG.getNode(Opcode, dl, Op.getValueType(),
12449 Op.getOperand(1), Op.getOperand(2));
12452 // SSE/SSE2/AVX floating point max/min intrinsics.
12453 case Intrinsic::x86_sse_max_ps:
12454 case Intrinsic::x86_sse2_max_pd:
12455 case Intrinsic::x86_avx_max_ps_256:
12456 case Intrinsic::x86_avx_max_pd_256:
12457 case Intrinsic::x86_sse_min_ps:
12458 case Intrinsic::x86_sse2_min_pd:
12459 case Intrinsic::x86_avx_min_ps_256:
12460 case Intrinsic::x86_avx_min_pd_256: {
12463 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12464 case Intrinsic::x86_sse_max_ps:
12465 case Intrinsic::x86_sse2_max_pd:
12466 case Intrinsic::x86_avx_max_ps_256:
12467 case Intrinsic::x86_avx_max_pd_256:
12468 Opcode = X86ISD::FMAX;
12470 case Intrinsic::x86_sse_min_ps:
12471 case Intrinsic::x86_sse2_min_pd:
12472 case Intrinsic::x86_avx_min_ps_256:
12473 case Intrinsic::x86_avx_min_pd_256:
12474 Opcode = X86ISD::FMIN;
12477 return DAG.getNode(Opcode, dl, Op.getValueType(),
12478 Op.getOperand(1), Op.getOperand(2));
12481 // AVX2 variable shift intrinsics
12482 case Intrinsic::x86_avx2_psllv_d:
12483 case Intrinsic::x86_avx2_psllv_q:
12484 case Intrinsic::x86_avx2_psllv_d_256:
12485 case Intrinsic::x86_avx2_psllv_q_256:
12486 case Intrinsic::x86_avx2_psrlv_d:
12487 case Intrinsic::x86_avx2_psrlv_q:
12488 case Intrinsic::x86_avx2_psrlv_d_256:
12489 case Intrinsic::x86_avx2_psrlv_q_256:
12490 case Intrinsic::x86_avx2_psrav_d:
12491 case Intrinsic::x86_avx2_psrav_d_256: {
12494 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12495 case Intrinsic::x86_avx2_psllv_d:
12496 case Intrinsic::x86_avx2_psllv_q:
12497 case Intrinsic::x86_avx2_psllv_d_256:
12498 case Intrinsic::x86_avx2_psllv_q_256:
12501 case Intrinsic::x86_avx2_psrlv_d:
12502 case Intrinsic::x86_avx2_psrlv_q:
12503 case Intrinsic::x86_avx2_psrlv_d_256:
12504 case Intrinsic::x86_avx2_psrlv_q_256:
12507 case Intrinsic::x86_avx2_psrav_d:
12508 case Intrinsic::x86_avx2_psrav_d_256:
12512 return DAG.getNode(Opcode, dl, Op.getValueType(),
12513 Op.getOperand(1), Op.getOperand(2));
12516 case Intrinsic::x86_sse2_packssdw_128:
12517 case Intrinsic::x86_sse2_packsswb_128:
12518 case Intrinsic::x86_avx2_packssdw:
12519 case Intrinsic::x86_avx2_packsswb:
12520 return DAG.getNode(X86ISD::PACKSS, dl, Op.getValueType(),
12521 Op.getOperand(1), Op.getOperand(2));
12523 case Intrinsic::x86_sse2_packuswb_128:
12524 case Intrinsic::x86_sse41_packusdw:
12525 case Intrinsic::x86_avx2_packuswb:
12526 case Intrinsic::x86_avx2_packusdw:
12527 return DAG.getNode(X86ISD::PACKUS, dl, Op.getValueType(),
12528 Op.getOperand(1), Op.getOperand(2));
12530 case Intrinsic::x86_ssse3_pshuf_b_128:
12531 case Intrinsic::x86_avx2_pshuf_b:
12532 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
12533 Op.getOperand(1), Op.getOperand(2));
12535 case Intrinsic::x86_ssse3_psign_b_128:
12536 case Intrinsic::x86_ssse3_psign_w_128:
12537 case Intrinsic::x86_ssse3_psign_d_128:
12538 case Intrinsic::x86_avx2_psign_b:
12539 case Intrinsic::x86_avx2_psign_w:
12540 case Intrinsic::x86_avx2_psign_d:
12541 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
12542 Op.getOperand(1), Op.getOperand(2));
12544 case Intrinsic::x86_sse41_insertps:
12545 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
12546 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
12548 case Intrinsic::x86_avx_vperm2f128_ps_256:
12549 case Intrinsic::x86_avx_vperm2f128_pd_256:
12550 case Intrinsic::x86_avx_vperm2f128_si_256:
12551 case Intrinsic::x86_avx2_vperm2i128:
12552 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
12553 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
12555 case Intrinsic::x86_avx2_permd:
12556 case Intrinsic::x86_avx2_permps:
12557 // Operands intentionally swapped. Mask is last operand to intrinsic,
12558 // but second operand for node/instruction.
12559 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
12560 Op.getOperand(2), Op.getOperand(1));
12562 case Intrinsic::x86_sse_sqrt_ps:
12563 case Intrinsic::x86_sse2_sqrt_pd:
12564 case Intrinsic::x86_avx_sqrt_ps_256:
12565 case Intrinsic::x86_avx_sqrt_pd_256:
12566 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
12568 // ptest and testp intrinsics. The intrinsic these come from are designed to
12569 // return an integer value, not just an instruction so lower it to the ptest
12570 // or testp pattern and a setcc for the result.
12571 case Intrinsic::x86_sse41_ptestz:
12572 case Intrinsic::x86_sse41_ptestc:
12573 case Intrinsic::x86_sse41_ptestnzc:
12574 case Intrinsic::x86_avx_ptestz_256:
12575 case Intrinsic::x86_avx_ptestc_256:
12576 case Intrinsic::x86_avx_ptestnzc_256:
12577 case Intrinsic::x86_avx_vtestz_ps:
12578 case Intrinsic::x86_avx_vtestc_ps:
12579 case Intrinsic::x86_avx_vtestnzc_ps:
12580 case Intrinsic::x86_avx_vtestz_pd:
12581 case Intrinsic::x86_avx_vtestc_pd:
12582 case Intrinsic::x86_avx_vtestnzc_pd:
12583 case Intrinsic::x86_avx_vtestz_ps_256:
12584 case Intrinsic::x86_avx_vtestc_ps_256:
12585 case Intrinsic::x86_avx_vtestnzc_ps_256:
12586 case Intrinsic::x86_avx_vtestz_pd_256:
12587 case Intrinsic::x86_avx_vtestc_pd_256:
12588 case Intrinsic::x86_avx_vtestnzc_pd_256: {
12589 bool IsTestPacked = false;
12592 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
12593 case Intrinsic::x86_avx_vtestz_ps:
12594 case Intrinsic::x86_avx_vtestz_pd:
12595 case Intrinsic::x86_avx_vtestz_ps_256:
12596 case Intrinsic::x86_avx_vtestz_pd_256:
12597 IsTestPacked = true; // Fallthrough
12598 case Intrinsic::x86_sse41_ptestz:
12599 case Intrinsic::x86_avx_ptestz_256:
12601 X86CC = X86::COND_E;
12603 case Intrinsic::x86_avx_vtestc_ps:
12604 case Intrinsic::x86_avx_vtestc_pd:
12605 case Intrinsic::x86_avx_vtestc_ps_256:
12606 case Intrinsic::x86_avx_vtestc_pd_256:
12607 IsTestPacked = true; // Fallthrough
12608 case Intrinsic::x86_sse41_ptestc:
12609 case Intrinsic::x86_avx_ptestc_256:
12611 X86CC = X86::COND_B;
12613 case Intrinsic::x86_avx_vtestnzc_ps:
12614 case Intrinsic::x86_avx_vtestnzc_pd:
12615 case Intrinsic::x86_avx_vtestnzc_ps_256:
12616 case Intrinsic::x86_avx_vtestnzc_pd_256:
12617 IsTestPacked = true; // Fallthrough
12618 case Intrinsic::x86_sse41_ptestnzc:
12619 case Intrinsic::x86_avx_ptestnzc_256:
12621 X86CC = X86::COND_A;
12625 SDValue LHS = Op.getOperand(1);
12626 SDValue RHS = Op.getOperand(2);
12627 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
12628 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
12629 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12630 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
12631 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12633 case Intrinsic::x86_avx512_kortestz_w:
12634 case Intrinsic::x86_avx512_kortestc_w: {
12635 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
12636 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
12637 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
12638 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12639 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
12640 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
12641 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12644 // SSE/AVX shift intrinsics
12645 case Intrinsic::x86_sse2_psll_w:
12646 case Intrinsic::x86_sse2_psll_d:
12647 case Intrinsic::x86_sse2_psll_q:
12648 case Intrinsic::x86_avx2_psll_w:
12649 case Intrinsic::x86_avx2_psll_d:
12650 case Intrinsic::x86_avx2_psll_q:
12651 case Intrinsic::x86_sse2_psrl_w:
12652 case Intrinsic::x86_sse2_psrl_d:
12653 case Intrinsic::x86_sse2_psrl_q:
12654 case Intrinsic::x86_avx2_psrl_w:
12655 case Intrinsic::x86_avx2_psrl_d:
12656 case Intrinsic::x86_avx2_psrl_q:
12657 case Intrinsic::x86_sse2_psra_w:
12658 case Intrinsic::x86_sse2_psra_d:
12659 case Intrinsic::x86_avx2_psra_w:
12660 case Intrinsic::x86_avx2_psra_d: {
12663 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12664 case Intrinsic::x86_sse2_psll_w:
12665 case Intrinsic::x86_sse2_psll_d:
12666 case Intrinsic::x86_sse2_psll_q:
12667 case Intrinsic::x86_avx2_psll_w:
12668 case Intrinsic::x86_avx2_psll_d:
12669 case Intrinsic::x86_avx2_psll_q:
12670 Opcode = X86ISD::VSHL;
12672 case Intrinsic::x86_sse2_psrl_w:
12673 case Intrinsic::x86_sse2_psrl_d:
12674 case Intrinsic::x86_sse2_psrl_q:
12675 case Intrinsic::x86_avx2_psrl_w:
12676 case Intrinsic::x86_avx2_psrl_d:
12677 case Intrinsic::x86_avx2_psrl_q:
12678 Opcode = X86ISD::VSRL;
12680 case Intrinsic::x86_sse2_psra_w:
12681 case Intrinsic::x86_sse2_psra_d:
12682 case Intrinsic::x86_avx2_psra_w:
12683 case Intrinsic::x86_avx2_psra_d:
12684 Opcode = X86ISD::VSRA;
12687 return DAG.getNode(Opcode, dl, Op.getValueType(),
12688 Op.getOperand(1), Op.getOperand(2));
12691 // SSE/AVX immediate shift intrinsics
12692 case Intrinsic::x86_sse2_pslli_w:
12693 case Intrinsic::x86_sse2_pslli_d:
12694 case Intrinsic::x86_sse2_pslli_q:
12695 case Intrinsic::x86_avx2_pslli_w:
12696 case Intrinsic::x86_avx2_pslli_d:
12697 case Intrinsic::x86_avx2_pslli_q:
12698 case Intrinsic::x86_sse2_psrli_w:
12699 case Intrinsic::x86_sse2_psrli_d:
12700 case Intrinsic::x86_sse2_psrli_q:
12701 case Intrinsic::x86_avx2_psrli_w:
12702 case Intrinsic::x86_avx2_psrli_d:
12703 case Intrinsic::x86_avx2_psrli_q:
12704 case Intrinsic::x86_sse2_psrai_w:
12705 case Intrinsic::x86_sse2_psrai_d:
12706 case Intrinsic::x86_avx2_psrai_w:
12707 case Intrinsic::x86_avx2_psrai_d: {
12710 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12711 case Intrinsic::x86_sse2_pslli_w:
12712 case Intrinsic::x86_sse2_pslli_d:
12713 case Intrinsic::x86_sse2_pslli_q:
12714 case Intrinsic::x86_avx2_pslli_w:
12715 case Intrinsic::x86_avx2_pslli_d:
12716 case Intrinsic::x86_avx2_pslli_q:
12717 Opcode = X86ISD::VSHLI;
12719 case Intrinsic::x86_sse2_psrli_w:
12720 case Intrinsic::x86_sse2_psrli_d:
12721 case Intrinsic::x86_sse2_psrli_q:
12722 case Intrinsic::x86_avx2_psrli_w:
12723 case Intrinsic::x86_avx2_psrli_d:
12724 case Intrinsic::x86_avx2_psrli_q:
12725 Opcode = X86ISD::VSRLI;
12727 case Intrinsic::x86_sse2_psrai_w:
12728 case Intrinsic::x86_sse2_psrai_d:
12729 case Intrinsic::x86_avx2_psrai_w:
12730 case Intrinsic::x86_avx2_psrai_d:
12731 Opcode = X86ISD::VSRAI;
12734 return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
12735 Op.getOperand(1), Op.getOperand(2), DAG);
12738 case Intrinsic::x86_sse42_pcmpistria128:
12739 case Intrinsic::x86_sse42_pcmpestria128:
12740 case Intrinsic::x86_sse42_pcmpistric128:
12741 case Intrinsic::x86_sse42_pcmpestric128:
12742 case Intrinsic::x86_sse42_pcmpistrio128:
12743 case Intrinsic::x86_sse42_pcmpestrio128:
12744 case Intrinsic::x86_sse42_pcmpistris128:
12745 case Intrinsic::x86_sse42_pcmpestris128:
12746 case Intrinsic::x86_sse42_pcmpistriz128:
12747 case Intrinsic::x86_sse42_pcmpestriz128: {
12751 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12752 case Intrinsic::x86_sse42_pcmpistria128:
12753 Opcode = X86ISD::PCMPISTRI;
12754 X86CC = X86::COND_A;
12756 case Intrinsic::x86_sse42_pcmpestria128:
12757 Opcode = X86ISD::PCMPESTRI;
12758 X86CC = X86::COND_A;
12760 case Intrinsic::x86_sse42_pcmpistric128:
12761 Opcode = X86ISD::PCMPISTRI;
12762 X86CC = X86::COND_B;
12764 case Intrinsic::x86_sse42_pcmpestric128:
12765 Opcode = X86ISD::PCMPESTRI;
12766 X86CC = X86::COND_B;
12768 case Intrinsic::x86_sse42_pcmpistrio128:
12769 Opcode = X86ISD::PCMPISTRI;
12770 X86CC = X86::COND_O;
12772 case Intrinsic::x86_sse42_pcmpestrio128:
12773 Opcode = X86ISD::PCMPESTRI;
12774 X86CC = X86::COND_O;
12776 case Intrinsic::x86_sse42_pcmpistris128:
12777 Opcode = X86ISD::PCMPISTRI;
12778 X86CC = X86::COND_S;
12780 case Intrinsic::x86_sse42_pcmpestris128:
12781 Opcode = X86ISD::PCMPESTRI;
12782 X86CC = X86::COND_S;
12784 case Intrinsic::x86_sse42_pcmpistriz128:
12785 Opcode = X86ISD::PCMPISTRI;
12786 X86CC = X86::COND_E;
12788 case Intrinsic::x86_sse42_pcmpestriz128:
12789 Opcode = X86ISD::PCMPESTRI;
12790 X86CC = X86::COND_E;
12793 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12794 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12795 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
12796 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12797 DAG.getConstant(X86CC, MVT::i8),
12798 SDValue(PCMP.getNode(), 1));
12799 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12802 case Intrinsic::x86_sse42_pcmpistri128:
12803 case Intrinsic::x86_sse42_pcmpestri128: {
12805 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
12806 Opcode = X86ISD::PCMPISTRI;
12808 Opcode = X86ISD::PCMPESTRI;
12810 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12811 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12812 return DAG.getNode(Opcode, dl, VTs, NewOps);
12814 case Intrinsic::x86_fma_vfmadd_ps:
12815 case Intrinsic::x86_fma_vfmadd_pd:
12816 case Intrinsic::x86_fma_vfmsub_ps:
12817 case Intrinsic::x86_fma_vfmsub_pd:
12818 case Intrinsic::x86_fma_vfnmadd_ps:
12819 case Intrinsic::x86_fma_vfnmadd_pd:
12820 case Intrinsic::x86_fma_vfnmsub_ps:
12821 case Intrinsic::x86_fma_vfnmsub_pd:
12822 case Intrinsic::x86_fma_vfmaddsub_ps:
12823 case Intrinsic::x86_fma_vfmaddsub_pd:
12824 case Intrinsic::x86_fma_vfmsubadd_ps:
12825 case Intrinsic::x86_fma_vfmsubadd_pd:
12826 case Intrinsic::x86_fma_vfmadd_ps_256:
12827 case Intrinsic::x86_fma_vfmadd_pd_256:
12828 case Intrinsic::x86_fma_vfmsub_ps_256:
12829 case Intrinsic::x86_fma_vfmsub_pd_256:
12830 case Intrinsic::x86_fma_vfnmadd_ps_256:
12831 case Intrinsic::x86_fma_vfnmadd_pd_256:
12832 case Intrinsic::x86_fma_vfnmsub_ps_256:
12833 case Intrinsic::x86_fma_vfnmsub_pd_256:
12834 case Intrinsic::x86_fma_vfmaddsub_ps_256:
12835 case Intrinsic::x86_fma_vfmaddsub_pd_256:
12836 case Intrinsic::x86_fma_vfmsubadd_ps_256:
12837 case Intrinsic::x86_fma_vfmsubadd_pd_256:
12838 case Intrinsic::x86_fma_vfmadd_ps_512:
12839 case Intrinsic::x86_fma_vfmadd_pd_512:
12840 case Intrinsic::x86_fma_vfmsub_ps_512:
12841 case Intrinsic::x86_fma_vfmsub_pd_512:
12842 case Intrinsic::x86_fma_vfnmadd_ps_512:
12843 case Intrinsic::x86_fma_vfnmadd_pd_512:
12844 case Intrinsic::x86_fma_vfnmsub_ps_512:
12845 case Intrinsic::x86_fma_vfnmsub_pd_512:
12846 case Intrinsic::x86_fma_vfmaddsub_ps_512:
12847 case Intrinsic::x86_fma_vfmaddsub_pd_512:
12848 case Intrinsic::x86_fma_vfmsubadd_ps_512:
12849 case Intrinsic::x86_fma_vfmsubadd_pd_512: {
12852 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12853 case Intrinsic::x86_fma_vfmadd_ps:
12854 case Intrinsic::x86_fma_vfmadd_pd:
12855 case Intrinsic::x86_fma_vfmadd_ps_256:
12856 case Intrinsic::x86_fma_vfmadd_pd_256:
12857 case Intrinsic::x86_fma_vfmadd_ps_512:
12858 case Intrinsic::x86_fma_vfmadd_pd_512:
12859 Opc = X86ISD::FMADD;
12861 case Intrinsic::x86_fma_vfmsub_ps:
12862 case Intrinsic::x86_fma_vfmsub_pd:
12863 case Intrinsic::x86_fma_vfmsub_ps_256:
12864 case Intrinsic::x86_fma_vfmsub_pd_256:
12865 case Intrinsic::x86_fma_vfmsub_ps_512:
12866 case Intrinsic::x86_fma_vfmsub_pd_512:
12867 Opc = X86ISD::FMSUB;
12869 case Intrinsic::x86_fma_vfnmadd_ps:
12870 case Intrinsic::x86_fma_vfnmadd_pd:
12871 case Intrinsic::x86_fma_vfnmadd_ps_256:
12872 case Intrinsic::x86_fma_vfnmadd_pd_256:
12873 case Intrinsic::x86_fma_vfnmadd_ps_512:
12874 case Intrinsic::x86_fma_vfnmadd_pd_512:
12875 Opc = X86ISD::FNMADD;
12877 case Intrinsic::x86_fma_vfnmsub_ps:
12878 case Intrinsic::x86_fma_vfnmsub_pd:
12879 case Intrinsic::x86_fma_vfnmsub_ps_256:
12880 case Intrinsic::x86_fma_vfnmsub_pd_256:
12881 case Intrinsic::x86_fma_vfnmsub_ps_512:
12882 case Intrinsic::x86_fma_vfnmsub_pd_512:
12883 Opc = X86ISD::FNMSUB;
12885 case Intrinsic::x86_fma_vfmaddsub_ps:
12886 case Intrinsic::x86_fma_vfmaddsub_pd:
12887 case Intrinsic::x86_fma_vfmaddsub_ps_256:
12888 case Intrinsic::x86_fma_vfmaddsub_pd_256:
12889 case Intrinsic::x86_fma_vfmaddsub_ps_512:
12890 case Intrinsic::x86_fma_vfmaddsub_pd_512:
12891 Opc = X86ISD::FMADDSUB;
12893 case Intrinsic::x86_fma_vfmsubadd_ps:
12894 case Intrinsic::x86_fma_vfmsubadd_pd:
12895 case Intrinsic::x86_fma_vfmsubadd_ps_256:
12896 case Intrinsic::x86_fma_vfmsubadd_pd_256:
12897 case Intrinsic::x86_fma_vfmsubadd_ps_512:
12898 case Intrinsic::x86_fma_vfmsubadd_pd_512:
12899 Opc = X86ISD::FMSUBADD;
12903 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
12904 Op.getOperand(2), Op.getOperand(3));
12909 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12910 SDValue Src, SDValue Mask, SDValue Base,
12911 SDValue Index, SDValue ScaleOp, SDValue Chain,
12912 const X86Subtarget * Subtarget) {
12914 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12915 assert(C && "Invalid scale type");
12916 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12917 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12918 Index.getSimpleValueType().getVectorNumElements());
12920 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12922 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12924 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12925 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12926 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12927 SDValue Segment = DAG.getRegister(0, MVT::i32);
12928 if (Src.getOpcode() == ISD::UNDEF)
12929 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12930 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12931 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12932 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12933 return DAG.getMergeValues(RetOps, dl);
12936 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12937 SDValue Src, SDValue Mask, SDValue Base,
12938 SDValue Index, SDValue ScaleOp, SDValue Chain) {
12940 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12941 assert(C && "Invalid scale type");
12942 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12943 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12944 SDValue Segment = DAG.getRegister(0, MVT::i32);
12945 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12946 Index.getSimpleValueType().getVectorNumElements());
12948 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12950 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12952 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12953 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12954 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12955 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12956 return SDValue(Res, 1);
12959 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12960 SDValue Mask, SDValue Base, SDValue Index,
12961 SDValue ScaleOp, SDValue Chain) {
12963 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12964 assert(C && "Invalid scale type");
12965 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12966 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12967 SDValue Segment = DAG.getRegister(0, MVT::i32);
12969 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
12971 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12973 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12975 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12976 //SDVTList VTs = DAG.getVTList(MVT::Other);
12977 SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12978 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
12979 return SDValue(Res, 0);
12982 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
12983 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
12984 // also used to custom lower READCYCLECOUNTER nodes.
12985 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
12986 SelectionDAG &DAG, const X86Subtarget *Subtarget,
12987 SmallVectorImpl<SDValue> &Results) {
12988 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12989 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
12992 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
12993 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
12994 // and the EAX register is loaded with the low-order 32 bits.
12995 if (Subtarget->is64Bit()) {
12996 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
12997 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
13000 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
13001 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
13004 SDValue Chain = HI.getValue(1);
13006 if (Opcode == X86ISD::RDTSCP_DAG) {
13007 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
13009 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
13010 // the ECX register. Add 'ecx' explicitly to the chain.
13011 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
13013 // Explicitly store the content of ECX at the location passed in input
13014 // to the 'rdtscp' intrinsic.
13015 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
13016 MachinePointerInfo(), false, false, 0);
13019 if (Subtarget->is64Bit()) {
13020 // The EDX register is loaded with the high-order 32 bits of the MSR, and
13021 // the EAX register is loaded with the low-order 32 bits.
13022 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
13023 DAG.getConstant(32, MVT::i8));
13024 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
13025 Results.push_back(Chain);
13029 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
13030 SDValue Ops[] = { LO, HI };
13031 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
13032 Results.push_back(Pair);
13033 Results.push_back(Chain);
13036 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
13037 SelectionDAG &DAG) {
13038 SmallVector<SDValue, 2> Results;
13040 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
13042 return DAG.getMergeValues(Results, DL);
13045 enum IntrinsicType {
13046 GATHER, SCATTER, PREFETCH, RDSEED, RDRAND, RDTSC, XTEST
13049 struct IntrinsicData {
13050 IntrinsicData(IntrinsicType IType, unsigned IOpc0, unsigned IOpc1)
13051 :Type(IType), Opc0(IOpc0), Opc1(IOpc1) {}
13052 IntrinsicType Type;
13057 std::map < unsigned, IntrinsicData> IntrMap;
13058 static void InitIntinsicsMap() {
13059 static bool Initialized = false;
13062 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
13063 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
13064 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
13065 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
13066 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpd_512,
13067 IntrinsicData(GATHER, X86::VGATHERQPDZrm, 0)));
13068 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpd_512,
13069 IntrinsicData(GATHER, X86::VGATHERDPDZrm, 0)));
13070 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dps_512,
13071 IntrinsicData(GATHER, X86::VGATHERDPSZrm, 0)));
13072 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpi_512,
13073 IntrinsicData(GATHER, X86::VPGATHERQDZrm, 0)));
13074 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpq_512,
13075 IntrinsicData(GATHER, X86::VPGATHERQQZrm, 0)));
13076 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpi_512,
13077 IntrinsicData(GATHER, X86::VPGATHERDDZrm, 0)));
13078 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpq_512,
13079 IntrinsicData(GATHER, X86::VPGATHERDQZrm, 0)));
13081 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qps_512,
13082 IntrinsicData(SCATTER, X86::VSCATTERQPSZmr, 0)));
13083 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpd_512,
13084 IntrinsicData(SCATTER, X86::VSCATTERQPDZmr, 0)));
13085 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpd_512,
13086 IntrinsicData(SCATTER, X86::VSCATTERDPDZmr, 0)));
13087 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dps_512,
13088 IntrinsicData(SCATTER, X86::VSCATTERDPSZmr, 0)));
13089 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpi_512,
13090 IntrinsicData(SCATTER, X86::VPSCATTERQDZmr, 0)));
13091 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpq_512,
13092 IntrinsicData(SCATTER, X86::VPSCATTERQQZmr, 0)));
13093 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpi_512,
13094 IntrinsicData(SCATTER, X86::VPSCATTERDDZmr, 0)));
13095 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpq_512,
13096 IntrinsicData(SCATTER, X86::VPSCATTERDQZmr, 0)));
13098 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qps_512,
13099 IntrinsicData(PREFETCH, X86::VGATHERPF0QPSm,
13100 X86::VGATHERPF1QPSm)));
13101 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qpd_512,
13102 IntrinsicData(PREFETCH, X86::VGATHERPF0QPDm,
13103 X86::VGATHERPF1QPDm)));
13104 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dpd_512,
13105 IntrinsicData(PREFETCH, X86::VGATHERPF0DPDm,
13106 X86::VGATHERPF1DPDm)));
13107 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dps_512,
13108 IntrinsicData(PREFETCH, X86::VGATHERPF0DPSm,
13109 X86::VGATHERPF1DPSm)));
13110 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qps_512,
13111 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPSm,
13112 X86::VSCATTERPF1QPSm)));
13113 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qpd_512,
13114 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPDm,
13115 X86::VSCATTERPF1QPDm)));
13116 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dpd_512,
13117 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPDm,
13118 X86::VSCATTERPF1DPDm)));
13119 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dps_512,
13120 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPSm,
13121 X86::VSCATTERPF1DPSm)));
13122 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_16,
13123 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
13124 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_32,
13125 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
13126 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_64,
13127 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
13128 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_16,
13129 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
13130 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_32,
13131 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
13132 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_64,
13133 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
13134 IntrMap.insert(std::make_pair(Intrinsic::x86_xtest,
13135 IntrinsicData(XTEST, X86ISD::XTEST, 0)));
13136 IntrMap.insert(std::make_pair(Intrinsic::x86_rdtsc,
13137 IntrinsicData(RDTSC, X86ISD::RDTSC_DAG, 0)));
13138 IntrMap.insert(std::make_pair(Intrinsic::x86_rdtscp,
13139 IntrinsicData(RDTSC, X86ISD::RDTSCP_DAG, 0)));
13140 Initialized = true;
13143 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
13144 SelectionDAG &DAG) {
13145 InitIntinsicsMap();
13146 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
13147 std::map < unsigned, IntrinsicData>::const_iterator itr = IntrMap.find(IntNo);
13148 if (itr == IntrMap.end())
13152 IntrinsicData Intr = itr->second;
13153 switch(Intr.Type) {
13156 // Emit the node with the right value type.
13157 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
13158 SDValue Result = DAG.getNode(Intr.Opc0, dl, VTs, Op.getOperand(0));
13160 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
13161 // Otherwise return the value from Rand, which is always 0, casted to i32.
13162 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
13163 DAG.getConstant(1, Op->getValueType(1)),
13164 DAG.getConstant(X86::COND_B, MVT::i32),
13165 SDValue(Result.getNode(), 1) };
13166 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
13167 DAG.getVTList(Op->getValueType(1), MVT::Glue),
13170 // Return { result, isValid, chain }.
13171 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
13172 SDValue(Result.getNode(), 2));
13175 //gather(v1, mask, index, base, scale);
13176 SDValue Chain = Op.getOperand(0);
13177 SDValue Src = Op.getOperand(2);
13178 SDValue Base = Op.getOperand(3);
13179 SDValue Index = Op.getOperand(4);
13180 SDValue Mask = Op.getOperand(5);
13181 SDValue Scale = Op.getOperand(6);
13182 return getGatherNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
13186 //scatter(base, mask, index, v1, scale);
13187 SDValue Chain = Op.getOperand(0);
13188 SDValue Base = Op.getOperand(2);
13189 SDValue Mask = Op.getOperand(3);
13190 SDValue Index = Op.getOperand(4);
13191 SDValue Src = Op.getOperand(5);
13192 SDValue Scale = Op.getOperand(6);
13193 return getScatterNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
13196 SDValue Hint = Op.getOperand(6);
13198 if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
13199 (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
13200 llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
13201 unsigned Opcode = (HintVal ? Intr.Opc1 : Intr.Opc0);
13202 SDValue Chain = Op.getOperand(0);
13203 SDValue Mask = Op.getOperand(2);
13204 SDValue Index = Op.getOperand(3);
13205 SDValue Base = Op.getOperand(4);
13206 SDValue Scale = Op.getOperand(5);
13207 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
13209 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
13211 SmallVector<SDValue, 2> Results;
13212 getReadTimeStampCounter(Op.getNode(), dl, Intr.Opc0, DAG, Subtarget, Results);
13213 return DAG.getMergeValues(Results, dl);
13215 // XTEST intrinsics.
13217 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
13218 SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
13219 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13220 DAG.getConstant(X86::COND_NE, MVT::i8),
13222 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
13223 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
13224 Ret, SDValue(InTrans.getNode(), 1));
13227 llvm_unreachable("Unknown Intrinsic Type");
13230 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
13231 SelectionDAG &DAG) const {
13232 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13233 MFI->setReturnAddressIsTaken(true);
13235 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
13238 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13240 EVT PtrVT = getPointerTy();
13243 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
13244 const X86RegisterInfo *RegInfo =
13245 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13246 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
13247 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
13248 DAG.getNode(ISD::ADD, dl, PtrVT,
13249 FrameAddr, Offset),
13250 MachinePointerInfo(), false, false, false, 0);
13253 // Just load the return address.
13254 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
13255 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
13256 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
13259 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
13260 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13261 MFI->setFrameAddressIsTaken(true);
13263 EVT VT = Op.getValueType();
13264 SDLoc dl(Op); // FIXME probably not meaningful
13265 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13266 const X86RegisterInfo *RegInfo =
13267 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13268 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
13269 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
13270 (FrameReg == X86::EBP && VT == MVT::i32)) &&
13271 "Invalid Frame Register!");
13272 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
13274 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
13275 MachinePointerInfo(),
13276 false, false, false, 0);
13280 // FIXME? Maybe this could be a TableGen attribute on some registers and
13281 // this table could be generated automatically from RegInfo.
13282 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
13284 unsigned Reg = StringSwitch<unsigned>(RegName)
13285 .Case("esp", X86::ESP)
13286 .Case("rsp", X86::RSP)
13290 report_fatal_error("Invalid register name global variable");
13293 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
13294 SelectionDAG &DAG) const {
13295 const X86RegisterInfo *RegInfo =
13296 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13297 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
13300 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
13301 SDValue Chain = Op.getOperand(0);
13302 SDValue Offset = Op.getOperand(1);
13303 SDValue Handler = Op.getOperand(2);
13306 EVT PtrVT = getPointerTy();
13307 const X86RegisterInfo *RegInfo =
13308 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13309 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
13310 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
13311 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
13312 "Invalid Frame Register!");
13313 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
13314 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
13316 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
13317 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
13318 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
13319 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
13321 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
13323 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
13324 DAG.getRegister(StoreAddrReg, PtrVT));
13327 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
13328 SelectionDAG &DAG) const {
13330 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
13331 DAG.getVTList(MVT::i32, MVT::Other),
13332 Op.getOperand(0), Op.getOperand(1));
13335 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
13336 SelectionDAG &DAG) const {
13338 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
13339 Op.getOperand(0), Op.getOperand(1));
13342 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
13343 return Op.getOperand(0);
13346 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
13347 SelectionDAG &DAG) const {
13348 SDValue Root = Op.getOperand(0);
13349 SDValue Trmp = Op.getOperand(1); // trampoline
13350 SDValue FPtr = Op.getOperand(2); // nested function
13351 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
13354 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
13355 const TargetRegisterInfo* TRI = DAG.getTarget().getRegisterInfo();
13357 if (Subtarget->is64Bit()) {
13358 SDValue OutChains[6];
13360 // Large code-model.
13361 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
13362 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
13364 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
13365 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
13367 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
13369 // Load the pointer to the nested function into R11.
13370 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
13371 SDValue Addr = Trmp;
13372 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13373 Addr, MachinePointerInfo(TrmpAddr),
13376 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13377 DAG.getConstant(2, MVT::i64));
13378 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
13379 MachinePointerInfo(TrmpAddr, 2),
13382 // Load the 'nest' parameter value into R10.
13383 // R10 is specified in X86CallingConv.td
13384 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
13385 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13386 DAG.getConstant(10, MVT::i64));
13387 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13388 Addr, MachinePointerInfo(TrmpAddr, 10),
13391 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13392 DAG.getConstant(12, MVT::i64));
13393 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
13394 MachinePointerInfo(TrmpAddr, 12),
13397 // Jump to the nested function.
13398 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
13399 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13400 DAG.getConstant(20, MVT::i64));
13401 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13402 Addr, MachinePointerInfo(TrmpAddr, 20),
13405 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
13406 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13407 DAG.getConstant(22, MVT::i64));
13408 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
13409 MachinePointerInfo(TrmpAddr, 22),
13412 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
13414 const Function *Func =
13415 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
13416 CallingConv::ID CC = Func->getCallingConv();
13421 llvm_unreachable("Unsupported calling convention");
13422 case CallingConv::C:
13423 case CallingConv::X86_StdCall: {
13424 // Pass 'nest' parameter in ECX.
13425 // Must be kept in sync with X86CallingConv.td
13426 NestReg = X86::ECX;
13428 // Check that ECX wasn't needed by an 'inreg' parameter.
13429 FunctionType *FTy = Func->getFunctionType();
13430 const AttributeSet &Attrs = Func->getAttributes();
13432 if (!Attrs.isEmpty() && !Func->isVarArg()) {
13433 unsigned InRegCount = 0;
13436 for (FunctionType::param_iterator I = FTy->param_begin(),
13437 E = FTy->param_end(); I != E; ++I, ++Idx)
13438 if (Attrs.hasAttribute(Idx, Attribute::InReg))
13439 // FIXME: should only count parameters that are lowered to integers.
13440 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
13442 if (InRegCount > 2) {
13443 report_fatal_error("Nest register in use - reduce number of inreg"
13449 case CallingConv::X86_FastCall:
13450 case CallingConv::X86_ThisCall:
13451 case CallingConv::Fast:
13452 // Pass 'nest' parameter in EAX.
13453 // Must be kept in sync with X86CallingConv.td
13454 NestReg = X86::EAX;
13458 SDValue OutChains[4];
13459 SDValue Addr, Disp;
13461 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13462 DAG.getConstant(10, MVT::i32));
13463 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
13465 // This is storing the opcode for MOV32ri.
13466 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
13467 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
13468 OutChains[0] = DAG.getStore(Root, dl,
13469 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
13470 Trmp, MachinePointerInfo(TrmpAddr),
13473 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13474 DAG.getConstant(1, MVT::i32));
13475 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
13476 MachinePointerInfo(TrmpAddr, 1),
13479 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
13480 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13481 DAG.getConstant(5, MVT::i32));
13482 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
13483 MachinePointerInfo(TrmpAddr, 5),
13486 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13487 DAG.getConstant(6, MVT::i32));
13488 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
13489 MachinePointerInfo(TrmpAddr, 6),
13492 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
13496 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
13497 SelectionDAG &DAG) const {
13499 The rounding mode is in bits 11:10 of FPSR, and has the following
13501 00 Round to nearest
13506 FLT_ROUNDS, on the other hand, expects the following:
13513 To perform the conversion, we do:
13514 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
13517 MachineFunction &MF = DAG.getMachineFunction();
13518 const TargetMachine &TM = MF.getTarget();
13519 const TargetFrameLowering &TFI = *TM.getFrameLowering();
13520 unsigned StackAlignment = TFI.getStackAlignment();
13521 MVT VT = Op.getSimpleValueType();
13524 // Save FP Control Word to stack slot
13525 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
13526 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
13528 MachineMemOperand *MMO =
13529 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
13530 MachineMemOperand::MOStore, 2, 2);
13532 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
13533 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
13534 DAG.getVTList(MVT::Other),
13535 Ops, MVT::i16, MMO);
13537 // Load FP Control Word from stack slot
13538 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
13539 MachinePointerInfo(), false, false, false, 0);
13541 // Transform as necessary
13543 DAG.getNode(ISD::SRL, DL, MVT::i16,
13544 DAG.getNode(ISD::AND, DL, MVT::i16,
13545 CWD, DAG.getConstant(0x800, MVT::i16)),
13546 DAG.getConstant(11, MVT::i8));
13548 DAG.getNode(ISD::SRL, DL, MVT::i16,
13549 DAG.getNode(ISD::AND, DL, MVT::i16,
13550 CWD, DAG.getConstant(0x400, MVT::i16)),
13551 DAG.getConstant(9, MVT::i8));
13554 DAG.getNode(ISD::AND, DL, MVT::i16,
13555 DAG.getNode(ISD::ADD, DL, MVT::i16,
13556 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
13557 DAG.getConstant(1, MVT::i16)),
13558 DAG.getConstant(3, MVT::i16));
13560 return DAG.getNode((VT.getSizeInBits() < 16 ?
13561 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
13564 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
13565 MVT VT = Op.getSimpleValueType();
13567 unsigned NumBits = VT.getSizeInBits();
13570 Op = Op.getOperand(0);
13571 if (VT == MVT::i8) {
13572 // Zero extend to i32 since there is not an i8 bsr.
13574 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13577 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
13578 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13579 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13581 // If src is zero (i.e. bsr sets ZF), returns NumBits.
13584 DAG.getConstant(NumBits+NumBits-1, OpVT),
13585 DAG.getConstant(X86::COND_E, MVT::i8),
13588 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
13590 // Finally xor with NumBits-1.
13591 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13594 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13598 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
13599 MVT VT = Op.getSimpleValueType();
13601 unsigned NumBits = VT.getSizeInBits();
13604 Op = Op.getOperand(0);
13605 if (VT == MVT::i8) {
13606 // Zero extend to i32 since there is not an i8 bsr.
13608 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13611 // Issue a bsr (scan bits in reverse).
13612 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13613 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13615 // And xor with NumBits-1.
13616 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13619 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13623 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
13624 MVT VT = Op.getSimpleValueType();
13625 unsigned NumBits = VT.getSizeInBits();
13627 Op = Op.getOperand(0);
13629 // Issue a bsf (scan bits forward) which also sets EFLAGS.
13630 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13631 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
13633 // If src is zero (i.e. bsf sets ZF), returns NumBits.
13636 DAG.getConstant(NumBits, VT),
13637 DAG.getConstant(X86::COND_E, MVT::i8),
13640 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
13643 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
13644 // ones, and then concatenate the result back.
13645 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
13646 MVT VT = Op.getSimpleValueType();
13648 assert(VT.is256BitVector() && VT.isInteger() &&
13649 "Unsupported value type for operation");
13651 unsigned NumElems = VT.getVectorNumElements();
13654 // Extract the LHS vectors
13655 SDValue LHS = Op.getOperand(0);
13656 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13657 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13659 // Extract the RHS vectors
13660 SDValue RHS = Op.getOperand(1);
13661 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13662 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13664 MVT EltVT = VT.getVectorElementType();
13665 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13667 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13668 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
13669 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
13672 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
13673 assert(Op.getSimpleValueType().is256BitVector() &&
13674 Op.getSimpleValueType().isInteger() &&
13675 "Only handle AVX 256-bit vector integer operation");
13676 return Lower256IntArith(Op, DAG);
13679 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
13680 assert(Op.getSimpleValueType().is256BitVector() &&
13681 Op.getSimpleValueType().isInteger() &&
13682 "Only handle AVX 256-bit vector integer operation");
13683 return Lower256IntArith(Op, DAG);
13686 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
13687 SelectionDAG &DAG) {
13689 MVT VT = Op.getSimpleValueType();
13691 // Decompose 256-bit ops into smaller 128-bit ops.
13692 if (VT.is256BitVector() && !Subtarget->hasInt256())
13693 return Lower256IntArith(Op, DAG);
13695 SDValue A = Op.getOperand(0);
13696 SDValue B = Op.getOperand(1);
13698 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
13699 if (VT == MVT::v4i32) {
13700 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
13701 "Should not custom lower when pmuldq is available!");
13703 // Extract the odd parts.
13704 static const int UnpackMask[] = { 1, -1, 3, -1 };
13705 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
13706 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
13708 // Multiply the even parts.
13709 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
13710 // Now multiply odd parts.
13711 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
13713 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
13714 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
13716 // Merge the two vectors back together with a shuffle. This expands into 2
13718 static const int ShufMask[] = { 0, 4, 2, 6 };
13719 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
13722 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
13723 "Only know how to lower V2I64/V4I64/V8I64 multiply");
13725 // Ahi = psrlqi(a, 32);
13726 // Bhi = psrlqi(b, 32);
13728 // AloBlo = pmuludq(a, b);
13729 // AloBhi = pmuludq(a, Bhi);
13730 // AhiBlo = pmuludq(Ahi, b);
13732 // AloBhi = psllqi(AloBhi, 32);
13733 // AhiBlo = psllqi(AhiBlo, 32);
13734 // return AloBlo + AloBhi + AhiBlo;
13736 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
13737 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
13739 // Bit cast to 32-bit vectors for MULUDQ
13740 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
13741 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
13742 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
13743 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
13744 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
13745 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
13747 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
13748 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
13749 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
13751 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
13752 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
13754 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
13755 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
13758 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
13759 assert(Subtarget->isTargetWin64() && "Unexpected target");
13760 EVT VT = Op.getValueType();
13761 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
13762 "Unexpected return type for lowering");
13766 switch (Op->getOpcode()) {
13767 default: llvm_unreachable("Unexpected request for libcall!");
13768 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
13769 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
13770 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
13771 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
13772 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
13773 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
13777 SDValue InChain = DAG.getEntryNode();
13779 TargetLowering::ArgListTy Args;
13780 TargetLowering::ArgListEntry Entry;
13781 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
13782 EVT ArgVT = Op->getOperand(i).getValueType();
13783 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
13784 "Unexpected argument type for lowering");
13785 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
13786 Entry.Node = StackPtr;
13787 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
13789 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13790 Entry.Ty = PointerType::get(ArgTy,0);
13791 Entry.isSExt = false;
13792 Entry.isZExt = false;
13793 Args.push_back(Entry);
13796 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
13799 TargetLowering::CallLoweringInfo CLI(DAG);
13800 CLI.setDebugLoc(dl).setChain(InChain)
13801 .setCallee(getLibcallCallingConv(LC),
13802 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
13804 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
13806 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
13807 return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
13810 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
13811 SelectionDAG &DAG) {
13812 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
13813 EVT VT = Op0.getValueType();
13816 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
13817 (VT == MVT::v8i32 && Subtarget->hasInt256()));
13819 // Get the high parts.
13820 const int Mask[] = {1, 2, 3, 4, 5, 6, 7, 8};
13821 SDValue Hi0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
13822 SDValue Hi1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
13824 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
13826 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
13827 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
13829 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
13830 SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
13831 DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
13832 SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
13833 DAG.getNode(Opcode, dl, MulVT, Hi0, Hi1));
13835 // Shuffle it back into the right order.
13836 const int HighMask[] = {1, 5, 3, 7, 9, 13, 11, 15};
13837 SDValue Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
13838 const int LowMask[] = {0, 4, 2, 6, 8, 12, 10, 14};
13839 SDValue Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
13841 // If we have a signed multiply but no PMULDQ fix up the high parts of a
13842 // unsigned multiply.
13843 if (IsSigned && !Subtarget->hasSSE41()) {
13845 DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
13846 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
13847 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
13848 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
13849 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
13851 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
13852 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
13855 return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Highs, Lows);
13858 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
13859 const X86Subtarget *Subtarget) {
13860 MVT VT = Op.getSimpleValueType();
13862 SDValue R = Op.getOperand(0);
13863 SDValue Amt = Op.getOperand(1);
13865 // Optimize shl/srl/sra with constant shift amount.
13866 if (isSplatVector(Amt.getNode())) {
13867 SDValue SclrAmt = Amt->getOperand(0);
13868 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
13869 uint64_t ShiftAmt = C->getZExtValue();
13871 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
13872 (Subtarget->hasInt256() &&
13873 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13874 (Subtarget->hasAVX512() &&
13875 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13876 if (Op.getOpcode() == ISD::SHL)
13877 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13879 if (Op.getOpcode() == ISD::SRL)
13880 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13882 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
13883 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13887 if (VT == MVT::v16i8) {
13888 if (Op.getOpcode() == ISD::SHL) {
13889 // Make a large shift.
13890 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13891 MVT::v8i16, R, ShiftAmt,
13893 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13894 // Zero out the rightmost bits.
13895 SmallVector<SDValue, 16> V(16,
13896 DAG.getConstant(uint8_t(-1U << ShiftAmt),
13898 return DAG.getNode(ISD::AND, dl, VT, SHL,
13899 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13901 if (Op.getOpcode() == ISD::SRL) {
13902 // Make a large shift.
13903 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13904 MVT::v8i16, R, ShiftAmt,
13906 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13907 // Zero out the leftmost bits.
13908 SmallVector<SDValue, 16> V(16,
13909 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13911 return DAG.getNode(ISD::AND, dl, VT, SRL,
13912 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13914 if (Op.getOpcode() == ISD::SRA) {
13915 if (ShiftAmt == 7) {
13916 // R s>> 7 === R s< 0
13917 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13918 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13921 // R s>> a === ((R u>> a) ^ m) - m
13922 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13923 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
13925 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13926 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13927 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13930 llvm_unreachable("Unknown shift opcode.");
13933 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
13934 if (Op.getOpcode() == ISD::SHL) {
13935 // Make a large shift.
13936 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13937 MVT::v16i16, R, ShiftAmt,
13939 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13940 // Zero out the rightmost bits.
13941 SmallVector<SDValue, 32> V(32,
13942 DAG.getConstant(uint8_t(-1U << ShiftAmt),
13944 return DAG.getNode(ISD::AND, dl, VT, SHL,
13945 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13947 if (Op.getOpcode() == ISD::SRL) {
13948 // Make a large shift.
13949 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13950 MVT::v16i16, R, ShiftAmt,
13952 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13953 // Zero out the leftmost bits.
13954 SmallVector<SDValue, 32> V(32,
13955 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13957 return DAG.getNode(ISD::AND, dl, VT, SRL,
13958 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13960 if (Op.getOpcode() == ISD::SRA) {
13961 if (ShiftAmt == 7) {
13962 // R s>> 7 === R s< 0
13963 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13964 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13967 // R s>> a === ((R u>> a) ^ m) - m
13968 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13969 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
13971 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13972 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13973 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13976 llvm_unreachable("Unknown shift opcode.");
13981 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13982 if (!Subtarget->is64Bit() &&
13983 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
13984 Amt.getOpcode() == ISD::BITCAST &&
13985 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13986 Amt = Amt.getOperand(0);
13987 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13988 VT.getVectorNumElements();
13989 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
13990 uint64_t ShiftAmt = 0;
13991 for (unsigned i = 0; i != Ratio; ++i) {
13992 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
13996 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
13998 // Check remaining shift amounts.
13999 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
14000 uint64_t ShAmt = 0;
14001 for (unsigned j = 0; j != Ratio; ++j) {
14002 ConstantSDNode *C =
14003 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
14007 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
14009 if (ShAmt != ShiftAmt)
14012 switch (Op.getOpcode()) {
14014 llvm_unreachable("Unknown shift opcode!");
14016 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
14019 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
14022 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
14030 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
14031 const X86Subtarget* Subtarget) {
14032 MVT VT = Op.getSimpleValueType();
14034 SDValue R = Op.getOperand(0);
14035 SDValue Amt = Op.getOperand(1);
14037 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
14038 VT == MVT::v4i32 || VT == MVT::v8i16 ||
14039 (Subtarget->hasInt256() &&
14040 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
14041 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
14042 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
14044 EVT EltVT = VT.getVectorElementType();
14046 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
14047 unsigned NumElts = VT.getVectorNumElements();
14049 for (i = 0; i != NumElts; ++i) {
14050 if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
14054 for (j = i; j != NumElts; ++j) {
14055 SDValue Arg = Amt.getOperand(j);
14056 if (Arg.getOpcode() == ISD::UNDEF) continue;
14057 if (Arg != Amt.getOperand(i))
14060 if (i != NumElts && j == NumElts)
14061 BaseShAmt = Amt.getOperand(i);
14063 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
14064 Amt = Amt.getOperand(0);
14065 if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
14066 cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
14067 SDValue InVec = Amt.getOperand(0);
14068 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
14069 unsigned NumElts = InVec.getValueType().getVectorNumElements();
14071 for (; i != NumElts; ++i) {
14072 SDValue Arg = InVec.getOperand(i);
14073 if (Arg.getOpcode() == ISD::UNDEF) continue;
14077 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
14078 if (ConstantSDNode *C =
14079 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
14080 unsigned SplatIdx =
14081 cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
14082 if (C->getZExtValue() == SplatIdx)
14083 BaseShAmt = InVec.getOperand(1);
14086 if (!BaseShAmt.getNode())
14087 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
14088 DAG.getIntPtrConstant(0));
14092 if (BaseShAmt.getNode()) {
14093 if (EltVT.bitsGT(MVT::i32))
14094 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
14095 else if (EltVT.bitsLT(MVT::i32))
14096 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
14098 switch (Op.getOpcode()) {
14100 llvm_unreachable("Unknown shift opcode!");
14102 switch (VT.SimpleTy) {
14103 default: return SDValue();
14112 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
14115 switch (VT.SimpleTy) {
14116 default: return SDValue();
14123 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
14126 switch (VT.SimpleTy) {
14127 default: return SDValue();
14136 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
14142 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
14143 if (!Subtarget->is64Bit() &&
14144 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
14145 (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
14146 Amt.getOpcode() == ISD::BITCAST &&
14147 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
14148 Amt = Amt.getOperand(0);
14149 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
14150 VT.getVectorNumElements();
14151 std::vector<SDValue> Vals(Ratio);
14152 for (unsigned i = 0; i != Ratio; ++i)
14153 Vals[i] = Amt.getOperand(i);
14154 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
14155 for (unsigned j = 0; j != Ratio; ++j)
14156 if (Vals[j] != Amt.getOperand(i + j))
14159 switch (Op.getOpcode()) {
14161 llvm_unreachable("Unknown shift opcode!");
14163 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
14165 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
14167 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
14174 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
14175 SelectionDAG &DAG) {
14177 MVT VT = Op.getSimpleValueType();
14179 SDValue R = Op.getOperand(0);
14180 SDValue Amt = Op.getOperand(1);
14183 if (!Subtarget->hasSSE2())
14186 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
14190 V = LowerScalarVariableShift(Op, DAG, Subtarget);
14194 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
14196 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
14197 if (Subtarget->hasInt256()) {
14198 if (Op.getOpcode() == ISD::SRL &&
14199 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
14200 VT == MVT::v4i64 || VT == MVT::v8i32))
14202 if (Op.getOpcode() == ISD::SHL &&
14203 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
14204 VT == MVT::v4i64 || VT == MVT::v8i32))
14206 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
14210 // If possible, lower this packed shift into a vector multiply instead of
14211 // expanding it into a sequence of scalar shifts.
14212 // Do this only if the vector shift count is a constant build_vector.
14213 if (Op.getOpcode() == ISD::SHL &&
14214 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
14215 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
14216 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
14217 SmallVector<SDValue, 8> Elts;
14218 EVT SVT = VT.getScalarType();
14219 unsigned SVTBits = SVT.getSizeInBits();
14220 const APInt &One = APInt(SVTBits, 1);
14221 unsigned NumElems = VT.getVectorNumElements();
14223 for (unsigned i=0; i !=NumElems; ++i) {
14224 SDValue Op = Amt->getOperand(i);
14225 if (Op->getOpcode() == ISD::UNDEF) {
14226 Elts.push_back(Op);
14230 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
14231 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
14232 uint64_t ShAmt = C.getZExtValue();
14233 if (ShAmt >= SVTBits) {
14234 Elts.push_back(DAG.getUNDEF(SVT));
14237 Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
14239 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14240 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
14243 // Lower SHL with variable shift amount.
14244 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
14245 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
14247 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
14248 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
14249 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
14250 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
14253 // If possible, lower this shift as a sequence of two shifts by
14254 // constant plus a MOVSS/MOVSD instead of scalarizing it.
14256 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
14258 // Could be rewritten as:
14259 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
14261 // The advantage is that the two shifts from the example would be
14262 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
14263 // the vector shift into four scalar shifts plus four pairs of vector
14265 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
14266 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
14267 unsigned TargetOpcode = X86ISD::MOVSS;
14268 bool CanBeSimplified;
14269 // The splat value for the first packed shift (the 'X' from the example).
14270 SDValue Amt1 = Amt->getOperand(0);
14271 // The splat value for the second packed shift (the 'Y' from the example).
14272 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
14273 Amt->getOperand(2);
14275 // See if it is possible to replace this node with a sequence of
14276 // two shifts followed by a MOVSS/MOVSD
14277 if (VT == MVT::v4i32) {
14278 // Check if it is legal to use a MOVSS.
14279 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
14280 Amt2 == Amt->getOperand(3);
14281 if (!CanBeSimplified) {
14282 // Otherwise, check if we can still simplify this node using a MOVSD.
14283 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
14284 Amt->getOperand(2) == Amt->getOperand(3);
14285 TargetOpcode = X86ISD::MOVSD;
14286 Amt2 = Amt->getOperand(2);
14289 // Do similar checks for the case where the machine value type
14291 CanBeSimplified = Amt1 == Amt->getOperand(1);
14292 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
14293 CanBeSimplified = Amt2 == Amt->getOperand(i);
14295 if (!CanBeSimplified) {
14296 TargetOpcode = X86ISD::MOVSD;
14297 CanBeSimplified = true;
14298 Amt2 = Amt->getOperand(4);
14299 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
14300 CanBeSimplified = Amt1 == Amt->getOperand(i);
14301 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
14302 CanBeSimplified = Amt2 == Amt->getOperand(j);
14306 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
14307 isa<ConstantSDNode>(Amt2)) {
14308 // Replace this node with two shifts followed by a MOVSS/MOVSD.
14309 EVT CastVT = MVT::v4i32;
14311 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
14312 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
14314 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
14315 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
14316 if (TargetOpcode == X86ISD::MOVSD)
14317 CastVT = MVT::v2i64;
14318 SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
14319 SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
14320 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
14322 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
14326 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
14327 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
14330 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
14331 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
14333 // Turn 'a' into a mask suitable for VSELECT
14334 SDValue VSelM = DAG.getConstant(0x80, VT);
14335 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
14336 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
14338 SDValue CM1 = DAG.getConstant(0x0f, VT);
14339 SDValue CM2 = DAG.getConstant(0x3f, VT);
14341 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
14342 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
14343 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
14344 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
14345 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
14348 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
14349 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
14350 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
14352 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
14353 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
14354 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
14355 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
14356 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
14359 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
14360 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
14361 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
14363 // return VSELECT(r, r+r, a);
14364 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
14365 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
14369 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
14370 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
14371 // solution better.
14372 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
14373 MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
14375 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
14376 R = DAG.getNode(ExtOpc, dl, NewVT, R);
14377 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
14378 return DAG.getNode(ISD::TRUNCATE, dl, VT,
14379 DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
14382 // Decompose 256-bit shifts into smaller 128-bit shifts.
14383 if (VT.is256BitVector()) {
14384 unsigned NumElems = VT.getVectorNumElements();
14385 MVT EltVT = VT.getVectorElementType();
14386 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14388 // Extract the two vectors
14389 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
14390 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
14392 // Recreate the shift amount vectors
14393 SDValue Amt1, Amt2;
14394 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
14395 // Constant shift amount
14396 SmallVector<SDValue, 4> Amt1Csts;
14397 SmallVector<SDValue, 4> Amt2Csts;
14398 for (unsigned i = 0; i != NumElems/2; ++i)
14399 Amt1Csts.push_back(Amt->getOperand(i));
14400 for (unsigned i = NumElems/2; i != NumElems; ++i)
14401 Amt2Csts.push_back(Amt->getOperand(i));
14403 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
14404 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
14406 // Variable shift amount
14407 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
14408 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
14411 // Issue new vector shifts for the smaller types
14412 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
14413 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
14415 // Concatenate the result back
14416 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
14422 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
14423 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
14424 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
14425 // looks for this combo and may remove the "setcc" instruction if the "setcc"
14426 // has only one use.
14427 SDNode *N = Op.getNode();
14428 SDValue LHS = N->getOperand(0);
14429 SDValue RHS = N->getOperand(1);
14430 unsigned BaseOp = 0;
14433 switch (Op.getOpcode()) {
14434 default: llvm_unreachable("Unknown ovf instruction!");
14436 // A subtract of one will be selected as a INC. Note that INC doesn't
14437 // set CF, so we can't do this for UADDO.
14438 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14440 BaseOp = X86ISD::INC;
14441 Cond = X86::COND_O;
14444 BaseOp = X86ISD::ADD;
14445 Cond = X86::COND_O;
14448 BaseOp = X86ISD::ADD;
14449 Cond = X86::COND_B;
14452 // A subtract of one will be selected as a DEC. Note that DEC doesn't
14453 // set CF, so we can't do this for USUBO.
14454 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14456 BaseOp = X86ISD::DEC;
14457 Cond = X86::COND_O;
14460 BaseOp = X86ISD::SUB;
14461 Cond = X86::COND_O;
14464 BaseOp = X86ISD::SUB;
14465 Cond = X86::COND_B;
14468 BaseOp = X86ISD::SMUL;
14469 Cond = X86::COND_O;
14471 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
14472 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
14474 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
14477 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14478 DAG.getConstant(X86::COND_O, MVT::i32),
14479 SDValue(Sum.getNode(), 2));
14481 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
14485 // Also sets EFLAGS.
14486 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
14487 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
14490 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
14491 DAG.getConstant(Cond, MVT::i32),
14492 SDValue(Sum.getNode(), 1));
14494 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
14497 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
14498 SelectionDAG &DAG) const {
14500 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
14501 MVT VT = Op.getSimpleValueType();
14503 if (!Subtarget->hasSSE2() || !VT.isVector())
14506 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
14507 ExtraVT.getScalarType().getSizeInBits();
14509 switch (VT.SimpleTy) {
14510 default: return SDValue();
14513 if (!Subtarget->hasFp256())
14515 if (!Subtarget->hasInt256()) {
14516 // needs to be split
14517 unsigned NumElems = VT.getVectorNumElements();
14519 // Extract the LHS vectors
14520 SDValue LHS = Op.getOperand(0);
14521 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14522 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14524 MVT EltVT = VT.getVectorElementType();
14525 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14527 EVT ExtraEltVT = ExtraVT.getVectorElementType();
14528 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
14529 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
14531 SDValue Extra = DAG.getValueType(ExtraVT);
14533 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
14534 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
14536 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
14541 SDValue Op0 = Op.getOperand(0);
14542 SDValue Op00 = Op0.getOperand(0);
14544 // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
14545 if (Op0.getOpcode() == ISD::BITCAST &&
14546 Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
14547 // (sext (vzext x)) -> (vsext x)
14548 Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
14549 if (Tmp1.getNode()) {
14550 EVT ExtraEltVT = ExtraVT.getVectorElementType();
14551 // This folding is only valid when the in-reg type is a vector of i8,
14553 if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
14554 ExtraEltVT == MVT::i32) {
14555 SDValue Tmp1Op0 = Tmp1.getOperand(0);
14556 assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
14557 "This optimization is invalid without a VZEXT.");
14558 return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
14564 // If the above didn't work, then just use Shift-Left + Shift-Right.
14565 Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
14567 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
14573 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
14574 SelectionDAG &DAG) {
14576 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
14577 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
14578 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
14579 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
14581 // The only fence that needs an instruction is a sequentially-consistent
14582 // cross-thread fence.
14583 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
14584 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
14585 // no-sse2). There isn't any reason to disable it if the target processor
14587 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
14588 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
14590 SDValue Chain = Op.getOperand(0);
14591 SDValue Zero = DAG.getConstant(0, MVT::i32);
14593 DAG.getRegister(X86::ESP, MVT::i32), // Base
14594 DAG.getTargetConstant(1, MVT::i8), // Scale
14595 DAG.getRegister(0, MVT::i32), // Index
14596 DAG.getTargetConstant(0, MVT::i32), // Disp
14597 DAG.getRegister(0, MVT::i32), // Segment.
14601 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
14602 return SDValue(Res, 0);
14605 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
14606 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
14609 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
14610 SelectionDAG &DAG) {
14611 MVT T = Op.getSimpleValueType();
14615 switch(T.SimpleTy) {
14616 default: llvm_unreachable("Invalid value type!");
14617 case MVT::i8: Reg = X86::AL; size = 1; break;
14618 case MVT::i16: Reg = X86::AX; size = 2; break;
14619 case MVT::i32: Reg = X86::EAX; size = 4; break;
14621 assert(Subtarget->is64Bit() && "Node not type legal!");
14622 Reg = X86::RAX; size = 8;
14625 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
14626 Op.getOperand(2), SDValue());
14627 SDValue Ops[] = { cpIn.getValue(0),
14630 DAG.getTargetConstant(size, MVT::i8),
14631 cpIn.getValue(1) };
14632 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14633 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
14634 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
14638 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
14639 SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
14640 MVT::i32, cpOut.getValue(2));
14641 SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
14642 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
14644 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
14645 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
14646 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
14650 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
14651 SelectionDAG &DAG) {
14652 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
14653 MVT DstVT = Op.getSimpleValueType();
14655 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
14656 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14657 if (DstVT != MVT::f64)
14658 // This conversion needs to be expanded.
14661 SDValue InVec = Op->getOperand(0);
14663 unsigned NumElts = SrcVT.getVectorNumElements();
14664 EVT SVT = SrcVT.getVectorElementType();
14666 // Widen the vector in input in the case of MVT::v2i32.
14667 // Example: from MVT::v2i32 to MVT::v4i32.
14668 SmallVector<SDValue, 16> Elts;
14669 for (unsigned i = 0, e = NumElts; i != e; ++i)
14670 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
14671 DAG.getIntPtrConstant(i)));
14673 // Explicitly mark the extra elements as Undef.
14674 SDValue Undef = DAG.getUNDEF(SVT);
14675 for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
14676 Elts.push_back(Undef);
14678 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
14679 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
14680 SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
14681 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
14682 DAG.getIntPtrConstant(0));
14685 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
14686 Subtarget->hasMMX() && "Unexpected custom BITCAST");
14687 assert((DstVT == MVT::i64 ||
14688 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
14689 "Unexpected custom BITCAST");
14690 // i64 <=> MMX conversions are Legal.
14691 if (SrcVT==MVT::i64 && DstVT.isVector())
14693 if (DstVT==MVT::i64 && SrcVT.isVector())
14695 // MMX <=> MMX conversions are Legal.
14696 if (SrcVT.isVector() && DstVT.isVector())
14698 // All other conversions need to be expanded.
14702 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
14703 SDNode *Node = Op.getNode();
14705 EVT T = Node->getValueType(0);
14706 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
14707 DAG.getConstant(0, T), Node->getOperand(2));
14708 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
14709 cast<AtomicSDNode>(Node)->getMemoryVT(),
14710 Node->getOperand(0),
14711 Node->getOperand(1), negOp,
14712 cast<AtomicSDNode>(Node)->getMemOperand(),
14713 cast<AtomicSDNode>(Node)->getOrdering(),
14714 cast<AtomicSDNode>(Node)->getSynchScope());
14717 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
14718 SDNode *Node = Op.getNode();
14720 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14722 // Convert seq_cst store -> xchg
14723 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
14724 // FIXME: On 32-bit, store -> fist or movq would be more efficient
14725 // (The only way to get a 16-byte store is cmpxchg16b)
14726 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
14727 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
14728 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14729 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
14730 cast<AtomicSDNode>(Node)->getMemoryVT(),
14731 Node->getOperand(0),
14732 Node->getOperand(1), Node->getOperand(2),
14733 cast<AtomicSDNode>(Node)->getMemOperand(),
14734 cast<AtomicSDNode>(Node)->getOrdering(),
14735 cast<AtomicSDNode>(Node)->getSynchScope());
14736 return Swap.getValue(1);
14738 // Other atomic stores have a simple pattern.
14742 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
14743 EVT VT = Op.getNode()->getSimpleValueType(0);
14745 // Let legalize expand this if it isn't a legal type yet.
14746 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14749 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14752 bool ExtraOp = false;
14753 switch (Op.getOpcode()) {
14754 default: llvm_unreachable("Invalid code");
14755 case ISD::ADDC: Opc = X86ISD::ADD; break;
14756 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
14757 case ISD::SUBC: Opc = X86ISD::SUB; break;
14758 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
14762 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14764 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14765 Op.getOperand(1), Op.getOperand(2));
14768 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
14769 SelectionDAG &DAG) {
14770 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
14772 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
14773 // which returns the values as { float, float } (in XMM0) or
14774 // { double, double } (which is returned in XMM0, XMM1).
14776 SDValue Arg = Op.getOperand(0);
14777 EVT ArgVT = Arg.getValueType();
14778 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14780 TargetLowering::ArgListTy Args;
14781 TargetLowering::ArgListEntry Entry;
14785 Entry.isSExt = false;
14786 Entry.isZExt = false;
14787 Args.push_back(Entry);
14789 bool isF64 = ArgVT == MVT::f64;
14790 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
14791 // the small struct {f32, f32} is returned in (eax, edx). For f64,
14792 // the results are returned via SRet in memory.
14793 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
14794 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14795 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
14797 Type *RetTy = isF64
14798 ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
14799 : (Type*)VectorType::get(ArgTy, 4);
14801 TargetLowering::CallLoweringInfo CLI(DAG);
14802 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
14803 .setCallee(CallingConv::C, RetTy, Callee, &Args, 0);
14805 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
14808 // Returned in xmm0 and xmm1.
14809 return CallResult.first;
14811 // Returned in bits 0:31 and 32:64 xmm0.
14812 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14813 CallResult.first, DAG.getIntPtrConstant(0));
14814 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14815 CallResult.first, DAG.getIntPtrConstant(1));
14816 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
14817 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
14820 /// LowerOperation - Provide custom lowering hooks for some operations.
14822 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
14823 switch (Op.getOpcode()) {
14824 default: llvm_unreachable("Should not custom lower this!");
14825 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
14826 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
14827 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
14828 return LowerCMP_SWAP(Op, Subtarget, DAG);
14829 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
14830 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
14831 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
14832 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
14833 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
14834 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
14835 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
14836 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
14837 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
14838 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
14839 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
14840 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
14841 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
14842 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
14843 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
14844 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
14845 case ISD::SHL_PARTS:
14846 case ISD::SRA_PARTS:
14847 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
14848 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
14849 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
14850 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
14851 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
14852 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
14853 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
14854 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
14855 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
14856 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
14857 case ISD::FABS: return LowerFABS(Op, DAG);
14858 case ISD::FNEG: return LowerFNEG(Op, DAG);
14859 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
14860 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
14861 case ISD::SETCC: return LowerSETCC(Op, DAG);
14862 case ISD::SELECT: return LowerSELECT(Op, DAG);
14863 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
14864 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
14865 case ISD::VASTART: return LowerVASTART(Op, DAG);
14866 case ISD::VAARG: return LowerVAARG(Op, DAG);
14867 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
14868 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
14869 case ISD::INTRINSIC_VOID:
14870 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
14871 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
14872 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
14873 case ISD::FRAME_TO_ARGS_OFFSET:
14874 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
14875 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
14876 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
14877 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
14878 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
14879 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
14880 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
14881 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
14882 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
14883 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
14884 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
14885 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
14886 case ISD::UMUL_LOHI:
14887 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
14890 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
14896 case ISD::UMULO: return LowerXALUO(Op, DAG);
14897 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
14898 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
14902 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
14903 case ISD::ADD: return LowerADD(Op, DAG);
14904 case ISD::SUB: return LowerSUB(Op, DAG);
14905 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
14909 static void ReplaceATOMIC_LOAD(SDNode *Node,
14910 SmallVectorImpl<SDValue> &Results,
14911 SelectionDAG &DAG) {
14913 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14915 // Convert wide load -> cmpxchg8b/cmpxchg16b
14916 // FIXME: On 32-bit, load -> fild or movq would be more efficient
14917 // (The only way to get a 16-byte load is cmpxchg16b)
14918 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
14919 SDValue Zero = DAG.getConstant(0, VT);
14920 SDVTList VTs = DAG.getVTList(VT, MVT::i1, MVT::Other);
14922 DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, VT, VTs,
14923 Node->getOperand(0), Node->getOperand(1), Zero, Zero,
14924 cast<AtomicSDNode>(Node)->getMemOperand(),
14925 cast<AtomicSDNode>(Node)->getOrdering(),
14926 cast<AtomicSDNode>(Node)->getOrdering(),
14927 cast<AtomicSDNode>(Node)->getSynchScope());
14928 Results.push_back(Swap.getValue(0));
14929 Results.push_back(Swap.getValue(2));
14933 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
14934 SelectionDAG &DAG, unsigned NewOp) {
14936 assert (Node->getValueType(0) == MVT::i64 &&
14937 "Only know how to expand i64 atomics");
14939 SDValue Chain = Node->getOperand(0);
14940 SDValue In1 = Node->getOperand(1);
14941 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14942 Node->getOperand(2), DAG.getIntPtrConstant(0));
14943 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14944 Node->getOperand(2), DAG.getIntPtrConstant(1));
14945 SDValue Ops[] = { Chain, In1, In2L, In2H };
14946 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
14948 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, MVT::i64,
14949 cast<MemSDNode>(Node)->getMemOperand());
14950 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
14951 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF));
14952 Results.push_back(Result.getValue(2));
14955 /// ReplaceNodeResults - Replace a node with an illegal result type
14956 /// with a new node built out of custom code.
14957 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
14958 SmallVectorImpl<SDValue>&Results,
14959 SelectionDAG &DAG) const {
14961 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14962 switch (N->getOpcode()) {
14964 llvm_unreachable("Do not know how to custom type legalize this operation!");
14965 case ISD::SIGN_EXTEND_INREG:
14970 // We don't want to expand or promote these.
14977 case ISD::UDIVREM: {
14978 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
14979 Results.push_back(V);
14982 case ISD::FP_TO_SINT:
14983 case ISD::FP_TO_UINT: {
14984 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
14986 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
14989 std::pair<SDValue,SDValue> Vals =
14990 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
14991 SDValue FIST = Vals.first, StackSlot = Vals.second;
14992 if (FIST.getNode()) {
14993 EVT VT = N->getValueType(0);
14994 // Return a load from the stack slot.
14995 if (StackSlot.getNode())
14996 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
14997 MachinePointerInfo(),
14998 false, false, false, 0));
15000 Results.push_back(FIST);
15004 case ISD::UINT_TO_FP: {
15005 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
15006 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
15007 N->getValueType(0) != MVT::v2f32)
15009 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
15011 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
15013 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
15014 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
15015 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
15016 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
15017 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
15018 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
15021 case ISD::FP_ROUND: {
15022 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
15024 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
15025 Results.push_back(V);
15028 case ISD::INTRINSIC_W_CHAIN: {
15029 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
15031 default : llvm_unreachable("Do not know how to custom type "
15032 "legalize this intrinsic operation!");
15033 case Intrinsic::x86_rdtsc:
15034 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
15036 case Intrinsic::x86_rdtscp:
15037 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
15041 case ISD::READCYCLECOUNTER: {
15042 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
15045 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
15046 EVT T = N->getValueType(0);
15047 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
15048 bool Regs64bit = T == MVT::i128;
15049 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
15050 SDValue cpInL, cpInH;
15051 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
15052 DAG.getConstant(0, HalfT));
15053 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
15054 DAG.getConstant(1, HalfT));
15055 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
15056 Regs64bit ? X86::RAX : X86::EAX,
15058 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
15059 Regs64bit ? X86::RDX : X86::EDX,
15060 cpInH, cpInL.getValue(1));
15061 SDValue swapInL, swapInH;
15062 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
15063 DAG.getConstant(0, HalfT));
15064 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
15065 DAG.getConstant(1, HalfT));
15066 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
15067 Regs64bit ? X86::RBX : X86::EBX,
15068 swapInL, cpInH.getValue(1));
15069 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
15070 Regs64bit ? X86::RCX : X86::ECX,
15071 swapInH, swapInL.getValue(1));
15072 SDValue Ops[] = { swapInH.getValue(0),
15074 swapInH.getValue(1) };
15075 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15076 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
15077 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
15078 X86ISD::LCMPXCHG8_DAG;
15079 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
15080 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
15081 Regs64bit ? X86::RAX : X86::EAX,
15082 HalfT, Result.getValue(1));
15083 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
15084 Regs64bit ? X86::RDX : X86::EDX,
15085 HalfT, cpOutL.getValue(2));
15086 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
15088 SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
15089 MVT::i32, cpOutH.getValue(2));
15091 DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15092 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
15093 Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
15095 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
15096 Results.push_back(Success);
15097 Results.push_back(EFLAGS.getValue(1));
15100 case ISD::ATOMIC_LOAD_ADD:
15101 case ISD::ATOMIC_LOAD_AND:
15102 case ISD::ATOMIC_LOAD_NAND:
15103 case ISD::ATOMIC_LOAD_OR:
15104 case ISD::ATOMIC_LOAD_SUB:
15105 case ISD::ATOMIC_LOAD_XOR:
15106 case ISD::ATOMIC_LOAD_MAX:
15107 case ISD::ATOMIC_LOAD_MIN:
15108 case ISD::ATOMIC_LOAD_UMAX:
15109 case ISD::ATOMIC_LOAD_UMIN:
15110 case ISD::ATOMIC_SWAP: {
15112 switch (N->getOpcode()) {
15113 default: llvm_unreachable("Unexpected opcode");
15114 case ISD::ATOMIC_LOAD_ADD:
15115 Opc = X86ISD::ATOMADD64_DAG;
15117 case ISD::ATOMIC_LOAD_AND:
15118 Opc = X86ISD::ATOMAND64_DAG;
15120 case ISD::ATOMIC_LOAD_NAND:
15121 Opc = X86ISD::ATOMNAND64_DAG;
15123 case ISD::ATOMIC_LOAD_OR:
15124 Opc = X86ISD::ATOMOR64_DAG;
15126 case ISD::ATOMIC_LOAD_SUB:
15127 Opc = X86ISD::ATOMSUB64_DAG;
15129 case ISD::ATOMIC_LOAD_XOR:
15130 Opc = X86ISD::ATOMXOR64_DAG;
15132 case ISD::ATOMIC_LOAD_MAX:
15133 Opc = X86ISD::ATOMMAX64_DAG;
15135 case ISD::ATOMIC_LOAD_MIN:
15136 Opc = X86ISD::ATOMMIN64_DAG;
15138 case ISD::ATOMIC_LOAD_UMAX:
15139 Opc = X86ISD::ATOMUMAX64_DAG;
15141 case ISD::ATOMIC_LOAD_UMIN:
15142 Opc = X86ISD::ATOMUMIN64_DAG;
15144 case ISD::ATOMIC_SWAP:
15145 Opc = X86ISD::ATOMSWAP64_DAG;
15148 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
15151 case ISD::ATOMIC_LOAD: {
15152 ReplaceATOMIC_LOAD(N, Results, DAG);
15155 case ISD::BITCAST: {
15156 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
15157 EVT DstVT = N->getValueType(0);
15158 EVT SrcVT = N->getOperand(0)->getValueType(0);
15160 if (SrcVT != MVT::f64 ||
15161 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
15164 unsigned NumElts = DstVT.getVectorNumElements();
15165 EVT SVT = DstVT.getVectorElementType();
15166 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
15167 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
15168 MVT::v2f64, N->getOperand(0));
15169 SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
15171 SmallVector<SDValue, 8> Elts;
15172 for (unsigned i = 0, e = NumElts; i != e; ++i)
15173 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
15174 ToVecInt, DAG.getIntPtrConstant(i)));
15176 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
15181 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
15183 default: return nullptr;
15184 case X86ISD::BSF: return "X86ISD::BSF";
15185 case X86ISD::BSR: return "X86ISD::BSR";
15186 case X86ISD::SHLD: return "X86ISD::SHLD";
15187 case X86ISD::SHRD: return "X86ISD::SHRD";
15188 case X86ISD::FAND: return "X86ISD::FAND";
15189 case X86ISD::FANDN: return "X86ISD::FANDN";
15190 case X86ISD::FOR: return "X86ISD::FOR";
15191 case X86ISD::FXOR: return "X86ISD::FXOR";
15192 case X86ISD::FSRL: return "X86ISD::FSRL";
15193 case X86ISD::FILD: return "X86ISD::FILD";
15194 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
15195 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
15196 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
15197 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
15198 case X86ISD::FLD: return "X86ISD::FLD";
15199 case X86ISD::FST: return "X86ISD::FST";
15200 case X86ISD::CALL: return "X86ISD::CALL";
15201 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
15202 case X86ISD::RDTSCP_DAG: return "X86ISD::RDTSCP_DAG";
15203 case X86ISD::BT: return "X86ISD::BT";
15204 case X86ISD::CMP: return "X86ISD::CMP";
15205 case X86ISD::COMI: return "X86ISD::COMI";
15206 case X86ISD::UCOMI: return "X86ISD::UCOMI";
15207 case X86ISD::CMPM: return "X86ISD::CMPM";
15208 case X86ISD::CMPMU: return "X86ISD::CMPMU";
15209 case X86ISD::SETCC: return "X86ISD::SETCC";
15210 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
15211 case X86ISD::FSETCC: return "X86ISD::FSETCC";
15212 case X86ISD::CMOV: return "X86ISD::CMOV";
15213 case X86ISD::BRCOND: return "X86ISD::BRCOND";
15214 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
15215 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
15216 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
15217 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
15218 case X86ISD::Wrapper: return "X86ISD::Wrapper";
15219 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
15220 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
15221 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
15222 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
15223 case X86ISD::PINSRB: return "X86ISD::PINSRB";
15224 case X86ISD::PINSRW: return "X86ISD::PINSRW";
15225 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
15226 case X86ISD::ANDNP: return "X86ISD::ANDNP";
15227 case X86ISD::PSIGN: return "X86ISD::PSIGN";
15228 case X86ISD::BLENDV: return "X86ISD::BLENDV";
15229 case X86ISD::BLENDI: return "X86ISD::BLENDI";
15230 case X86ISD::SUBUS: return "X86ISD::SUBUS";
15231 case X86ISD::HADD: return "X86ISD::HADD";
15232 case X86ISD::HSUB: return "X86ISD::HSUB";
15233 case X86ISD::FHADD: return "X86ISD::FHADD";
15234 case X86ISD::FHSUB: return "X86ISD::FHSUB";
15235 case X86ISD::UMAX: return "X86ISD::UMAX";
15236 case X86ISD::UMIN: return "X86ISD::UMIN";
15237 case X86ISD::SMAX: return "X86ISD::SMAX";
15238 case X86ISD::SMIN: return "X86ISD::SMIN";
15239 case X86ISD::FMAX: return "X86ISD::FMAX";
15240 case X86ISD::FMIN: return "X86ISD::FMIN";
15241 case X86ISD::FMAXC: return "X86ISD::FMAXC";
15242 case X86ISD::FMINC: return "X86ISD::FMINC";
15243 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
15244 case X86ISD::FRCP: return "X86ISD::FRCP";
15245 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
15246 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
15247 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
15248 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
15249 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
15250 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
15251 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
15252 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
15253 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
15254 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
15255 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
15256 case X86ISD::LCMPXCHG16_DAG: return "X86ISD::LCMPXCHG16_DAG";
15257 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
15258 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
15259 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
15260 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
15261 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
15262 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
15263 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
15264 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
15265 case X86ISD::VZEXT: return "X86ISD::VZEXT";
15266 case X86ISD::VSEXT: return "X86ISD::VSEXT";
15267 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
15268 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
15269 case X86ISD::VINSERT: return "X86ISD::VINSERT";
15270 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
15271 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
15272 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
15273 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
15274 case X86ISD::VSHL: return "X86ISD::VSHL";
15275 case X86ISD::VSRL: return "X86ISD::VSRL";
15276 case X86ISD::VSRA: return "X86ISD::VSRA";
15277 case X86ISD::VSHLI: return "X86ISD::VSHLI";
15278 case X86ISD::VSRLI: return "X86ISD::VSRLI";
15279 case X86ISD::VSRAI: return "X86ISD::VSRAI";
15280 case X86ISD::CMPP: return "X86ISD::CMPP";
15281 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
15282 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
15283 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
15284 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
15285 case X86ISD::ADD: return "X86ISD::ADD";
15286 case X86ISD::SUB: return "X86ISD::SUB";
15287 case X86ISD::ADC: return "X86ISD::ADC";
15288 case X86ISD::SBB: return "X86ISD::SBB";
15289 case X86ISD::SMUL: return "X86ISD::SMUL";
15290 case X86ISD::UMUL: return "X86ISD::UMUL";
15291 case X86ISD::INC: return "X86ISD::INC";
15292 case X86ISD::DEC: return "X86ISD::DEC";
15293 case X86ISD::OR: return "X86ISD::OR";
15294 case X86ISD::XOR: return "X86ISD::XOR";
15295 case X86ISD::AND: return "X86ISD::AND";
15296 case X86ISD::BEXTR: return "X86ISD::BEXTR";
15297 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
15298 case X86ISD::PTEST: return "X86ISD::PTEST";
15299 case X86ISD::TESTP: return "X86ISD::TESTP";
15300 case X86ISD::TESTM: return "X86ISD::TESTM";
15301 case X86ISD::TESTNM: return "X86ISD::TESTNM";
15302 case X86ISD::KORTEST: return "X86ISD::KORTEST";
15303 case X86ISD::PACKSS: return "X86ISD::PACKSS";
15304 case X86ISD::PACKUS: return "X86ISD::PACKUS";
15305 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
15306 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
15307 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
15308 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
15309 case X86ISD::SHUFP: return "X86ISD::SHUFP";
15310 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
15311 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
15312 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
15313 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
15314 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
15315 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
15316 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
15317 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
15318 case X86ISD::MOVSD: return "X86ISD::MOVSD";
15319 case X86ISD::MOVSS: return "X86ISD::MOVSS";
15320 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
15321 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
15322 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
15323 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
15324 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
15325 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
15326 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
15327 case X86ISD::VPERMV: return "X86ISD::VPERMV";
15328 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
15329 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
15330 case X86ISD::VPERMI: return "X86ISD::VPERMI";
15331 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
15332 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
15333 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
15334 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
15335 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
15336 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
15337 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
15338 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
15339 case X86ISD::SAHF: return "X86ISD::SAHF";
15340 case X86ISD::RDRAND: return "X86ISD::RDRAND";
15341 case X86ISD::RDSEED: return "X86ISD::RDSEED";
15342 case X86ISD::FMADD: return "X86ISD::FMADD";
15343 case X86ISD::FMSUB: return "X86ISD::FMSUB";
15344 case X86ISD::FNMADD: return "X86ISD::FNMADD";
15345 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
15346 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
15347 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
15348 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
15349 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
15350 case X86ISD::XTEST: return "X86ISD::XTEST";
15354 // isLegalAddressingMode - Return true if the addressing mode represented
15355 // by AM is legal for this target, for a load/store of the specified type.
15356 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
15358 // X86 supports extremely general addressing modes.
15359 CodeModel::Model M = getTargetMachine().getCodeModel();
15360 Reloc::Model R = getTargetMachine().getRelocationModel();
15362 // X86 allows a sign-extended 32-bit immediate field as a displacement.
15363 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
15368 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
15370 // If a reference to this global requires an extra load, we can't fold it.
15371 if (isGlobalStubReference(GVFlags))
15374 // If BaseGV requires a register for the PIC base, we cannot also have a
15375 // BaseReg specified.
15376 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
15379 // If lower 4G is not available, then we must use rip-relative addressing.
15380 if ((M != CodeModel::Small || R != Reloc::Static) &&
15381 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
15385 switch (AM.Scale) {
15391 // These scales always work.
15396 // These scales are formed with basereg+scalereg. Only accept if there is
15401 default: // Other stuff never works.
15408 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
15409 unsigned Bits = Ty->getScalarSizeInBits();
15411 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
15412 // particularly cheaper than those without.
15416 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
15417 // variable shifts just as cheap as scalar ones.
15418 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
15421 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
15422 // fully general vector.
15426 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
15427 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15429 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
15430 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
15431 return NumBits1 > NumBits2;
15434 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
15435 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15438 if (!isTypeLegal(EVT::getEVT(Ty1)))
15441 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
15443 // Assuming the caller doesn't have a zeroext or signext return parameter,
15444 // truncation all the way down to i1 is valid.
15448 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
15449 return isInt<32>(Imm);
15452 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
15453 // Can also use sub to handle negated immediates.
15454 return isInt<32>(Imm);
15457 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
15458 if (!VT1.isInteger() || !VT2.isInteger())
15460 unsigned NumBits1 = VT1.getSizeInBits();
15461 unsigned NumBits2 = VT2.getSizeInBits();
15462 return NumBits1 > NumBits2;
15465 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
15466 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
15467 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
15470 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
15471 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
15472 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
15475 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
15476 EVT VT1 = Val.getValueType();
15477 if (isZExtFree(VT1, VT2))
15480 if (Val.getOpcode() != ISD::LOAD)
15483 if (!VT1.isSimple() || !VT1.isInteger() ||
15484 !VT2.isSimple() || !VT2.isInteger())
15487 switch (VT1.getSimpleVT().SimpleTy) {
15492 // X86 has 8, 16, and 32-bit zero-extending loads.
15500 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
15501 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
15504 VT = VT.getScalarType();
15506 if (!VT.isSimple())
15509 switch (VT.getSimpleVT().SimpleTy) {
15520 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
15521 // i16 instructions are longer (0x66 prefix) and potentially slower.
15522 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
15525 /// isShuffleMaskLegal - Targets can use this to indicate that they only
15526 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
15527 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
15528 /// are assumed to be legal.
15530 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
15532 if (!VT.isSimple())
15535 MVT SVT = VT.getSimpleVT();
15537 // Very little shuffling can be done for 64-bit vectors right now.
15538 if (VT.getSizeInBits() == 64)
15541 // If this is a single-input shuffle with no 128 bit lane crossings we can
15542 // lower it into pshufb.
15543 if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
15544 (SVT.is256BitVector() && Subtarget->hasInt256())) {
15545 bool isLegal = true;
15546 for (unsigned I = 0, E = M.size(); I != E; ++I) {
15547 if (M[I] >= (int)SVT.getVectorNumElements() ||
15548 ShuffleCrosses128bitLane(SVT, I, M[I])) {
15557 // FIXME: blends, shifts.
15558 return (SVT.getVectorNumElements() == 2 ||
15559 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
15560 isMOVLMask(M, SVT) ||
15561 isSHUFPMask(M, SVT) ||
15562 isPSHUFDMask(M, SVT) ||
15563 isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
15564 isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
15565 isPALIGNRMask(M, SVT, Subtarget) ||
15566 isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
15567 isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
15568 isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
15569 isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
15570 isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
15574 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
15576 if (!VT.isSimple())
15579 MVT SVT = VT.getSimpleVT();
15580 unsigned NumElts = SVT.getVectorNumElements();
15581 // FIXME: This collection of masks seems suspect.
15584 if (NumElts == 4 && SVT.is128BitVector()) {
15585 return (isMOVLMask(Mask, SVT) ||
15586 isCommutedMOVLMask(Mask, SVT, true) ||
15587 isSHUFPMask(Mask, SVT) ||
15588 isSHUFPMask(Mask, SVT, /* Commuted */ true));
15593 //===----------------------------------------------------------------------===//
15594 // X86 Scheduler Hooks
15595 //===----------------------------------------------------------------------===//
15597 /// Utility function to emit xbegin specifying the start of an RTM region.
15598 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
15599 const TargetInstrInfo *TII) {
15600 DebugLoc DL = MI->getDebugLoc();
15602 const BasicBlock *BB = MBB->getBasicBlock();
15603 MachineFunction::iterator I = MBB;
15606 // For the v = xbegin(), we generate
15617 MachineBasicBlock *thisMBB = MBB;
15618 MachineFunction *MF = MBB->getParent();
15619 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15620 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15621 MF->insert(I, mainMBB);
15622 MF->insert(I, sinkMBB);
15624 // Transfer the remainder of BB and its successor edges to sinkMBB.
15625 sinkMBB->splice(sinkMBB->begin(), MBB,
15626 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15627 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15631 // # fallthrough to mainMBB
15632 // # abortion to sinkMBB
15633 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
15634 thisMBB->addSuccessor(mainMBB);
15635 thisMBB->addSuccessor(sinkMBB);
15639 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
15640 mainMBB->addSuccessor(sinkMBB);
15643 // EAX is live into the sinkMBB
15644 sinkMBB->addLiveIn(X86::EAX);
15645 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15646 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15649 MI->eraseFromParent();
15653 // Get CMPXCHG opcode for the specified data type.
15654 static unsigned getCmpXChgOpcode(EVT VT) {
15655 switch (VT.getSimpleVT().SimpleTy) {
15656 case MVT::i8: return X86::LCMPXCHG8;
15657 case MVT::i16: return X86::LCMPXCHG16;
15658 case MVT::i32: return X86::LCMPXCHG32;
15659 case MVT::i64: return X86::LCMPXCHG64;
15663 llvm_unreachable("Invalid operand size!");
15666 // Get LOAD opcode for the specified data type.
15667 static unsigned getLoadOpcode(EVT VT) {
15668 switch (VT.getSimpleVT().SimpleTy) {
15669 case MVT::i8: return X86::MOV8rm;
15670 case MVT::i16: return X86::MOV16rm;
15671 case MVT::i32: return X86::MOV32rm;
15672 case MVT::i64: return X86::MOV64rm;
15676 llvm_unreachable("Invalid operand size!");
15679 // Get opcode of the non-atomic one from the specified atomic instruction.
15680 static unsigned getNonAtomicOpcode(unsigned Opc) {
15682 case X86::ATOMAND8: return X86::AND8rr;
15683 case X86::ATOMAND16: return X86::AND16rr;
15684 case X86::ATOMAND32: return X86::AND32rr;
15685 case X86::ATOMAND64: return X86::AND64rr;
15686 case X86::ATOMOR8: return X86::OR8rr;
15687 case X86::ATOMOR16: return X86::OR16rr;
15688 case X86::ATOMOR32: return X86::OR32rr;
15689 case X86::ATOMOR64: return X86::OR64rr;
15690 case X86::ATOMXOR8: return X86::XOR8rr;
15691 case X86::ATOMXOR16: return X86::XOR16rr;
15692 case X86::ATOMXOR32: return X86::XOR32rr;
15693 case X86::ATOMXOR64: return X86::XOR64rr;
15695 llvm_unreachable("Unhandled atomic-load-op opcode!");
15698 // Get opcode of the non-atomic one from the specified atomic instruction with
15700 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
15701 unsigned &ExtraOpc) {
15703 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr;
15704 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr;
15705 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr;
15706 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr;
15707 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr;
15708 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
15709 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
15710 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
15711 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr;
15712 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
15713 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
15714 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
15715 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr;
15716 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
15717 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
15718 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
15719 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr;
15720 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
15721 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
15722 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
15724 llvm_unreachable("Unhandled atomic-load-op opcode!");
15727 // Get opcode of the non-atomic one from the specified atomic instruction for
15728 // 64-bit data type on 32-bit target.
15729 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
15731 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr;
15732 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr;
15733 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr;
15734 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr;
15735 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr;
15736 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
15737 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr;
15738 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr;
15739 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr;
15740 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr;
15742 llvm_unreachable("Unhandled atomic-load-op opcode!");
15745 // Get opcode of the non-atomic one from the specified atomic instruction for
15746 // 64-bit data type on 32-bit target with extra opcode.
15747 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
15749 unsigned &ExtraOpc) {
15751 case X86::ATOMNAND6432:
15752 ExtraOpc = X86::NOT32r;
15753 HiOpc = X86::AND32rr;
15754 return X86::AND32rr;
15756 llvm_unreachable("Unhandled atomic-load-op opcode!");
15759 // Get pseudo CMOV opcode from the specified data type.
15760 static unsigned getPseudoCMOVOpc(EVT VT) {
15761 switch (VT.getSimpleVT().SimpleTy) {
15762 case MVT::i8: return X86::CMOV_GR8;
15763 case MVT::i16: return X86::CMOV_GR16;
15764 case MVT::i32: return X86::CMOV_GR32;
15768 llvm_unreachable("Unknown CMOV opcode!");
15771 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
15772 // They will be translated into a spin-loop or compare-exchange loop from
15775 // dst = atomic-fetch-op MI.addr, MI.val
15781 // t1 = LOAD MI.addr
15783 // t4 = phi(t1, t3 / loop)
15784 // t2 = OP MI.val, t4
15786 // LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
15792 MachineBasicBlock *
15793 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
15794 MachineBasicBlock *MBB) const {
15795 MachineFunction *MF = MBB->getParent();
15796 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
15797 DebugLoc DL = MI->getDebugLoc();
15799 MachineRegisterInfo &MRI = MF->getRegInfo();
15801 const BasicBlock *BB = MBB->getBasicBlock();
15802 MachineFunction::iterator I = MBB;
15805 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
15806 "Unexpected number of operands");
15808 assert(MI->hasOneMemOperand() &&
15809 "Expected atomic-load-op to have one memoperand");
15811 // Memory Reference
15812 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15813 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15815 unsigned DstReg, SrcReg;
15816 unsigned MemOpndSlot;
15818 unsigned CurOp = 0;
15820 DstReg = MI->getOperand(CurOp++).getReg();
15821 MemOpndSlot = CurOp;
15822 CurOp += X86::AddrNumOperands;
15823 SrcReg = MI->getOperand(CurOp++).getReg();
15825 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15826 MVT::SimpleValueType VT = *RC->vt_begin();
15827 unsigned t1 = MRI.createVirtualRegister(RC);
15828 unsigned t2 = MRI.createVirtualRegister(RC);
15829 unsigned t3 = MRI.createVirtualRegister(RC);
15830 unsigned t4 = MRI.createVirtualRegister(RC);
15831 unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
15833 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
15834 unsigned LOADOpc = getLoadOpcode(VT);
15836 // For the atomic load-arith operator, we generate
15839 // t1 = LOAD [MI.addr]
15841 // t4 = phi(t1 / thisMBB, t3 / mainMBB)
15842 // t1 = OP MI.val, EAX
15844 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
15850 MachineBasicBlock *thisMBB = MBB;
15851 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15852 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15853 MF->insert(I, mainMBB);
15854 MF->insert(I, sinkMBB);
15856 MachineInstrBuilder MIB;
15858 // Transfer the remainder of BB and its successor edges to sinkMBB.
15859 sinkMBB->splice(sinkMBB->begin(), MBB,
15860 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15861 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15864 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
15865 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15866 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15868 NewMO.setIsKill(false);
15869 MIB.addOperand(NewMO);
15871 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15872 unsigned flags = (*MMOI)->getFlags();
15873 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15874 MachineMemOperand *MMO =
15875 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15876 (*MMOI)->getSize(),
15877 (*MMOI)->getBaseAlignment(),
15878 (*MMOI)->getTBAAInfo(),
15879 (*MMOI)->getRanges());
15880 MIB.addMemOperand(MMO);
15883 thisMBB->addSuccessor(mainMBB);
15886 MachineBasicBlock *origMainMBB = mainMBB;
15889 MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
15890 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15892 unsigned Opc = MI->getOpcode();
15895 llvm_unreachable("Unhandled atomic-load-op opcode!");
15896 case X86::ATOMAND8:
15897 case X86::ATOMAND16:
15898 case X86::ATOMAND32:
15899 case X86::ATOMAND64:
15901 case X86::ATOMOR16:
15902 case X86::ATOMOR32:
15903 case X86::ATOMOR64:
15904 case X86::ATOMXOR8:
15905 case X86::ATOMXOR16:
15906 case X86::ATOMXOR32:
15907 case X86::ATOMXOR64: {
15908 unsigned ARITHOpc = getNonAtomicOpcode(Opc);
15909 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
15913 case X86::ATOMNAND8:
15914 case X86::ATOMNAND16:
15915 case X86::ATOMNAND32:
15916 case X86::ATOMNAND64: {
15917 unsigned Tmp = MRI.createVirtualRegister(RC);
15919 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
15920 BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
15922 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
15925 case X86::ATOMMAX8:
15926 case X86::ATOMMAX16:
15927 case X86::ATOMMAX32:
15928 case X86::ATOMMAX64:
15929 case X86::ATOMMIN8:
15930 case X86::ATOMMIN16:
15931 case X86::ATOMMIN32:
15932 case X86::ATOMMIN64:
15933 case X86::ATOMUMAX8:
15934 case X86::ATOMUMAX16:
15935 case X86::ATOMUMAX32:
15936 case X86::ATOMUMAX64:
15937 case X86::ATOMUMIN8:
15938 case X86::ATOMUMIN16:
15939 case X86::ATOMUMIN32:
15940 case X86::ATOMUMIN64: {
15942 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
15944 BuildMI(mainMBB, DL, TII->get(CMPOpc))
15948 if (Subtarget->hasCMov()) {
15949 if (VT != MVT::i8) {
15951 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
15955 // Promote i8 to i32 to use CMOV32
15956 const TargetRegisterInfo* TRI = MF->getTarget().getRegisterInfo();
15957 const TargetRegisterClass *RC32 =
15958 TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
15959 unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
15960 unsigned AccReg32 = MRI.createVirtualRegister(RC32);
15961 unsigned Tmp = MRI.createVirtualRegister(RC32);
15963 unsigned Undef = MRI.createVirtualRegister(RC32);
15964 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
15966 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
15969 .addImm(X86::sub_8bit);
15970 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
15973 .addImm(X86::sub_8bit);
15975 BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
15979 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
15980 .addReg(Tmp, 0, X86::sub_8bit);
15983 // Use pseudo select and lower them.
15984 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
15985 "Invalid atomic-load-op transformation!");
15986 unsigned SelOpc = getPseudoCMOVOpc(VT);
15987 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
15988 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
15989 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
15990 .addReg(SrcReg).addReg(t4)
15992 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15993 // Replace the original PHI node as mainMBB is changed after CMOV
15995 BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
15996 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15997 Phi->eraseFromParent();
16003 // Copy PhyReg back from virtual register.
16004 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
16007 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
16008 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16009 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
16011 NewMO.setIsKill(false);
16012 MIB.addOperand(NewMO);
16015 MIB.setMemRefs(MMOBegin, MMOEnd);
16017 // Copy PhyReg back to virtual register.
16018 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
16021 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
16023 mainMBB->addSuccessor(origMainMBB);
16024 mainMBB->addSuccessor(sinkMBB);
16027 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16028 TII->get(TargetOpcode::COPY), DstReg)
16031 MI->eraseFromParent();
16035 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
16036 // instructions. They will be translated into a spin-loop or compare-exchange
16040 // dst = atomic-fetch-op MI.addr, MI.val
16046 // t1L = LOAD [MI.addr + 0]
16047 // t1H = LOAD [MI.addr + 4]
16049 // t4L = phi(t1L, t3L / loop)
16050 // t4H = phi(t1H, t3H / loop)
16051 // t2L = OP MI.val.lo, t4L
16052 // t2H = OP MI.val.hi, t4H
16057 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
16065 MachineBasicBlock *
16066 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
16067 MachineBasicBlock *MBB) const {
16068 MachineFunction *MF = MBB->getParent();
16069 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
16070 DebugLoc DL = MI->getDebugLoc();
16072 MachineRegisterInfo &MRI = MF->getRegInfo();
16074 const BasicBlock *BB = MBB->getBasicBlock();
16075 MachineFunction::iterator I = MBB;
16078 assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
16079 "Unexpected number of operands");
16081 assert(MI->hasOneMemOperand() &&
16082 "Expected atomic-load-op32 to have one memoperand");
16084 // Memory Reference
16085 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16086 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16088 unsigned DstLoReg, DstHiReg;
16089 unsigned SrcLoReg, SrcHiReg;
16090 unsigned MemOpndSlot;
16092 unsigned CurOp = 0;
16094 DstLoReg = MI->getOperand(CurOp++).getReg();
16095 DstHiReg = MI->getOperand(CurOp++).getReg();
16096 MemOpndSlot = CurOp;
16097 CurOp += X86::AddrNumOperands;
16098 SrcLoReg = MI->getOperand(CurOp++).getReg();
16099 SrcHiReg = MI->getOperand(CurOp++).getReg();
16101 const TargetRegisterClass *RC = &X86::GR32RegClass;
16102 const TargetRegisterClass *RC8 = &X86::GR8RegClass;
16104 unsigned t1L = MRI.createVirtualRegister(RC);
16105 unsigned t1H = MRI.createVirtualRegister(RC);
16106 unsigned t2L = MRI.createVirtualRegister(RC);
16107 unsigned t2H = MRI.createVirtualRegister(RC);
16108 unsigned t3L = MRI.createVirtualRegister(RC);
16109 unsigned t3H = MRI.createVirtualRegister(RC);
16110 unsigned t4L = MRI.createVirtualRegister(RC);
16111 unsigned t4H = MRI.createVirtualRegister(RC);
16113 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
16114 unsigned LOADOpc = X86::MOV32rm;
16116 // For the atomic load-arith operator, we generate
16119 // t1L = LOAD [MI.addr + 0]
16120 // t1H = LOAD [MI.addr + 4]
16122 // t4L = phi(t1L / thisMBB, t3L / mainMBB)
16123 // t4H = phi(t1H / thisMBB, t3H / mainMBB)
16124 // t2L = OP MI.val.lo, t4L
16125 // t2H = OP MI.val.hi, t4H
16128 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
16136 MachineBasicBlock *thisMBB = MBB;
16137 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16138 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16139 MF->insert(I, mainMBB);
16140 MF->insert(I, sinkMBB);
16142 MachineInstrBuilder MIB;
16144 // Transfer the remainder of BB and its successor edges to sinkMBB.
16145 sinkMBB->splice(sinkMBB->begin(), MBB,
16146 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16147 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16151 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
16152 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16153 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
16155 NewMO.setIsKill(false);
16156 MIB.addOperand(NewMO);
16158 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
16159 unsigned flags = (*MMOI)->getFlags();
16160 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
16161 MachineMemOperand *MMO =
16162 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
16163 (*MMOI)->getSize(),
16164 (*MMOI)->getBaseAlignment(),
16165 (*MMOI)->getTBAAInfo(),
16166 (*MMOI)->getRanges());
16167 MIB.addMemOperand(MMO);
16169 MachineInstr *LowMI = MIB;
16172 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
16173 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16174 if (i == X86::AddrDisp) {
16175 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
16177 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
16179 NewMO.setIsKill(false);
16180 MIB.addOperand(NewMO);
16183 MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
16185 thisMBB->addSuccessor(mainMBB);
16188 MachineBasicBlock *origMainMBB = mainMBB;
16191 MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
16192 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
16193 MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
16194 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
16196 unsigned Opc = MI->getOpcode();
16199 llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
16200 case X86::ATOMAND6432:
16201 case X86::ATOMOR6432:
16202 case X86::ATOMXOR6432:
16203 case X86::ATOMADD6432:
16204 case X86::ATOMSUB6432: {
16206 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
16207 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
16209 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
16213 case X86::ATOMNAND6432: {
16214 unsigned HiOpc, NOTOpc;
16215 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
16216 unsigned TmpL = MRI.createVirtualRegister(RC);
16217 unsigned TmpH = MRI.createVirtualRegister(RC);
16218 BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
16220 BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
16222 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
16223 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
16226 case X86::ATOMMAX6432:
16227 case X86::ATOMMIN6432:
16228 case X86::ATOMUMAX6432:
16229 case X86::ATOMUMIN6432: {
16231 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
16232 unsigned cL = MRI.createVirtualRegister(RC8);
16233 unsigned cH = MRI.createVirtualRegister(RC8);
16234 unsigned cL32 = MRI.createVirtualRegister(RC);
16235 unsigned cH32 = MRI.createVirtualRegister(RC);
16236 unsigned cc = MRI.createVirtualRegister(RC);
16237 // cl := cmp src_lo, lo
16238 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
16239 .addReg(SrcLoReg).addReg(t4L);
16240 BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
16241 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
16242 // ch := cmp src_hi, hi
16243 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
16244 .addReg(SrcHiReg).addReg(t4H);
16245 BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
16246 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
16247 // cc := if (src_hi == hi) ? cl : ch;
16248 if (Subtarget->hasCMov()) {
16249 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
16250 .addReg(cH32).addReg(cL32);
16252 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
16253 .addReg(cH32).addReg(cL32)
16254 .addImm(X86::COND_E);
16255 mainMBB = EmitLoweredSelect(MIB, mainMBB);
16257 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
16258 if (Subtarget->hasCMov()) {
16259 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
16260 .addReg(SrcLoReg).addReg(t4L);
16261 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
16262 .addReg(SrcHiReg).addReg(t4H);
16264 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
16265 .addReg(SrcLoReg).addReg(t4L)
16266 .addImm(X86::COND_NE);
16267 mainMBB = EmitLoweredSelect(MIB, mainMBB);
16268 // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
16269 // 2nd CMOV lowering.
16270 mainMBB->addLiveIn(X86::EFLAGS);
16271 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
16272 .addReg(SrcHiReg).addReg(t4H)
16273 .addImm(X86::COND_NE);
16274 mainMBB = EmitLoweredSelect(MIB, mainMBB);
16275 // Replace the original PHI node as mainMBB is changed after CMOV
16277 BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
16278 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
16279 BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
16280 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
16281 PhiL->eraseFromParent();
16282 PhiH->eraseFromParent();
16286 case X86::ATOMSWAP6432: {
16288 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
16289 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
16290 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
16295 // Copy EDX:EAX back from HiReg:LoReg
16296 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
16297 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
16298 // Copy ECX:EBX from t1H:t1L
16299 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
16300 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
16302 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
16303 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16304 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
16306 NewMO.setIsKill(false);
16307 MIB.addOperand(NewMO);
16309 MIB.setMemRefs(MMOBegin, MMOEnd);
16311 // Copy EDX:EAX back to t3H:t3L
16312 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
16313 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
16315 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
16317 mainMBB->addSuccessor(origMainMBB);
16318 mainMBB->addSuccessor(sinkMBB);
16321 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16322 TII->get(TargetOpcode::COPY), DstLoReg)
16324 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16325 TII->get(TargetOpcode::COPY), DstHiReg)
16328 MI->eraseFromParent();
16332 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
16333 // or XMM0_V32I8 in AVX all of this code can be replaced with that
16334 // in the .td file.
16335 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
16336 const TargetInstrInfo *TII) {
16338 switch (MI->getOpcode()) {
16339 default: llvm_unreachable("illegal opcode!");
16340 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
16341 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
16342 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
16343 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
16344 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
16345 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
16346 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
16347 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
16350 DebugLoc dl = MI->getDebugLoc();
16351 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
16353 unsigned NumArgs = MI->getNumOperands();
16354 for (unsigned i = 1; i < NumArgs; ++i) {
16355 MachineOperand &Op = MI->getOperand(i);
16356 if (!(Op.isReg() && Op.isImplicit()))
16357 MIB.addOperand(Op);
16359 if (MI->hasOneMemOperand())
16360 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
16362 BuildMI(*BB, MI, dl,
16363 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16364 .addReg(X86::XMM0);
16366 MI->eraseFromParent();
16370 // FIXME: Custom handling because TableGen doesn't support multiple implicit
16371 // defs in an instruction pattern
16372 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
16373 const TargetInstrInfo *TII) {
16375 switch (MI->getOpcode()) {
16376 default: llvm_unreachable("illegal opcode!");
16377 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
16378 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
16379 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
16380 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
16381 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
16382 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
16383 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
16384 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
16387 DebugLoc dl = MI->getDebugLoc();
16388 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
16390 unsigned NumArgs = MI->getNumOperands(); // remove the results
16391 for (unsigned i = 1; i < NumArgs; ++i) {
16392 MachineOperand &Op = MI->getOperand(i);
16393 if (!(Op.isReg() && Op.isImplicit()))
16394 MIB.addOperand(Op);
16396 if (MI->hasOneMemOperand())
16397 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
16399 BuildMI(*BB, MI, dl,
16400 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16403 MI->eraseFromParent();
16407 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
16408 const TargetInstrInfo *TII,
16409 const X86Subtarget* Subtarget) {
16410 DebugLoc dl = MI->getDebugLoc();
16412 // Address into RAX/EAX, other two args into ECX, EDX.
16413 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
16414 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
16415 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
16416 for (int i = 0; i < X86::AddrNumOperands; ++i)
16417 MIB.addOperand(MI->getOperand(i));
16419 unsigned ValOps = X86::AddrNumOperands;
16420 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
16421 .addReg(MI->getOperand(ValOps).getReg());
16422 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
16423 .addReg(MI->getOperand(ValOps+1).getReg());
16425 // The instruction doesn't actually take any operands though.
16426 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
16428 MI->eraseFromParent(); // The pseudo is gone now.
16432 MachineBasicBlock *
16433 X86TargetLowering::EmitVAARG64WithCustomInserter(
16435 MachineBasicBlock *MBB) const {
16436 // Emit va_arg instruction on X86-64.
16438 // Operands to this pseudo-instruction:
16439 // 0 ) Output : destination address (reg)
16440 // 1-5) Input : va_list address (addr, i64mem)
16441 // 6 ) ArgSize : Size (in bytes) of vararg type
16442 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
16443 // 8 ) Align : Alignment of type
16444 // 9 ) EFLAGS (implicit-def)
16446 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
16447 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
16449 unsigned DestReg = MI->getOperand(0).getReg();
16450 MachineOperand &Base = MI->getOperand(1);
16451 MachineOperand &Scale = MI->getOperand(2);
16452 MachineOperand &Index = MI->getOperand(3);
16453 MachineOperand &Disp = MI->getOperand(4);
16454 MachineOperand &Segment = MI->getOperand(5);
16455 unsigned ArgSize = MI->getOperand(6).getImm();
16456 unsigned ArgMode = MI->getOperand(7).getImm();
16457 unsigned Align = MI->getOperand(8).getImm();
16459 // Memory Reference
16460 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
16461 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16462 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16464 // Machine Information
16465 const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
16466 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
16467 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
16468 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
16469 DebugLoc DL = MI->getDebugLoc();
16471 // struct va_list {
16474 // i64 overflow_area (address)
16475 // i64 reg_save_area (address)
16477 // sizeof(va_list) = 24
16478 // alignment(va_list) = 8
16480 unsigned TotalNumIntRegs = 6;
16481 unsigned TotalNumXMMRegs = 8;
16482 bool UseGPOffset = (ArgMode == 1);
16483 bool UseFPOffset = (ArgMode == 2);
16484 unsigned MaxOffset = TotalNumIntRegs * 8 +
16485 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
16487 /* Align ArgSize to a multiple of 8 */
16488 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
16489 bool NeedsAlign = (Align > 8);
16491 MachineBasicBlock *thisMBB = MBB;
16492 MachineBasicBlock *overflowMBB;
16493 MachineBasicBlock *offsetMBB;
16494 MachineBasicBlock *endMBB;
16496 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
16497 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
16498 unsigned OffsetReg = 0;
16500 if (!UseGPOffset && !UseFPOffset) {
16501 // If we only pull from the overflow region, we don't create a branch.
16502 // We don't need to alter control flow.
16503 OffsetDestReg = 0; // unused
16504 OverflowDestReg = DestReg;
16506 offsetMBB = nullptr;
16507 overflowMBB = thisMBB;
16510 // First emit code to check if gp_offset (or fp_offset) is below the bound.
16511 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
16512 // If not, pull from overflow_area. (branch to overflowMBB)
16517 // offsetMBB overflowMBB
16522 // Registers for the PHI in endMBB
16523 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
16524 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
16526 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
16527 MachineFunction *MF = MBB->getParent();
16528 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16529 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16530 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16532 MachineFunction::iterator MBBIter = MBB;
16535 // Insert the new basic blocks
16536 MF->insert(MBBIter, offsetMBB);
16537 MF->insert(MBBIter, overflowMBB);
16538 MF->insert(MBBIter, endMBB);
16540 // Transfer the remainder of MBB and its successor edges to endMBB.
16541 endMBB->splice(endMBB->begin(), thisMBB,
16542 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
16543 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
16545 // Make offsetMBB and overflowMBB successors of thisMBB
16546 thisMBB->addSuccessor(offsetMBB);
16547 thisMBB->addSuccessor(overflowMBB);
16549 // endMBB is a successor of both offsetMBB and overflowMBB
16550 offsetMBB->addSuccessor(endMBB);
16551 overflowMBB->addSuccessor(endMBB);
16553 // Load the offset value into a register
16554 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
16555 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
16559 .addDisp(Disp, UseFPOffset ? 4 : 0)
16560 .addOperand(Segment)
16561 .setMemRefs(MMOBegin, MMOEnd);
16563 // Check if there is enough room left to pull this argument.
16564 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
16566 .addImm(MaxOffset + 8 - ArgSizeA8);
16568 // Branch to "overflowMBB" if offset >= max
16569 // Fall through to "offsetMBB" otherwise
16570 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
16571 .addMBB(overflowMBB);
16574 // In offsetMBB, emit code to use the reg_save_area.
16576 assert(OffsetReg != 0);
16578 // Read the reg_save_area address.
16579 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
16580 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
16585 .addOperand(Segment)
16586 .setMemRefs(MMOBegin, MMOEnd);
16588 // Zero-extend the offset
16589 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
16590 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
16593 .addImm(X86::sub_32bit);
16595 // Add the offset to the reg_save_area to get the final address.
16596 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
16597 .addReg(OffsetReg64)
16598 .addReg(RegSaveReg);
16600 // Compute the offset for the next argument
16601 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
16602 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
16604 .addImm(UseFPOffset ? 16 : 8);
16606 // Store it back into the va_list.
16607 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
16611 .addDisp(Disp, UseFPOffset ? 4 : 0)
16612 .addOperand(Segment)
16613 .addReg(NextOffsetReg)
16614 .setMemRefs(MMOBegin, MMOEnd);
16617 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
16622 // Emit code to use overflow area
16625 // Load the overflow_area address into a register.
16626 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
16627 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
16632 .addOperand(Segment)
16633 .setMemRefs(MMOBegin, MMOEnd);
16635 // If we need to align it, do so. Otherwise, just copy the address
16636 // to OverflowDestReg.
16638 // Align the overflow address
16639 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
16640 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
16642 // aligned_addr = (addr + (align-1)) & ~(align-1)
16643 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
16644 .addReg(OverflowAddrReg)
16647 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
16649 .addImm(~(uint64_t)(Align-1));
16651 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
16652 .addReg(OverflowAddrReg);
16655 // Compute the next overflow address after this argument.
16656 // (the overflow address should be kept 8-byte aligned)
16657 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
16658 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
16659 .addReg(OverflowDestReg)
16660 .addImm(ArgSizeA8);
16662 // Store the new overflow address.
16663 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
16668 .addOperand(Segment)
16669 .addReg(NextAddrReg)
16670 .setMemRefs(MMOBegin, MMOEnd);
16672 // If we branched, emit the PHI to the front of endMBB.
16674 BuildMI(*endMBB, endMBB->begin(), DL,
16675 TII->get(X86::PHI), DestReg)
16676 .addReg(OffsetDestReg).addMBB(offsetMBB)
16677 .addReg(OverflowDestReg).addMBB(overflowMBB);
16680 // Erase the pseudo instruction
16681 MI->eraseFromParent();
16686 MachineBasicBlock *
16687 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
16689 MachineBasicBlock *MBB) const {
16690 // Emit code to save XMM registers to the stack. The ABI says that the
16691 // number of registers to save is given in %al, so it's theoretically
16692 // possible to do an indirect jump trick to avoid saving all of them,
16693 // however this code takes a simpler approach and just executes all
16694 // of the stores if %al is non-zero. It's less code, and it's probably
16695 // easier on the hardware branch predictor, and stores aren't all that
16696 // expensive anyway.
16698 // Create the new basic blocks. One block contains all the XMM stores,
16699 // and one block is the final destination regardless of whether any
16700 // stores were performed.
16701 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
16702 MachineFunction *F = MBB->getParent();
16703 MachineFunction::iterator MBBIter = MBB;
16705 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
16706 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
16707 F->insert(MBBIter, XMMSaveMBB);
16708 F->insert(MBBIter, EndMBB);
16710 // Transfer the remainder of MBB and its successor edges to EndMBB.
16711 EndMBB->splice(EndMBB->begin(), MBB,
16712 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16713 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
16715 // The original block will now fall through to the XMM save block.
16716 MBB->addSuccessor(XMMSaveMBB);
16717 // The XMMSaveMBB will fall through to the end block.
16718 XMMSaveMBB->addSuccessor(EndMBB);
16720 // Now add the instructions.
16721 const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
16722 DebugLoc DL = MI->getDebugLoc();
16724 unsigned CountReg = MI->getOperand(0).getReg();
16725 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
16726 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
16728 if (!Subtarget->isTargetWin64()) {
16729 // If %al is 0, branch around the XMM save block.
16730 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
16731 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
16732 MBB->addSuccessor(EndMBB);
16735 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
16736 // that was just emitted, but clearly shouldn't be "saved".
16737 assert((MI->getNumOperands() <= 3 ||
16738 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
16739 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
16740 && "Expected last argument to be EFLAGS");
16741 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
16742 // In the XMM save block, save all the XMM argument registers.
16743 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
16744 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
16745 MachineMemOperand *MMO =
16746 F->getMachineMemOperand(
16747 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
16748 MachineMemOperand::MOStore,
16749 /*Size=*/16, /*Align=*/16);
16750 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
16751 .addFrameIndex(RegSaveFrameIndex)
16752 .addImm(/*Scale=*/1)
16753 .addReg(/*IndexReg=*/0)
16754 .addImm(/*Disp=*/Offset)
16755 .addReg(/*Segment=*/0)
16756 .addReg(MI->getOperand(i).getReg())
16757 .addMemOperand(MMO);
16760 MI->eraseFromParent(); // The pseudo instruction is gone now.
16765 // The EFLAGS operand of SelectItr might be missing a kill marker
16766 // because there were multiple uses of EFLAGS, and ISel didn't know
16767 // which to mark. Figure out whether SelectItr should have had a
16768 // kill marker, and set it if it should. Returns the correct kill
16770 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
16771 MachineBasicBlock* BB,
16772 const TargetRegisterInfo* TRI) {
16773 // Scan forward through BB for a use/def of EFLAGS.
16774 MachineBasicBlock::iterator miI(std::next(SelectItr));
16775 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
16776 const MachineInstr& mi = *miI;
16777 if (mi.readsRegister(X86::EFLAGS))
16779 if (mi.definesRegister(X86::EFLAGS))
16780 break; // Should have kill-flag - update below.
16783 // If we hit the end of the block, check whether EFLAGS is live into a
16785 if (miI == BB->end()) {
16786 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
16787 sEnd = BB->succ_end();
16788 sItr != sEnd; ++sItr) {
16789 MachineBasicBlock* succ = *sItr;
16790 if (succ->isLiveIn(X86::EFLAGS))
16795 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
16796 // out. SelectMI should have a kill flag on EFLAGS.
16797 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
16801 MachineBasicBlock *
16802 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
16803 MachineBasicBlock *BB) const {
16804 const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
16805 DebugLoc DL = MI->getDebugLoc();
16807 // To "insert" a SELECT_CC instruction, we actually have to insert the
16808 // diamond control-flow pattern. The incoming instruction knows the
16809 // destination vreg to set, the condition code register to branch on, the
16810 // true/false values to select between, and a branch opcode to use.
16811 const BasicBlock *LLVM_BB = BB->getBasicBlock();
16812 MachineFunction::iterator It = BB;
16818 // cmpTY ccX, r1, r2
16820 // fallthrough --> copy0MBB
16821 MachineBasicBlock *thisMBB = BB;
16822 MachineFunction *F = BB->getParent();
16823 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
16824 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
16825 F->insert(It, copy0MBB);
16826 F->insert(It, sinkMBB);
16828 // If the EFLAGS register isn't dead in the terminator, then claim that it's
16829 // live into the sink and copy blocks.
16830 const TargetRegisterInfo* TRI = BB->getParent()->getTarget().getRegisterInfo();
16831 if (!MI->killsRegister(X86::EFLAGS) &&
16832 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
16833 copy0MBB->addLiveIn(X86::EFLAGS);
16834 sinkMBB->addLiveIn(X86::EFLAGS);
16837 // Transfer the remainder of BB and its successor edges to sinkMBB.
16838 sinkMBB->splice(sinkMBB->begin(), BB,
16839 std::next(MachineBasicBlock::iterator(MI)), BB->end());
16840 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
16842 // Add the true and fallthrough blocks as its successors.
16843 BB->addSuccessor(copy0MBB);
16844 BB->addSuccessor(sinkMBB);
16846 // Create the conditional branch instruction.
16848 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
16849 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
16852 // %FalseValue = ...
16853 // # fallthrough to sinkMBB
16854 copy0MBB->addSuccessor(sinkMBB);
16857 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
16859 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16860 TII->get(X86::PHI), MI->getOperand(0).getReg())
16861 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
16862 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
16864 MI->eraseFromParent(); // The pseudo instruction is gone now.
16868 MachineBasicBlock *
16869 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
16870 bool Is64Bit) const {
16871 MachineFunction *MF = BB->getParent();
16872 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
16873 DebugLoc DL = MI->getDebugLoc();
16874 const BasicBlock *LLVM_BB = BB->getBasicBlock();
16876 assert(MF->shouldSplitStack());
16878 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
16879 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
16882 // ... [Till the alloca]
16883 // If stacklet is not large enough, jump to mallocMBB
16886 // Allocate by subtracting from RSP
16887 // Jump to continueMBB
16890 // Allocate by call to runtime
16894 // [rest of original BB]
16897 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16898 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16899 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16901 MachineRegisterInfo &MRI = MF->getRegInfo();
16902 const TargetRegisterClass *AddrRegClass =
16903 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
16905 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16906 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16907 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
16908 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
16909 sizeVReg = MI->getOperand(1).getReg(),
16910 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
16912 MachineFunction::iterator MBBIter = BB;
16915 MF->insert(MBBIter, bumpMBB);
16916 MF->insert(MBBIter, mallocMBB);
16917 MF->insert(MBBIter, continueMBB);
16919 continueMBB->splice(continueMBB->begin(), BB,
16920 std::next(MachineBasicBlock::iterator(MI)), BB->end());
16921 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
16923 // Add code to the main basic block to check if the stack limit has been hit,
16924 // and if so, jump to mallocMBB otherwise to bumpMBB.
16925 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
16926 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
16927 .addReg(tmpSPVReg).addReg(sizeVReg);
16928 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
16929 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
16930 .addReg(SPLimitVReg);
16931 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
16933 // bumpMBB simply decreases the stack pointer, since we know the current
16934 // stacklet has enough space.
16935 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
16936 .addReg(SPLimitVReg);
16937 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
16938 .addReg(SPLimitVReg);
16939 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16941 // Calls into a routine in libgcc to allocate more space from the heap.
16942 const uint32_t *RegMask =
16943 MF->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16945 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
16947 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
16948 .addExternalSymbol("__morestack_allocate_stack_space")
16949 .addRegMask(RegMask)
16950 .addReg(X86::RDI, RegState::Implicit)
16951 .addReg(X86::RAX, RegState::ImplicitDefine);
16953 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
16955 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
16956 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
16957 .addExternalSymbol("__morestack_allocate_stack_space")
16958 .addRegMask(RegMask)
16959 .addReg(X86::EAX, RegState::ImplicitDefine);
16963 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
16966 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
16967 .addReg(Is64Bit ? X86::RAX : X86::EAX);
16968 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16970 // Set up the CFG correctly.
16971 BB->addSuccessor(bumpMBB);
16972 BB->addSuccessor(mallocMBB);
16973 mallocMBB->addSuccessor(continueMBB);
16974 bumpMBB->addSuccessor(continueMBB);
16976 // Take care of the PHI nodes.
16977 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
16978 MI->getOperand(0).getReg())
16979 .addReg(mallocPtrVReg).addMBB(mallocMBB)
16980 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
16982 // Delete the original pseudo instruction.
16983 MI->eraseFromParent();
16986 return continueMBB;
16989 MachineBasicBlock *
16990 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
16991 MachineBasicBlock *BB) const {
16992 const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
16993 DebugLoc DL = MI->getDebugLoc();
16995 assert(!Subtarget->isTargetMacho());
16997 // The lowering is pretty easy: we're just emitting the call to _alloca. The
16998 // non-trivial part is impdef of ESP.
17000 if (Subtarget->isTargetWin64()) {
17001 if (Subtarget->isTargetCygMing()) {
17002 // ___chkstk(Mingw64):
17003 // Clobbers R10, R11, RAX and EFLAGS.
17005 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
17006 .addExternalSymbol("___chkstk")
17007 .addReg(X86::RAX, RegState::Implicit)
17008 .addReg(X86::RSP, RegState::Implicit)
17009 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
17010 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
17011 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17013 // __chkstk(MSVCRT): does not update stack pointer.
17014 // Clobbers R10, R11 and EFLAGS.
17015 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
17016 .addExternalSymbol("__chkstk")
17017 .addReg(X86::RAX, RegState::Implicit)
17018 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17019 // RAX has the offset to be subtracted from RSP.
17020 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
17025 const char *StackProbeSymbol =
17026 Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
17028 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
17029 .addExternalSymbol(StackProbeSymbol)
17030 .addReg(X86::EAX, RegState::Implicit)
17031 .addReg(X86::ESP, RegState::Implicit)
17032 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
17033 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
17034 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17037 MI->eraseFromParent(); // The pseudo instruction is gone now.
17041 MachineBasicBlock *
17042 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
17043 MachineBasicBlock *BB) const {
17044 // This is pretty easy. We're taking the value that we received from
17045 // our load from the relocation, sticking it in either RDI (x86-64)
17046 // or EAX and doing an indirect call. The return value will then
17047 // be in the normal return register.
17048 MachineFunction *F = BB->getParent();
17049 const X86InstrInfo *TII
17050 = static_cast<const X86InstrInfo*>(F->getTarget().getInstrInfo());
17051 DebugLoc DL = MI->getDebugLoc();
17053 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
17054 assert(MI->getOperand(3).isGlobal() && "This should be a global");
17056 // Get a register mask for the lowered call.
17057 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
17058 // proper register mask.
17059 const uint32_t *RegMask =
17060 F->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
17061 if (Subtarget->is64Bit()) {
17062 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17063 TII->get(X86::MOV64rm), X86::RDI)
17065 .addImm(0).addReg(0)
17066 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17067 MI->getOperand(3).getTargetFlags())
17069 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
17070 addDirectMem(MIB, X86::RDI);
17071 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
17072 } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
17073 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17074 TII->get(X86::MOV32rm), X86::EAX)
17076 .addImm(0).addReg(0)
17077 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17078 MI->getOperand(3).getTargetFlags())
17080 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
17081 addDirectMem(MIB, X86::EAX);
17082 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
17084 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17085 TII->get(X86::MOV32rm), X86::EAX)
17086 .addReg(TII->getGlobalBaseReg(F))
17087 .addImm(0).addReg(0)
17088 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17089 MI->getOperand(3).getTargetFlags())
17091 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
17092 addDirectMem(MIB, X86::EAX);
17093 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
17096 MI->eraseFromParent(); // The pseudo instruction is gone now.
17100 MachineBasicBlock *
17101 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
17102 MachineBasicBlock *MBB) const {
17103 DebugLoc DL = MI->getDebugLoc();
17104 MachineFunction *MF = MBB->getParent();
17105 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17106 MachineRegisterInfo &MRI = MF->getRegInfo();
17108 const BasicBlock *BB = MBB->getBasicBlock();
17109 MachineFunction::iterator I = MBB;
17112 // Memory Reference
17113 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17114 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17117 unsigned MemOpndSlot = 0;
17119 unsigned CurOp = 0;
17121 DstReg = MI->getOperand(CurOp++).getReg();
17122 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
17123 assert(RC->hasType(MVT::i32) && "Invalid destination!");
17124 unsigned mainDstReg = MRI.createVirtualRegister(RC);
17125 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
17127 MemOpndSlot = CurOp;
17129 MVT PVT = getPointerTy();
17130 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
17131 "Invalid Pointer Size!");
17133 // For v = setjmp(buf), we generate
17136 // buf[LabelOffset] = restoreMBB
17137 // SjLjSetup restoreMBB
17143 // v = phi(main, restore)
17148 MachineBasicBlock *thisMBB = MBB;
17149 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17150 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17151 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
17152 MF->insert(I, mainMBB);
17153 MF->insert(I, sinkMBB);
17154 MF->push_back(restoreMBB);
17156 MachineInstrBuilder MIB;
17158 // Transfer the remainder of BB and its successor edges to sinkMBB.
17159 sinkMBB->splice(sinkMBB->begin(), MBB,
17160 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17161 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17164 unsigned PtrStoreOpc = 0;
17165 unsigned LabelReg = 0;
17166 const int64_t LabelOffset = 1 * PVT.getStoreSize();
17167 Reloc::Model RM = MF->getTarget().getRelocationModel();
17168 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
17169 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
17171 // Prepare IP either in reg or imm.
17172 if (!UseImmLabel) {
17173 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
17174 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
17175 LabelReg = MRI.createVirtualRegister(PtrRC);
17176 if (Subtarget->is64Bit()) {
17177 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
17181 .addMBB(restoreMBB)
17184 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
17185 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
17186 .addReg(XII->getGlobalBaseReg(MF))
17189 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
17193 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
17195 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
17196 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17197 if (i == X86::AddrDisp)
17198 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
17200 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
17203 MIB.addReg(LabelReg);
17205 MIB.addMBB(restoreMBB);
17206 MIB.setMemRefs(MMOBegin, MMOEnd);
17208 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
17209 .addMBB(restoreMBB);
17211 const X86RegisterInfo *RegInfo =
17212 static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
17213 MIB.addRegMask(RegInfo->getNoPreservedMask());
17214 thisMBB->addSuccessor(mainMBB);
17215 thisMBB->addSuccessor(restoreMBB);
17219 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
17220 mainMBB->addSuccessor(sinkMBB);
17223 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17224 TII->get(X86::PHI), DstReg)
17225 .addReg(mainDstReg).addMBB(mainMBB)
17226 .addReg(restoreDstReg).addMBB(restoreMBB);
17229 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
17230 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
17231 restoreMBB->addSuccessor(sinkMBB);
17233 MI->eraseFromParent();
17237 MachineBasicBlock *
17238 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
17239 MachineBasicBlock *MBB) const {
17240 DebugLoc DL = MI->getDebugLoc();
17241 MachineFunction *MF = MBB->getParent();
17242 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17243 MachineRegisterInfo &MRI = MF->getRegInfo();
17245 // Memory Reference
17246 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17247 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17249 MVT PVT = getPointerTy();
17250 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
17251 "Invalid Pointer Size!");
17253 const TargetRegisterClass *RC =
17254 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
17255 unsigned Tmp = MRI.createVirtualRegister(RC);
17256 // Since FP is only updated here but NOT referenced, it's treated as GPR.
17257 const X86RegisterInfo *RegInfo =
17258 static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
17259 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
17260 unsigned SP = RegInfo->getStackRegister();
17262 MachineInstrBuilder MIB;
17264 const int64_t LabelOffset = 1 * PVT.getStoreSize();
17265 const int64_t SPOffset = 2 * PVT.getStoreSize();
17267 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
17268 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
17271 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
17272 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
17273 MIB.addOperand(MI->getOperand(i));
17274 MIB.setMemRefs(MMOBegin, MMOEnd);
17276 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
17277 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17278 if (i == X86::AddrDisp)
17279 MIB.addDisp(MI->getOperand(i), LabelOffset);
17281 MIB.addOperand(MI->getOperand(i));
17283 MIB.setMemRefs(MMOBegin, MMOEnd);
17285 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
17286 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17287 if (i == X86::AddrDisp)
17288 MIB.addDisp(MI->getOperand(i), SPOffset);
17290 MIB.addOperand(MI->getOperand(i));
17292 MIB.setMemRefs(MMOBegin, MMOEnd);
17294 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
17296 MI->eraseFromParent();
17300 // Replace 213-type (isel default) FMA3 instructions with 231-type for
17301 // accumulator loops. Writing back to the accumulator allows the coalescer
17302 // to remove extra copies in the loop.
17303 MachineBasicBlock *
17304 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
17305 MachineBasicBlock *MBB) const {
17306 MachineOperand &AddendOp = MI->getOperand(3);
17308 // Bail out early if the addend isn't a register - we can't switch these.
17309 if (!AddendOp.isReg())
17312 MachineFunction &MF = *MBB->getParent();
17313 MachineRegisterInfo &MRI = MF.getRegInfo();
17315 // Check whether the addend is defined by a PHI:
17316 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
17317 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
17318 if (!AddendDef.isPHI())
17321 // Look for the following pattern:
17323 // %addend = phi [%entry, 0], [%loop, %result]
17325 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
17329 // %addend = phi [%entry, 0], [%loop, %result]
17331 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
17333 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
17334 assert(AddendDef.getOperand(i).isReg());
17335 MachineOperand PHISrcOp = AddendDef.getOperand(i);
17336 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
17337 if (&PHISrcInst == MI) {
17338 // Found a matching instruction.
17339 unsigned NewFMAOpc = 0;
17340 switch (MI->getOpcode()) {
17341 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
17342 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
17343 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
17344 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
17345 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
17346 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
17347 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
17348 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
17349 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
17350 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
17351 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
17352 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
17353 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
17354 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
17355 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
17356 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
17357 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
17358 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
17359 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
17360 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
17361 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
17362 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
17363 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
17364 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
17365 default: llvm_unreachable("Unrecognized FMA variant.");
17368 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
17369 MachineInstrBuilder MIB =
17370 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
17371 .addOperand(MI->getOperand(0))
17372 .addOperand(MI->getOperand(3))
17373 .addOperand(MI->getOperand(2))
17374 .addOperand(MI->getOperand(1));
17375 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
17376 MI->eraseFromParent();
17383 MachineBasicBlock *
17384 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
17385 MachineBasicBlock *BB) const {
17386 switch (MI->getOpcode()) {
17387 default: llvm_unreachable("Unexpected instr type to insert");
17388 case X86::TAILJMPd64:
17389 case X86::TAILJMPr64:
17390 case X86::TAILJMPm64:
17391 llvm_unreachable("TAILJMP64 would not be touched here.");
17392 case X86::TCRETURNdi64:
17393 case X86::TCRETURNri64:
17394 case X86::TCRETURNmi64:
17396 case X86::WIN_ALLOCA:
17397 return EmitLoweredWinAlloca(MI, BB);
17398 case X86::SEG_ALLOCA_32:
17399 return EmitLoweredSegAlloca(MI, BB, false);
17400 case X86::SEG_ALLOCA_64:
17401 return EmitLoweredSegAlloca(MI, BB, true);
17402 case X86::TLSCall_32:
17403 case X86::TLSCall_64:
17404 return EmitLoweredTLSCall(MI, BB);
17405 case X86::CMOV_GR8:
17406 case X86::CMOV_FR32:
17407 case X86::CMOV_FR64:
17408 case X86::CMOV_V4F32:
17409 case X86::CMOV_V2F64:
17410 case X86::CMOV_V2I64:
17411 case X86::CMOV_V8F32:
17412 case X86::CMOV_V4F64:
17413 case X86::CMOV_V4I64:
17414 case X86::CMOV_V16F32:
17415 case X86::CMOV_V8F64:
17416 case X86::CMOV_V8I64:
17417 case X86::CMOV_GR16:
17418 case X86::CMOV_GR32:
17419 case X86::CMOV_RFP32:
17420 case X86::CMOV_RFP64:
17421 case X86::CMOV_RFP80:
17422 return EmitLoweredSelect(MI, BB);
17424 case X86::FP32_TO_INT16_IN_MEM:
17425 case X86::FP32_TO_INT32_IN_MEM:
17426 case X86::FP32_TO_INT64_IN_MEM:
17427 case X86::FP64_TO_INT16_IN_MEM:
17428 case X86::FP64_TO_INT32_IN_MEM:
17429 case X86::FP64_TO_INT64_IN_MEM:
17430 case X86::FP80_TO_INT16_IN_MEM:
17431 case X86::FP80_TO_INT32_IN_MEM:
17432 case X86::FP80_TO_INT64_IN_MEM: {
17433 MachineFunction *F = BB->getParent();
17434 const TargetInstrInfo *TII = F->getTarget().getInstrInfo();
17435 DebugLoc DL = MI->getDebugLoc();
17437 // Change the floating point control register to use "round towards zero"
17438 // mode when truncating to an integer value.
17439 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
17440 addFrameReference(BuildMI(*BB, MI, DL,
17441 TII->get(X86::FNSTCW16m)), CWFrameIdx);
17443 // Load the old value of the high byte of the control word...
17445 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
17446 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
17449 // Set the high part to be round to zero...
17450 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
17453 // Reload the modified control word now...
17454 addFrameReference(BuildMI(*BB, MI, DL,
17455 TII->get(X86::FLDCW16m)), CWFrameIdx);
17457 // Restore the memory image of control word to original value
17458 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
17461 // Get the X86 opcode to use.
17463 switch (MI->getOpcode()) {
17464 default: llvm_unreachable("illegal opcode!");
17465 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
17466 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
17467 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
17468 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
17469 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
17470 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
17471 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
17472 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
17473 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
17477 MachineOperand &Op = MI->getOperand(0);
17479 AM.BaseType = X86AddressMode::RegBase;
17480 AM.Base.Reg = Op.getReg();
17482 AM.BaseType = X86AddressMode::FrameIndexBase;
17483 AM.Base.FrameIndex = Op.getIndex();
17485 Op = MI->getOperand(1);
17487 AM.Scale = Op.getImm();
17488 Op = MI->getOperand(2);
17490 AM.IndexReg = Op.getImm();
17491 Op = MI->getOperand(3);
17492 if (Op.isGlobal()) {
17493 AM.GV = Op.getGlobal();
17495 AM.Disp = Op.getImm();
17497 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
17498 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
17500 // Reload the original control word now.
17501 addFrameReference(BuildMI(*BB, MI, DL,
17502 TII->get(X86::FLDCW16m)), CWFrameIdx);
17504 MI->eraseFromParent(); // The pseudo instruction is gone now.
17507 // String/text processing lowering.
17508 case X86::PCMPISTRM128REG:
17509 case X86::VPCMPISTRM128REG:
17510 case X86::PCMPISTRM128MEM:
17511 case X86::VPCMPISTRM128MEM:
17512 case X86::PCMPESTRM128REG:
17513 case X86::VPCMPESTRM128REG:
17514 case X86::PCMPESTRM128MEM:
17515 case X86::VPCMPESTRM128MEM:
17516 assert(Subtarget->hasSSE42() &&
17517 "Target must have SSE4.2 or AVX features enabled");
17518 return EmitPCMPSTRM(MI, BB, BB->getParent()->getTarget().getInstrInfo());
17520 // String/text processing lowering.
17521 case X86::PCMPISTRIREG:
17522 case X86::VPCMPISTRIREG:
17523 case X86::PCMPISTRIMEM:
17524 case X86::VPCMPISTRIMEM:
17525 case X86::PCMPESTRIREG:
17526 case X86::VPCMPESTRIREG:
17527 case X86::PCMPESTRIMEM:
17528 case X86::VPCMPESTRIMEM:
17529 assert(Subtarget->hasSSE42() &&
17530 "Target must have SSE4.2 or AVX features enabled");
17531 return EmitPCMPSTRI(MI, BB, BB->getParent()->getTarget().getInstrInfo());
17533 // Thread synchronization.
17535 return EmitMonitor(MI, BB, BB->getParent()->getTarget().getInstrInfo(), Subtarget);
17539 return EmitXBegin(MI, BB, BB->getParent()->getTarget().getInstrInfo());
17541 // Atomic Lowering.
17542 case X86::ATOMAND8:
17543 case X86::ATOMAND16:
17544 case X86::ATOMAND32:
17545 case X86::ATOMAND64:
17548 case X86::ATOMOR16:
17549 case X86::ATOMOR32:
17550 case X86::ATOMOR64:
17552 case X86::ATOMXOR16:
17553 case X86::ATOMXOR8:
17554 case X86::ATOMXOR32:
17555 case X86::ATOMXOR64:
17557 case X86::ATOMNAND8:
17558 case X86::ATOMNAND16:
17559 case X86::ATOMNAND32:
17560 case X86::ATOMNAND64:
17562 case X86::ATOMMAX8:
17563 case X86::ATOMMAX16:
17564 case X86::ATOMMAX32:
17565 case X86::ATOMMAX64:
17567 case X86::ATOMMIN8:
17568 case X86::ATOMMIN16:
17569 case X86::ATOMMIN32:
17570 case X86::ATOMMIN64:
17572 case X86::ATOMUMAX8:
17573 case X86::ATOMUMAX16:
17574 case X86::ATOMUMAX32:
17575 case X86::ATOMUMAX64:
17577 case X86::ATOMUMIN8:
17578 case X86::ATOMUMIN16:
17579 case X86::ATOMUMIN32:
17580 case X86::ATOMUMIN64:
17581 return EmitAtomicLoadArith(MI, BB);
17583 // This group does 64-bit operations on a 32-bit host.
17584 case X86::ATOMAND6432:
17585 case X86::ATOMOR6432:
17586 case X86::ATOMXOR6432:
17587 case X86::ATOMNAND6432:
17588 case X86::ATOMADD6432:
17589 case X86::ATOMSUB6432:
17590 case X86::ATOMMAX6432:
17591 case X86::ATOMMIN6432:
17592 case X86::ATOMUMAX6432:
17593 case X86::ATOMUMIN6432:
17594 case X86::ATOMSWAP6432:
17595 return EmitAtomicLoadArith6432(MI, BB);
17597 case X86::VASTART_SAVE_XMM_REGS:
17598 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
17600 case X86::VAARG_64:
17601 return EmitVAARG64WithCustomInserter(MI, BB);
17603 case X86::EH_SjLj_SetJmp32:
17604 case X86::EH_SjLj_SetJmp64:
17605 return emitEHSjLjSetJmp(MI, BB);
17607 case X86::EH_SjLj_LongJmp32:
17608 case X86::EH_SjLj_LongJmp64:
17609 return emitEHSjLjLongJmp(MI, BB);
17611 case TargetOpcode::STACKMAP:
17612 case TargetOpcode::PATCHPOINT:
17613 return emitPatchPoint(MI, BB);
17615 case X86::VFMADDPDr213r:
17616 case X86::VFMADDPSr213r:
17617 case X86::VFMADDSDr213r:
17618 case X86::VFMADDSSr213r:
17619 case X86::VFMSUBPDr213r:
17620 case X86::VFMSUBPSr213r:
17621 case X86::VFMSUBSDr213r:
17622 case X86::VFMSUBSSr213r:
17623 case X86::VFNMADDPDr213r:
17624 case X86::VFNMADDPSr213r:
17625 case X86::VFNMADDSDr213r:
17626 case X86::VFNMADDSSr213r:
17627 case X86::VFNMSUBPDr213r:
17628 case X86::VFNMSUBPSr213r:
17629 case X86::VFNMSUBSDr213r:
17630 case X86::VFNMSUBSSr213r:
17631 case X86::VFMADDPDr213rY:
17632 case X86::VFMADDPSr213rY:
17633 case X86::VFMSUBPDr213rY:
17634 case X86::VFMSUBPSr213rY:
17635 case X86::VFNMADDPDr213rY:
17636 case X86::VFNMADDPSr213rY:
17637 case X86::VFNMSUBPDr213rY:
17638 case X86::VFNMSUBPSr213rY:
17639 return emitFMA3Instr(MI, BB);
17643 //===----------------------------------------------------------------------===//
17644 // X86 Optimization Hooks
17645 //===----------------------------------------------------------------------===//
17647 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
17650 const SelectionDAG &DAG,
17651 unsigned Depth) const {
17652 unsigned BitWidth = KnownZero.getBitWidth();
17653 unsigned Opc = Op.getOpcode();
17654 assert((Opc >= ISD::BUILTIN_OP_END ||
17655 Opc == ISD::INTRINSIC_WO_CHAIN ||
17656 Opc == ISD::INTRINSIC_W_CHAIN ||
17657 Opc == ISD::INTRINSIC_VOID) &&
17658 "Should use MaskedValueIsZero if you don't know whether Op"
17659 " is a target node!");
17661 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
17675 // These nodes' second result is a boolean.
17676 if (Op.getResNo() == 0)
17679 case X86ISD::SETCC:
17680 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
17682 case ISD::INTRINSIC_WO_CHAIN: {
17683 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17684 unsigned NumLoBits = 0;
17687 case Intrinsic::x86_sse_movmsk_ps:
17688 case Intrinsic::x86_avx_movmsk_ps_256:
17689 case Intrinsic::x86_sse2_movmsk_pd:
17690 case Intrinsic::x86_avx_movmsk_pd_256:
17691 case Intrinsic::x86_mmx_pmovmskb:
17692 case Intrinsic::x86_sse2_pmovmskb_128:
17693 case Intrinsic::x86_avx2_pmovmskb: {
17694 // High bits of movmskp{s|d}, pmovmskb are known zero.
17696 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
17697 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
17698 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
17699 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
17700 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
17701 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
17702 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
17703 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
17705 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
17714 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
17716 const SelectionDAG &,
17717 unsigned Depth) const {
17718 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
17719 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
17720 return Op.getValueType().getScalarType().getSizeInBits();
17726 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
17727 /// node is a GlobalAddress + offset.
17728 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
17729 const GlobalValue* &GA,
17730 int64_t &Offset) const {
17731 if (N->getOpcode() == X86ISD::Wrapper) {
17732 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
17733 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
17734 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
17738 return TargetLowering::isGAPlusOffset(N, GA, Offset);
17741 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
17742 /// same as extracting the high 128-bit part of 256-bit vector and then
17743 /// inserting the result into the low part of a new 256-bit vector
17744 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
17745 EVT VT = SVOp->getValueType(0);
17746 unsigned NumElems = VT.getVectorNumElements();
17748 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17749 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
17750 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17751 SVOp->getMaskElt(j) >= 0)
17757 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
17758 /// same as extracting the low 128-bit part of 256-bit vector and then
17759 /// inserting the result into the high part of a new 256-bit vector
17760 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
17761 EVT VT = SVOp->getValueType(0);
17762 unsigned NumElems = VT.getVectorNumElements();
17764 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17765 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
17766 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17767 SVOp->getMaskElt(j) >= 0)
17773 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
17774 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
17775 TargetLowering::DAGCombinerInfo &DCI,
17776 const X86Subtarget* Subtarget) {
17778 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17779 SDValue V1 = SVOp->getOperand(0);
17780 SDValue V2 = SVOp->getOperand(1);
17781 EVT VT = SVOp->getValueType(0);
17782 unsigned NumElems = VT.getVectorNumElements();
17784 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
17785 V2.getOpcode() == ISD::CONCAT_VECTORS) {
17789 // V UNDEF BUILD_VECTOR UNDEF
17791 // CONCAT_VECTOR CONCAT_VECTOR
17794 // RESULT: V + zero extended
17796 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
17797 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
17798 V1.getOperand(1).getOpcode() != ISD::UNDEF)
17801 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
17804 // To match the shuffle mask, the first half of the mask should
17805 // be exactly the first vector, and all the rest a splat with the
17806 // first element of the second one.
17807 for (unsigned i = 0; i != NumElems/2; ++i)
17808 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
17809 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
17812 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
17813 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
17814 if (Ld->hasNUsesOfValue(1, 0)) {
17815 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
17816 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
17818 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
17820 Ld->getPointerInfo(),
17821 Ld->getAlignment(),
17822 false/*isVolatile*/, true/*ReadMem*/,
17823 false/*WriteMem*/);
17825 // Make sure the newly-created LOAD is in the same position as Ld in
17826 // terms of dependency. We create a TokenFactor for Ld and ResNode,
17827 // and update uses of Ld's output chain to use the TokenFactor.
17828 if (Ld->hasAnyUseOfValue(1)) {
17829 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17830 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
17831 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
17832 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
17833 SDValue(ResNode.getNode(), 1));
17836 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
17840 // Emit a zeroed vector and insert the desired subvector on its
17842 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17843 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
17844 return DCI.CombineTo(N, InsV);
17847 //===--------------------------------------------------------------------===//
17848 // Combine some shuffles into subvector extracts and inserts:
17851 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17852 if (isShuffleHigh128VectorInsertLow(SVOp)) {
17853 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
17854 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
17855 return DCI.CombineTo(N, InsV);
17858 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17859 if (isShuffleLow128VectorInsertHigh(SVOp)) {
17860 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
17861 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
17862 return DCI.CombineTo(N, InsV);
17868 /// PerformShuffleCombine - Performs several different shuffle combines.
17869 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
17870 TargetLowering::DAGCombinerInfo &DCI,
17871 const X86Subtarget *Subtarget) {
17873 SDValue N0 = N->getOperand(0);
17874 SDValue N1 = N->getOperand(1);
17875 EVT VT = N->getValueType(0);
17877 // Don't create instructions with illegal types after legalize types has run.
17878 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17879 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
17882 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
17883 if (Subtarget->hasFp256() && VT.is256BitVector() &&
17884 N->getOpcode() == ISD::VECTOR_SHUFFLE)
17885 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
17887 // During Type Legalization, when promoting illegal vector types,
17888 // the backend might introduce new shuffle dag nodes and bitcasts.
17890 // This code performs the following transformation:
17891 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
17892 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
17894 // We do this only if both the bitcast and the BINOP dag nodes have
17895 // one use. Also, perform this transformation only if the new binary
17896 // operation is legal. This is to avoid introducing dag nodes that
17897 // potentially need to be further expanded (or custom lowered) into a
17898 // less optimal sequence of dag nodes.
17899 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
17900 N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
17901 N0.getOpcode() == ISD::BITCAST) {
17902 SDValue BC0 = N0.getOperand(0);
17903 EVT SVT = BC0.getValueType();
17904 unsigned Opcode = BC0.getOpcode();
17905 unsigned NumElts = VT.getVectorNumElements();
17907 if (BC0.hasOneUse() && SVT.isVector() &&
17908 SVT.getVectorNumElements() * 2 == NumElts &&
17909 TLI.isOperationLegal(Opcode, VT)) {
17910 bool CanFold = false;
17922 unsigned SVTNumElts = SVT.getVectorNumElements();
17923 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17924 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
17925 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
17926 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
17927 CanFold = SVOp->getMaskElt(i) < 0;
17930 SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
17931 SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
17932 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
17933 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
17938 // Only handle 128 wide vector from here on.
17939 if (!VT.is128BitVector())
17942 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
17943 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
17944 // consecutive, non-overlapping, and in the right order.
17945 SmallVector<SDValue, 16> Elts;
17946 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
17947 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
17949 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
17952 /// PerformTruncateCombine - Converts truncate operation to
17953 /// a sequence of vector shuffle operations.
17954 /// It is possible when we truncate 256-bit vector to 128-bit vector
17955 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
17956 TargetLowering::DAGCombinerInfo &DCI,
17957 const X86Subtarget *Subtarget) {
17961 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
17962 /// specific shuffle of a load can be folded into a single element load.
17963 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
17964 /// shuffles have been customed lowered so we need to handle those here.
17965 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
17966 TargetLowering::DAGCombinerInfo &DCI) {
17967 if (DCI.isBeforeLegalizeOps())
17970 SDValue InVec = N->getOperand(0);
17971 SDValue EltNo = N->getOperand(1);
17973 if (!isa<ConstantSDNode>(EltNo))
17976 EVT VT = InVec.getValueType();
17978 bool HasShuffleIntoBitcast = false;
17979 if (InVec.getOpcode() == ISD::BITCAST) {
17980 // Don't duplicate a load with other uses.
17981 if (!InVec.hasOneUse())
17983 EVT BCVT = InVec.getOperand(0).getValueType();
17984 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
17986 InVec = InVec.getOperand(0);
17987 HasShuffleIntoBitcast = true;
17990 if (!isTargetShuffle(InVec.getOpcode()))
17993 // Don't duplicate a load with other uses.
17994 if (!InVec.hasOneUse())
17997 SmallVector<int, 16> ShuffleMask;
17999 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
18003 // Select the input vector, guarding against out of range extract vector.
18004 unsigned NumElems = VT.getVectorNumElements();
18005 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
18006 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
18007 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
18008 : InVec.getOperand(1);
18010 // If inputs to shuffle are the same for both ops, then allow 2 uses
18011 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
18013 if (LdNode.getOpcode() == ISD::BITCAST) {
18014 // Don't duplicate a load with other uses.
18015 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
18018 AllowedUses = 1; // only allow 1 load use if we have a bitcast
18019 LdNode = LdNode.getOperand(0);
18022 if (!ISD::isNormalLoad(LdNode.getNode()))
18025 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
18027 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
18030 if (HasShuffleIntoBitcast) {
18031 // If there's a bitcast before the shuffle, check if the load type and
18032 // alignment is valid.
18033 unsigned Align = LN0->getAlignment();
18034 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18035 unsigned NewAlign = TLI.getDataLayout()->
18036 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
18038 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
18042 // All checks match so transform back to vector_shuffle so that DAG combiner
18043 // can finish the job
18046 // Create shuffle node taking into account the case that its a unary shuffle
18047 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
18048 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
18049 InVec.getOperand(0), Shuffle,
18051 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
18052 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
18056 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
18057 /// generation and convert it from being a bunch of shuffles and extracts
18058 /// to a simple store and scalar loads to extract the elements.
18059 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
18060 TargetLowering::DAGCombinerInfo &DCI) {
18061 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
18062 if (NewOp.getNode())
18065 SDValue InputVector = N->getOperand(0);
18067 // Detect whether we are trying to convert from mmx to i32 and the bitcast
18068 // from mmx to v2i32 has a single usage.
18069 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
18070 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
18071 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
18072 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
18073 N->getValueType(0),
18074 InputVector.getNode()->getOperand(0));
18076 // Only operate on vectors of 4 elements, where the alternative shuffling
18077 // gets to be more expensive.
18078 if (InputVector.getValueType() != MVT::v4i32)
18081 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
18082 // single use which is a sign-extend or zero-extend, and all elements are
18084 SmallVector<SDNode *, 4> Uses;
18085 unsigned ExtractedElements = 0;
18086 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
18087 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
18088 if (UI.getUse().getResNo() != InputVector.getResNo())
18091 SDNode *Extract = *UI;
18092 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
18095 if (Extract->getValueType(0) != MVT::i32)
18097 if (!Extract->hasOneUse())
18099 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
18100 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
18102 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
18105 // Record which element was extracted.
18106 ExtractedElements |=
18107 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
18109 Uses.push_back(Extract);
18112 // If not all the elements were used, this may not be worthwhile.
18113 if (ExtractedElements != 15)
18116 // Ok, we've now decided to do the transformation.
18117 SDLoc dl(InputVector);
18119 // Store the value to a temporary stack slot.
18120 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
18121 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
18122 MachinePointerInfo(), false, false, 0);
18124 // Replace each use (extract) with a load of the appropriate element.
18125 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
18126 UE = Uses.end(); UI != UE; ++UI) {
18127 SDNode *Extract = *UI;
18129 // cOMpute the element's address.
18130 SDValue Idx = Extract->getOperand(1);
18132 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
18133 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
18134 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18135 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
18137 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
18138 StackPtr, OffsetVal);
18140 // Load the scalar.
18141 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
18142 ScalarAddr, MachinePointerInfo(),
18143 false, false, false, 0);
18145 // Replace the exact with the load.
18146 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
18149 // The replacement was made in place; don't return anything.
18153 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
18154 static std::pair<unsigned, bool>
18155 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
18156 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
18157 if (!VT.isVector())
18158 return std::make_pair(0, false);
18160 bool NeedSplit = false;
18161 switch (VT.getSimpleVT().SimpleTy) {
18162 default: return std::make_pair(0, false);
18166 if (!Subtarget->hasAVX2())
18168 if (!Subtarget->hasAVX())
18169 return std::make_pair(0, false);
18174 if (!Subtarget->hasSSE2())
18175 return std::make_pair(0, false);
18178 // SSE2 has only a small subset of the operations.
18179 bool hasUnsigned = Subtarget->hasSSE41() ||
18180 (Subtarget->hasSSE2() && VT == MVT::v16i8);
18181 bool hasSigned = Subtarget->hasSSE41() ||
18182 (Subtarget->hasSSE2() && VT == MVT::v8i16);
18184 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18187 // Check for x CC y ? x : y.
18188 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
18189 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
18194 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
18197 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
18200 Opc = hasSigned ? X86ISD::SMIN : 0; break;
18203 Opc = hasSigned ? X86ISD::SMAX : 0; break;
18205 // Check for x CC y ? y : x -- a min/max with reversed arms.
18206 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
18207 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
18212 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
18215 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
18218 Opc = hasSigned ? X86ISD::SMAX : 0; break;
18221 Opc = hasSigned ? X86ISD::SMIN : 0; break;
18225 return std::make_pair(Opc, NeedSplit);
18229 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
18230 const X86Subtarget *Subtarget) {
18232 SDValue Cond = N->getOperand(0);
18233 SDValue LHS = N->getOperand(1);
18234 SDValue RHS = N->getOperand(2);
18236 if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
18237 SDValue CondSrc = Cond->getOperand(0);
18238 if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
18239 Cond = CondSrc->getOperand(0);
18242 MVT VT = N->getSimpleValueType(0);
18243 MVT EltVT = VT.getVectorElementType();
18244 unsigned NumElems = VT.getVectorNumElements();
18245 // There is no blend with immediate in AVX-512.
18246 if (VT.is512BitVector())
18249 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
18251 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
18254 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
18257 unsigned MaskValue = 0;
18258 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
18261 SmallVector<int, 8> ShuffleMask(NumElems, -1);
18262 for (unsigned i = 0; i < NumElems; ++i) {
18263 // Be sure we emit undef where we can.
18264 if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
18265 ShuffleMask[i] = -1;
18267 ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
18270 return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
18273 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
18275 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
18276 TargetLowering::DAGCombinerInfo &DCI,
18277 const X86Subtarget *Subtarget) {
18279 SDValue Cond = N->getOperand(0);
18280 // Get the LHS/RHS of the select.
18281 SDValue LHS = N->getOperand(1);
18282 SDValue RHS = N->getOperand(2);
18283 EVT VT = LHS.getValueType();
18284 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18286 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
18287 // instructions match the semantics of the common C idiom x<y?x:y but not
18288 // x<=y?x:y, because of how they handle negative zero (which can be
18289 // ignored in unsafe-math mode).
18290 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
18291 VT != MVT::f80 && TLI.isTypeLegal(VT) &&
18292 (Subtarget->hasSSE2() ||
18293 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
18294 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18296 unsigned Opcode = 0;
18297 // Check for x CC y ? x : y.
18298 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
18299 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
18303 // Converting this to a min would handle NaNs incorrectly, and swapping
18304 // the operands would cause it to handle comparisons between positive
18305 // and negative zero incorrectly.
18306 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
18307 if (!DAG.getTarget().Options.UnsafeFPMath &&
18308 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
18310 std::swap(LHS, RHS);
18312 Opcode = X86ISD::FMIN;
18315 // Converting this to a min would handle comparisons between positive
18316 // and negative zero incorrectly.
18317 if (!DAG.getTarget().Options.UnsafeFPMath &&
18318 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
18320 Opcode = X86ISD::FMIN;
18323 // Converting this to a min would handle both negative zeros and NaNs
18324 // incorrectly, but we can swap the operands to fix both.
18325 std::swap(LHS, RHS);
18329 Opcode = X86ISD::FMIN;
18333 // Converting this to a max would handle comparisons between positive
18334 // and negative zero incorrectly.
18335 if (!DAG.getTarget().Options.UnsafeFPMath &&
18336 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
18338 Opcode = X86ISD::FMAX;
18341 // Converting this to a max would handle NaNs incorrectly, and swapping
18342 // the operands would cause it to handle comparisons between positive
18343 // and negative zero incorrectly.
18344 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
18345 if (!DAG.getTarget().Options.UnsafeFPMath &&
18346 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
18348 std::swap(LHS, RHS);
18350 Opcode = X86ISD::FMAX;
18353 // Converting this to a max would handle both negative zeros and NaNs
18354 // incorrectly, but we can swap the operands to fix both.
18355 std::swap(LHS, RHS);
18359 Opcode = X86ISD::FMAX;
18362 // Check for x CC y ? y : x -- a min/max with reversed arms.
18363 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
18364 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
18368 // Converting this to a min would handle comparisons between positive
18369 // and negative zero incorrectly, and swapping the operands would
18370 // cause it to handle NaNs incorrectly.
18371 if (!DAG.getTarget().Options.UnsafeFPMath &&
18372 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
18373 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
18375 std::swap(LHS, RHS);
18377 Opcode = X86ISD::FMIN;
18380 // Converting this to a min would handle NaNs incorrectly.
18381 if (!DAG.getTarget().Options.UnsafeFPMath &&
18382 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
18384 Opcode = X86ISD::FMIN;
18387 // Converting this to a min would handle both negative zeros and NaNs
18388 // incorrectly, but we can swap the operands to fix both.
18389 std::swap(LHS, RHS);
18393 Opcode = X86ISD::FMIN;
18397 // Converting this to a max would handle NaNs incorrectly.
18398 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
18400 Opcode = X86ISD::FMAX;
18403 // Converting this to a max would handle comparisons between positive
18404 // and negative zero incorrectly, and swapping the operands would
18405 // cause it to handle NaNs incorrectly.
18406 if (!DAG.getTarget().Options.UnsafeFPMath &&
18407 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
18408 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
18410 std::swap(LHS, RHS);
18412 Opcode = X86ISD::FMAX;
18415 // Converting this to a max would handle both negative zeros and NaNs
18416 // incorrectly, but we can swap the operands to fix both.
18417 std::swap(LHS, RHS);
18421 Opcode = X86ISD::FMAX;
18427 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
18430 EVT CondVT = Cond.getValueType();
18431 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
18432 CondVT.getVectorElementType() == MVT::i1) {
18433 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
18434 // lowering on AVX-512. In this case we convert it to
18435 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
18436 // The same situation for all 128 and 256-bit vectors of i8 and i16
18437 EVT OpVT = LHS.getValueType();
18438 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
18439 (OpVT.getVectorElementType() == MVT::i8 ||
18440 OpVT.getVectorElementType() == MVT::i16)) {
18441 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
18442 DCI.AddToWorklist(Cond.getNode());
18443 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
18446 // If this is a select between two integer constants, try to do some
18448 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
18449 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
18450 // Don't do this for crazy integer types.
18451 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
18452 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
18453 // so that TrueC (the true value) is larger than FalseC.
18454 bool NeedsCondInvert = false;
18456 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
18457 // Efficiently invertible.
18458 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
18459 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
18460 isa<ConstantSDNode>(Cond.getOperand(1))))) {
18461 NeedsCondInvert = true;
18462 std::swap(TrueC, FalseC);
18465 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
18466 if (FalseC->getAPIntValue() == 0 &&
18467 TrueC->getAPIntValue().isPowerOf2()) {
18468 if (NeedsCondInvert) // Invert the condition if needed.
18469 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18470 DAG.getConstant(1, Cond.getValueType()));
18472 // Zero extend the condition if needed.
18473 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
18475 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18476 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
18477 DAG.getConstant(ShAmt, MVT::i8));
18480 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
18481 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18482 if (NeedsCondInvert) // Invert the condition if needed.
18483 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18484 DAG.getConstant(1, Cond.getValueType()));
18486 // Zero extend the condition if needed.
18487 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18488 FalseC->getValueType(0), Cond);
18489 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18490 SDValue(FalseC, 0));
18493 // Optimize cases that will turn into an LEA instruction. This requires
18494 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18495 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18496 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18497 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18499 bool isFastMultiplier = false;
18501 switch ((unsigned char)Diff) {
18503 case 1: // result = add base, cond
18504 case 2: // result = lea base( , cond*2)
18505 case 3: // result = lea base(cond, cond*2)
18506 case 4: // result = lea base( , cond*4)
18507 case 5: // result = lea base(cond, cond*4)
18508 case 8: // result = lea base( , cond*8)
18509 case 9: // result = lea base(cond, cond*8)
18510 isFastMultiplier = true;
18515 if (isFastMultiplier) {
18516 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18517 if (NeedsCondInvert) // Invert the condition if needed.
18518 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18519 DAG.getConstant(1, Cond.getValueType()));
18521 // Zero extend the condition if needed.
18522 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18524 // Scale the condition by the difference.
18526 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18527 DAG.getConstant(Diff, Cond.getValueType()));
18529 // Add the base if non-zero.
18530 if (FalseC->getAPIntValue() != 0)
18531 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18532 SDValue(FalseC, 0));
18539 // Canonicalize max and min:
18540 // (x > y) ? x : y -> (x >= y) ? x : y
18541 // (x < y) ? x : y -> (x <= y) ? x : y
18542 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
18543 // the need for an extra compare
18544 // against zero. e.g.
18545 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
18547 // testl %edi, %edi
18549 // cmovgl %edi, %eax
18553 // cmovsl %eax, %edi
18554 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
18555 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
18556 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
18557 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18562 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
18563 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
18564 Cond.getOperand(0), Cond.getOperand(1), NewCC);
18565 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
18570 // Early exit check
18571 if (!TLI.isTypeLegal(VT))
18574 // Match VSELECTs into subs with unsigned saturation.
18575 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
18576 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
18577 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
18578 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
18579 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18581 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
18582 // left side invert the predicate to simplify logic below.
18584 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
18586 CC = ISD::getSetCCInverse(CC, true);
18587 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
18591 if (Other.getNode() && Other->getNumOperands() == 2 &&
18592 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
18593 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
18594 SDValue CondRHS = Cond->getOperand(1);
18596 // Look for a general sub with unsigned saturation first.
18597 // x >= y ? x-y : 0 --> subus x, y
18598 // x > y ? x-y : 0 --> subus x, y
18599 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
18600 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
18601 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
18603 // If the RHS is a constant we have to reverse the const canonicalization.
18604 // x > C-1 ? x+-C : 0 --> subus x, C
18605 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
18606 isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
18607 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
18608 if (CondRHS.getConstantOperandVal(0) == -A-1)
18609 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
18610 DAG.getConstant(-A, VT));
18613 // Another special case: If C was a sign bit, the sub has been
18614 // canonicalized into a xor.
18615 // FIXME: Would it be better to use computeKnownBits to determine whether
18616 // it's safe to decanonicalize the xor?
18617 // x s< 0 ? x^C : 0 --> subus x, C
18618 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
18619 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
18620 isSplatVector(OpRHS.getNode())) {
18621 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
18623 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
18628 // Try to match a min/max vector operation.
18629 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
18630 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
18631 unsigned Opc = ret.first;
18632 bool NeedSplit = ret.second;
18634 if (Opc && NeedSplit) {
18635 unsigned NumElems = VT.getVectorNumElements();
18636 // Extract the LHS vectors
18637 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
18638 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
18640 // Extract the RHS vectors
18641 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
18642 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
18644 // Create min/max for each subvector
18645 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
18646 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
18648 // Merge the result
18649 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
18651 return DAG.getNode(Opc, DL, VT, LHS, RHS);
18654 // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
18655 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
18656 // Check if SETCC has already been promoted
18657 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
18658 // Check that condition value type matches vselect operand type
18661 assert(Cond.getValueType().isVector() &&
18662 "vector select expects a vector selector!");
18664 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
18665 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
18667 if (!TValIsAllOnes && !FValIsAllZeros) {
18668 // Try invert the condition if true value is not all 1s and false value
18670 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
18671 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
18673 if (TValIsAllZeros || FValIsAllOnes) {
18674 SDValue CC = Cond.getOperand(2);
18675 ISD::CondCode NewCC =
18676 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
18677 Cond.getOperand(0).getValueType().isInteger());
18678 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
18679 std::swap(LHS, RHS);
18680 TValIsAllOnes = FValIsAllOnes;
18681 FValIsAllZeros = TValIsAllZeros;
18685 if (TValIsAllOnes || FValIsAllZeros) {
18688 if (TValIsAllOnes && FValIsAllZeros)
18690 else if (TValIsAllOnes)
18691 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
18692 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
18693 else if (FValIsAllZeros)
18694 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
18695 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
18697 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
18701 // Try to fold this VSELECT into a MOVSS/MOVSD
18702 if (N->getOpcode() == ISD::VSELECT &&
18703 Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
18704 if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
18705 (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
18706 bool CanFold = false;
18707 unsigned NumElems = Cond.getNumOperands();
18711 if (isZero(Cond.getOperand(0))) {
18714 // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
18715 // fold (vselect <0,-1> -> (movsd A, B)
18716 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
18717 CanFold = isAllOnes(Cond.getOperand(i));
18718 } else if (isAllOnes(Cond.getOperand(0))) {
18722 // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
18723 // fold (vselect <-1,0> -> (movsd B, A)
18724 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
18725 CanFold = isZero(Cond.getOperand(i));
18729 if (VT == MVT::v4i32 || VT == MVT::v4f32)
18730 return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
18731 return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
18734 if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
18735 // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
18736 // (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
18737 // (v2i64 (bitcast B)))))
18739 // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
18740 // (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
18741 // (v2f64 (bitcast B)))))
18743 // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
18744 // (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
18745 // (v2i64 (bitcast A)))))
18747 // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
18748 // (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
18749 // (v2f64 (bitcast A)))))
18751 CanFold = (isZero(Cond.getOperand(0)) &&
18752 isZero(Cond.getOperand(1)) &&
18753 isAllOnes(Cond.getOperand(2)) &&
18754 isAllOnes(Cond.getOperand(3)));
18756 if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
18757 isAllOnes(Cond.getOperand(1)) &&
18758 isZero(Cond.getOperand(2)) &&
18759 isZero(Cond.getOperand(3))) {
18761 std::swap(LHS, RHS);
18765 EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
18766 SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
18767 SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
18768 SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
18770 return DAG.getNode(ISD::BITCAST, DL, VT, Select);
18776 // If we know that this node is legal then we know that it is going to be
18777 // matched by one of the SSE/AVX BLEND instructions. These instructions only
18778 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
18779 // to simplify previous instructions.
18780 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
18781 !DCI.isBeforeLegalize() &&
18782 // We explicitly check against v8i16 and v16i16 because, although
18783 // they're marked as Custom, they might only be legal when Cond is a
18784 // build_vector of constants. This will be taken care in a later
18786 (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
18787 VT != MVT::v8i16)) {
18788 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
18790 // Don't optimize vector selects that map to mask-registers.
18794 // Check all uses of that condition operand to check whether it will be
18795 // consumed by non-BLEND instructions, which may depend on all bits are set
18797 for (SDNode::use_iterator I = Cond->use_begin(),
18798 E = Cond->use_end(); I != E; ++I)
18799 if (I->getOpcode() != ISD::VSELECT)
18800 // TODO: Add other opcodes eventually lowered into BLEND.
18803 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
18804 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
18806 APInt KnownZero, KnownOne;
18807 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
18808 DCI.isBeforeLegalizeOps());
18809 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
18810 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
18811 DCI.CommitTargetLoweringOpt(TLO);
18814 // We should generate an X86ISD::BLENDI from a vselect if its argument
18815 // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
18816 // constants. This specific pattern gets generated when we split a
18817 // selector for a 512 bit vector in a machine without AVX512 (but with
18818 // 256-bit vectors), during legalization:
18820 // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
18822 // Iff we find this pattern and the build_vectors are built from
18823 // constants, we translate the vselect into a shuffle_vector that we
18824 // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
18825 if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
18826 SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
18827 if (Shuffle.getNode())
18834 // Check whether a boolean test is testing a boolean value generated by
18835 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
18838 // Simplify the following patterns:
18839 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
18840 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
18841 // to (Op EFLAGS Cond)
18843 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
18844 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
18845 // to (Op EFLAGS !Cond)
18847 // where Op could be BRCOND or CMOV.
18849 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
18850 // Quit if not CMP and SUB with its value result used.
18851 if (Cmp.getOpcode() != X86ISD::CMP &&
18852 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
18855 // Quit if not used as a boolean value.
18856 if (CC != X86::COND_E && CC != X86::COND_NE)
18859 // Check CMP operands. One of them should be 0 or 1 and the other should be
18860 // an SetCC or extended from it.
18861 SDValue Op1 = Cmp.getOperand(0);
18862 SDValue Op2 = Cmp.getOperand(1);
18865 const ConstantSDNode* C = nullptr;
18866 bool needOppositeCond = (CC == X86::COND_E);
18867 bool checkAgainstTrue = false; // Is it a comparison against 1?
18869 if ((C = dyn_cast<ConstantSDNode>(Op1)))
18871 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
18873 else // Quit if all operands are not constants.
18876 if (C->getZExtValue() == 1) {
18877 needOppositeCond = !needOppositeCond;
18878 checkAgainstTrue = true;
18879 } else if (C->getZExtValue() != 0)
18880 // Quit if the constant is neither 0 or 1.
18883 bool truncatedToBoolWithAnd = false;
18884 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
18885 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
18886 SetCC.getOpcode() == ISD::TRUNCATE ||
18887 SetCC.getOpcode() == ISD::AND) {
18888 if (SetCC.getOpcode() == ISD::AND) {
18890 ConstantSDNode *CS;
18891 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
18892 CS->getZExtValue() == 1)
18894 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
18895 CS->getZExtValue() == 1)
18899 SetCC = SetCC.getOperand(OpIdx);
18900 truncatedToBoolWithAnd = true;
18902 SetCC = SetCC.getOperand(0);
18905 switch (SetCC.getOpcode()) {
18906 case X86ISD::SETCC_CARRY:
18907 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
18908 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
18909 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
18910 // truncated to i1 using 'and'.
18911 if (checkAgainstTrue && !truncatedToBoolWithAnd)
18913 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
18914 "Invalid use of SETCC_CARRY!");
18916 case X86ISD::SETCC:
18917 // Set the condition code or opposite one if necessary.
18918 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
18919 if (needOppositeCond)
18920 CC = X86::GetOppositeBranchCondition(CC);
18921 return SetCC.getOperand(1);
18922 case X86ISD::CMOV: {
18923 // Check whether false/true value has canonical one, i.e. 0 or 1.
18924 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
18925 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
18926 // Quit if true value is not a constant.
18929 // Quit if false value is not a constant.
18931 SDValue Op = SetCC.getOperand(0);
18932 // Skip 'zext' or 'trunc' node.
18933 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
18934 Op.getOpcode() == ISD::TRUNCATE)
18935 Op = Op.getOperand(0);
18936 // A special case for rdrand/rdseed, where 0 is set if false cond is
18938 if ((Op.getOpcode() != X86ISD::RDRAND &&
18939 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
18942 // Quit if false value is not the constant 0 or 1.
18943 bool FValIsFalse = true;
18944 if (FVal && FVal->getZExtValue() != 0) {
18945 if (FVal->getZExtValue() != 1)
18947 // If FVal is 1, opposite cond is needed.
18948 needOppositeCond = !needOppositeCond;
18949 FValIsFalse = false;
18951 // Quit if TVal is not the constant opposite of FVal.
18952 if (FValIsFalse && TVal->getZExtValue() != 1)
18954 if (!FValIsFalse && TVal->getZExtValue() != 0)
18956 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
18957 if (needOppositeCond)
18958 CC = X86::GetOppositeBranchCondition(CC);
18959 return SetCC.getOperand(3);
18966 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
18967 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
18968 TargetLowering::DAGCombinerInfo &DCI,
18969 const X86Subtarget *Subtarget) {
18972 // If the flag operand isn't dead, don't touch this CMOV.
18973 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
18976 SDValue FalseOp = N->getOperand(0);
18977 SDValue TrueOp = N->getOperand(1);
18978 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
18979 SDValue Cond = N->getOperand(3);
18981 if (CC == X86::COND_E || CC == X86::COND_NE) {
18982 switch (Cond.getOpcode()) {
18986 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
18987 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
18988 return (CC == X86::COND_E) ? FalseOp : TrueOp;
18994 Flags = checkBoolTestSetCCCombine(Cond, CC);
18995 if (Flags.getNode() &&
18996 // Extra check as FCMOV only supports a subset of X86 cond.
18997 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
18998 SDValue Ops[] = { FalseOp, TrueOp,
18999 DAG.getConstant(CC, MVT::i8), Flags };
19000 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
19003 // If this is a select between two integer constants, try to do some
19004 // optimizations. Note that the operands are ordered the opposite of SELECT
19006 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
19007 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
19008 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
19009 // larger than FalseC (the false value).
19010 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
19011 CC = X86::GetOppositeBranchCondition(CC);
19012 std::swap(TrueC, FalseC);
19013 std::swap(TrueOp, FalseOp);
19016 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
19017 // This is efficient for any integer data type (including i8/i16) and
19019 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
19020 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
19021 DAG.getConstant(CC, MVT::i8), Cond);
19023 // Zero extend the condition if needed.
19024 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
19026 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
19027 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
19028 DAG.getConstant(ShAmt, MVT::i8));
19029 if (N->getNumValues() == 2) // Dead flag value?
19030 return DCI.CombineTo(N, Cond, SDValue());
19034 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
19035 // for any integer data type, including i8/i16.
19036 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
19037 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
19038 DAG.getConstant(CC, MVT::i8), Cond);
19040 // Zero extend the condition if needed.
19041 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
19042 FalseC->getValueType(0), Cond);
19043 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19044 SDValue(FalseC, 0));
19046 if (N->getNumValues() == 2) // Dead flag value?
19047 return DCI.CombineTo(N, Cond, SDValue());
19051 // Optimize cases that will turn into an LEA instruction. This requires
19052 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
19053 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
19054 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
19055 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
19057 bool isFastMultiplier = false;
19059 switch ((unsigned char)Diff) {
19061 case 1: // result = add base, cond
19062 case 2: // result = lea base( , cond*2)
19063 case 3: // result = lea base(cond, cond*2)
19064 case 4: // result = lea base( , cond*4)
19065 case 5: // result = lea base(cond, cond*4)
19066 case 8: // result = lea base( , cond*8)
19067 case 9: // result = lea base(cond, cond*8)
19068 isFastMultiplier = true;
19073 if (isFastMultiplier) {
19074 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
19075 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
19076 DAG.getConstant(CC, MVT::i8), Cond);
19077 // Zero extend the condition if needed.
19078 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
19080 // Scale the condition by the difference.
19082 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
19083 DAG.getConstant(Diff, Cond.getValueType()));
19085 // Add the base if non-zero.
19086 if (FalseC->getAPIntValue() != 0)
19087 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19088 SDValue(FalseC, 0));
19089 if (N->getNumValues() == 2) // Dead flag value?
19090 return DCI.CombineTo(N, Cond, SDValue());
19097 // Handle these cases:
19098 // (select (x != c), e, c) -> select (x != c), e, x),
19099 // (select (x == c), c, e) -> select (x == c), x, e)
19100 // where the c is an integer constant, and the "select" is the combination
19101 // of CMOV and CMP.
19103 // The rationale for this change is that the conditional-move from a constant
19104 // needs two instructions, however, conditional-move from a register needs
19105 // only one instruction.
19107 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
19108 // some instruction-combining opportunities. This opt needs to be
19109 // postponed as late as possible.
19111 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
19112 // the DCI.xxxx conditions are provided to postpone the optimization as
19113 // late as possible.
19115 ConstantSDNode *CmpAgainst = nullptr;
19116 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
19117 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
19118 !isa<ConstantSDNode>(Cond.getOperand(0))) {
19120 if (CC == X86::COND_NE &&
19121 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
19122 CC = X86::GetOppositeBranchCondition(CC);
19123 std::swap(TrueOp, FalseOp);
19126 if (CC == X86::COND_E &&
19127 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
19128 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
19129 DAG.getConstant(CC, MVT::i8), Cond };
19130 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
19138 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
19139 const X86Subtarget *Subtarget) {
19140 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
19142 default: return SDValue();
19143 // SSE/AVX/AVX2 blend intrinsics.
19144 case Intrinsic::x86_avx2_pblendvb:
19145 case Intrinsic::x86_avx2_pblendw:
19146 case Intrinsic::x86_avx2_pblendd_128:
19147 case Intrinsic::x86_avx2_pblendd_256:
19148 // Don't try to simplify this intrinsic if we don't have AVX2.
19149 if (!Subtarget->hasAVX2())
19152 case Intrinsic::x86_avx_blend_pd_256:
19153 case Intrinsic::x86_avx_blend_ps_256:
19154 case Intrinsic::x86_avx_blendv_pd_256:
19155 case Intrinsic::x86_avx_blendv_ps_256:
19156 // Don't try to simplify this intrinsic if we don't have AVX.
19157 if (!Subtarget->hasAVX())
19160 case Intrinsic::x86_sse41_pblendw:
19161 case Intrinsic::x86_sse41_blendpd:
19162 case Intrinsic::x86_sse41_blendps:
19163 case Intrinsic::x86_sse41_blendvps:
19164 case Intrinsic::x86_sse41_blendvpd:
19165 case Intrinsic::x86_sse41_pblendvb: {
19166 SDValue Op0 = N->getOperand(1);
19167 SDValue Op1 = N->getOperand(2);
19168 SDValue Mask = N->getOperand(3);
19170 // Don't try to simplify this intrinsic if we don't have SSE4.1.
19171 if (!Subtarget->hasSSE41())
19174 // fold (blend A, A, Mask) -> A
19177 // fold (blend A, B, allZeros) -> A
19178 if (ISD::isBuildVectorAllZeros(Mask.getNode()))
19180 // fold (blend A, B, allOnes) -> B
19181 if (ISD::isBuildVectorAllOnes(Mask.getNode()))
19184 // Simplify the case where the mask is a constant i32 value.
19185 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
19186 if (C->isNullValue())
19188 if (C->isAllOnesValue())
19193 // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
19194 case Intrinsic::x86_sse2_psrai_w:
19195 case Intrinsic::x86_sse2_psrai_d:
19196 case Intrinsic::x86_avx2_psrai_w:
19197 case Intrinsic::x86_avx2_psrai_d:
19198 case Intrinsic::x86_sse2_psra_w:
19199 case Intrinsic::x86_sse2_psra_d:
19200 case Intrinsic::x86_avx2_psra_w:
19201 case Intrinsic::x86_avx2_psra_d: {
19202 SDValue Op0 = N->getOperand(1);
19203 SDValue Op1 = N->getOperand(2);
19204 EVT VT = Op0.getValueType();
19205 assert(VT.isVector() && "Expected a vector type!");
19207 if (isa<BuildVectorSDNode>(Op1))
19208 Op1 = Op1.getOperand(0);
19210 if (!isa<ConstantSDNode>(Op1))
19213 EVT SVT = VT.getVectorElementType();
19214 unsigned SVTBits = SVT.getSizeInBits();
19216 ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
19217 const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
19218 uint64_t ShAmt = C.getZExtValue();
19220 // Don't try to convert this shift into a ISD::SRA if the shift
19221 // count is bigger than or equal to the element size.
19222 if (ShAmt >= SVTBits)
19225 // Trivial case: if the shift count is zero, then fold this
19226 // into the first operand.
19230 // Replace this packed shift intrinsic with a target independent
19232 SDValue Splat = DAG.getConstant(C, VT);
19233 return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
19238 /// PerformMulCombine - Optimize a single multiply with constant into two
19239 /// in order to implement it with two cheaper instructions, e.g.
19240 /// LEA + SHL, LEA + LEA.
19241 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
19242 TargetLowering::DAGCombinerInfo &DCI) {
19243 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
19246 EVT VT = N->getValueType(0);
19247 if (VT != MVT::i64)
19250 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
19253 uint64_t MulAmt = C->getZExtValue();
19254 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
19257 uint64_t MulAmt1 = 0;
19258 uint64_t MulAmt2 = 0;
19259 if ((MulAmt % 9) == 0) {
19261 MulAmt2 = MulAmt / 9;
19262 } else if ((MulAmt % 5) == 0) {
19264 MulAmt2 = MulAmt / 5;
19265 } else if ((MulAmt % 3) == 0) {
19267 MulAmt2 = MulAmt / 3;
19270 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
19273 if (isPowerOf2_64(MulAmt2) &&
19274 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
19275 // If second multiplifer is pow2, issue it first. We want the multiply by
19276 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
19278 std::swap(MulAmt1, MulAmt2);
19281 if (isPowerOf2_64(MulAmt1))
19282 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
19283 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
19285 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
19286 DAG.getConstant(MulAmt1, VT));
19288 if (isPowerOf2_64(MulAmt2))
19289 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
19290 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
19292 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
19293 DAG.getConstant(MulAmt2, VT));
19295 // Do not add new nodes to DAG combiner worklist.
19296 DCI.CombineTo(N, NewMul, false);
19301 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
19302 SDValue N0 = N->getOperand(0);
19303 SDValue N1 = N->getOperand(1);
19304 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
19305 EVT VT = N0.getValueType();
19307 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
19308 // since the result of setcc_c is all zero's or all ones.
19309 if (VT.isInteger() && !VT.isVector() &&
19310 N1C && N0.getOpcode() == ISD::AND &&
19311 N0.getOperand(1).getOpcode() == ISD::Constant) {
19312 SDValue N00 = N0.getOperand(0);
19313 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
19314 ((N00.getOpcode() == ISD::ANY_EXTEND ||
19315 N00.getOpcode() == ISD::ZERO_EXTEND) &&
19316 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
19317 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
19318 APInt ShAmt = N1C->getAPIntValue();
19319 Mask = Mask.shl(ShAmt);
19321 return DAG.getNode(ISD::AND, SDLoc(N), VT,
19322 N00, DAG.getConstant(Mask, VT));
19326 // Hardware support for vector shifts is sparse which makes us scalarize the
19327 // vector operations in many cases. Also, on sandybridge ADD is faster than
19329 // (shl V, 1) -> add V,V
19330 if (isSplatVector(N1.getNode())) {
19331 assert(N0.getValueType().isVector() && "Invalid vector shift type");
19332 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
19333 // We shift all of the values by one. In many cases we do not have
19334 // hardware support for this operation. This is better expressed as an ADD
19336 if (N1C && (1 == N1C->getZExtValue())) {
19337 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
19344 /// \brief Returns a vector of 0s if the node in input is a vector logical
19345 /// shift by a constant amount which is known to be bigger than or equal
19346 /// to the vector element size in bits.
19347 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
19348 const X86Subtarget *Subtarget) {
19349 EVT VT = N->getValueType(0);
19351 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
19352 (!Subtarget->hasInt256() ||
19353 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
19356 SDValue Amt = N->getOperand(1);
19358 if (isSplatVector(Amt.getNode())) {
19359 SDValue SclrAmt = Amt->getOperand(0);
19360 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
19361 APInt ShiftAmt = C->getAPIntValue();
19362 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
19364 // SSE2/AVX2 logical shifts always return a vector of 0s
19365 // if the shift amount is bigger than or equal to
19366 // the element size. The constant shift amount will be
19367 // encoded as a 8-bit immediate.
19368 if (ShiftAmt.trunc(8).uge(MaxAmount))
19369 return getZeroVector(VT, Subtarget, DAG, DL);
19376 /// PerformShiftCombine - Combine shifts.
19377 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
19378 TargetLowering::DAGCombinerInfo &DCI,
19379 const X86Subtarget *Subtarget) {
19380 if (N->getOpcode() == ISD::SHL) {
19381 SDValue V = PerformSHLCombine(N, DAG);
19382 if (V.getNode()) return V;
19385 if (N->getOpcode() != ISD::SRA) {
19386 // Try to fold this logical shift into a zero vector.
19387 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
19388 if (V.getNode()) return V;
19394 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
19395 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
19396 // and friends. Likewise for OR -> CMPNEQSS.
19397 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
19398 TargetLowering::DAGCombinerInfo &DCI,
19399 const X86Subtarget *Subtarget) {
19402 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
19403 // we're requiring SSE2 for both.
19404 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
19405 SDValue N0 = N->getOperand(0);
19406 SDValue N1 = N->getOperand(1);
19407 SDValue CMP0 = N0->getOperand(1);
19408 SDValue CMP1 = N1->getOperand(1);
19411 // The SETCCs should both refer to the same CMP.
19412 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
19415 SDValue CMP00 = CMP0->getOperand(0);
19416 SDValue CMP01 = CMP0->getOperand(1);
19417 EVT VT = CMP00.getValueType();
19419 if (VT == MVT::f32 || VT == MVT::f64) {
19420 bool ExpectingFlags = false;
19421 // Check for any users that want flags:
19422 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
19423 !ExpectingFlags && UI != UE; ++UI)
19424 switch (UI->getOpcode()) {
19429 ExpectingFlags = true;
19431 case ISD::CopyToReg:
19432 case ISD::SIGN_EXTEND:
19433 case ISD::ZERO_EXTEND:
19434 case ISD::ANY_EXTEND:
19438 if (!ExpectingFlags) {
19439 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
19440 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
19442 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
19443 X86::CondCode tmp = cc0;
19448 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
19449 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
19450 // FIXME: need symbolic constants for these magic numbers.
19451 // See X86ATTInstPrinter.cpp:printSSECC().
19452 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
19453 if (Subtarget->hasAVX512()) {
19454 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
19455 CMP01, DAG.getConstant(x86cc, MVT::i8));
19456 if (N->getValueType(0) != MVT::i1)
19457 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
19461 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
19462 CMP00.getValueType(), CMP00, CMP01,
19463 DAG.getConstant(x86cc, MVT::i8));
19465 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
19466 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
19468 if (is64BitFP && !Subtarget->is64Bit()) {
19469 // On a 32-bit target, we cannot bitcast the 64-bit float to a
19470 // 64-bit integer, since that's not a legal type. Since
19471 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
19472 // bits, but can do this little dance to extract the lowest 32 bits
19473 // and work with those going forward.
19474 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
19476 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
19478 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
19479 Vector32, DAG.getIntPtrConstant(0));
19483 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
19484 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
19485 DAG.getConstant(1, IntVT));
19486 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
19487 return OneBitOfTruth;
19495 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
19496 /// so it can be folded inside ANDNP.
19497 static bool CanFoldXORWithAllOnes(const SDNode *N) {
19498 EVT VT = N->getValueType(0);
19500 // Match direct AllOnes for 128 and 256-bit vectors
19501 if (ISD::isBuildVectorAllOnes(N))
19504 // Look through a bit convert.
19505 if (N->getOpcode() == ISD::BITCAST)
19506 N = N->getOperand(0).getNode();
19508 // Sometimes the operand may come from a insert_subvector building a 256-bit
19510 if (VT.is256BitVector() &&
19511 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
19512 SDValue V1 = N->getOperand(0);
19513 SDValue V2 = N->getOperand(1);
19515 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
19516 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
19517 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
19518 ISD::isBuildVectorAllOnes(V2.getNode()))
19525 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
19526 // register. In most cases we actually compare or select YMM-sized registers
19527 // and mixing the two types creates horrible code. This method optimizes
19528 // some of the transition sequences.
19529 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
19530 TargetLowering::DAGCombinerInfo &DCI,
19531 const X86Subtarget *Subtarget) {
19532 EVT VT = N->getValueType(0);
19533 if (!VT.is256BitVector())
19536 assert((N->getOpcode() == ISD::ANY_EXTEND ||
19537 N->getOpcode() == ISD::ZERO_EXTEND ||
19538 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
19540 SDValue Narrow = N->getOperand(0);
19541 EVT NarrowVT = Narrow->getValueType(0);
19542 if (!NarrowVT.is128BitVector())
19545 if (Narrow->getOpcode() != ISD::XOR &&
19546 Narrow->getOpcode() != ISD::AND &&
19547 Narrow->getOpcode() != ISD::OR)
19550 SDValue N0 = Narrow->getOperand(0);
19551 SDValue N1 = Narrow->getOperand(1);
19554 // The Left side has to be a trunc.
19555 if (N0.getOpcode() != ISD::TRUNCATE)
19558 // The type of the truncated inputs.
19559 EVT WideVT = N0->getOperand(0)->getValueType(0);
19563 // The right side has to be a 'trunc' or a constant vector.
19564 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
19565 bool RHSConst = (isSplatVector(N1.getNode()) &&
19566 isa<ConstantSDNode>(N1->getOperand(0)));
19567 if (!RHSTrunc && !RHSConst)
19570 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19572 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
19575 // Set N0 and N1 to hold the inputs to the new wide operation.
19576 N0 = N0->getOperand(0);
19578 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
19579 N1->getOperand(0));
19580 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
19581 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
19582 } else if (RHSTrunc) {
19583 N1 = N1->getOperand(0);
19586 // Generate the wide operation.
19587 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
19588 unsigned Opcode = N->getOpcode();
19590 case ISD::ANY_EXTEND:
19592 case ISD::ZERO_EXTEND: {
19593 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
19594 APInt Mask = APInt::getAllOnesValue(InBits);
19595 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
19596 return DAG.getNode(ISD::AND, DL, VT,
19597 Op, DAG.getConstant(Mask, VT));
19599 case ISD::SIGN_EXTEND:
19600 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
19601 Op, DAG.getValueType(NarrowVT));
19603 llvm_unreachable("Unexpected opcode");
19607 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
19608 TargetLowering::DAGCombinerInfo &DCI,
19609 const X86Subtarget *Subtarget) {
19610 EVT VT = N->getValueType(0);
19611 if (DCI.isBeforeLegalizeOps())
19614 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
19618 // Create BEXTR instructions
19619 // BEXTR is ((X >> imm) & (2**size-1))
19620 if (VT == MVT::i32 || VT == MVT::i64) {
19621 SDValue N0 = N->getOperand(0);
19622 SDValue N1 = N->getOperand(1);
19625 // Check for BEXTR.
19626 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
19627 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
19628 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
19629 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19630 if (MaskNode && ShiftNode) {
19631 uint64_t Mask = MaskNode->getZExtValue();
19632 uint64_t Shift = ShiftNode->getZExtValue();
19633 if (isMask_64(Mask)) {
19634 uint64_t MaskSize = CountPopulation_64(Mask);
19635 if (Shift + MaskSize <= VT.getSizeInBits())
19636 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
19637 DAG.getConstant(Shift | (MaskSize << 8), VT));
19645 // Want to form ANDNP nodes:
19646 // 1) In the hopes of then easily combining them with OR and AND nodes
19647 // to form PBLEND/PSIGN.
19648 // 2) To match ANDN packed intrinsics
19649 if (VT != MVT::v2i64 && VT != MVT::v4i64)
19652 SDValue N0 = N->getOperand(0);
19653 SDValue N1 = N->getOperand(1);
19656 // Check LHS for vnot
19657 if (N0.getOpcode() == ISD::XOR &&
19658 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
19659 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
19660 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
19662 // Check RHS for vnot
19663 if (N1.getOpcode() == ISD::XOR &&
19664 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
19665 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
19666 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
19671 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
19672 TargetLowering::DAGCombinerInfo &DCI,
19673 const X86Subtarget *Subtarget) {
19674 if (DCI.isBeforeLegalizeOps())
19677 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
19681 SDValue N0 = N->getOperand(0);
19682 SDValue N1 = N->getOperand(1);
19683 EVT VT = N->getValueType(0);
19685 // look for psign/blend
19686 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
19687 if (!Subtarget->hasSSSE3() ||
19688 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
19691 // Canonicalize pandn to RHS
19692 if (N0.getOpcode() == X86ISD::ANDNP)
19694 // or (and (m, y), (pandn m, x))
19695 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
19696 SDValue Mask = N1.getOperand(0);
19697 SDValue X = N1.getOperand(1);
19699 if (N0.getOperand(0) == Mask)
19700 Y = N0.getOperand(1);
19701 if (N0.getOperand(1) == Mask)
19702 Y = N0.getOperand(0);
19704 // Check to see if the mask appeared in both the AND and ANDNP and
19708 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
19709 // Look through mask bitcast.
19710 if (Mask.getOpcode() == ISD::BITCAST)
19711 Mask = Mask.getOperand(0);
19712 if (X.getOpcode() == ISD::BITCAST)
19713 X = X.getOperand(0);
19714 if (Y.getOpcode() == ISD::BITCAST)
19715 Y = Y.getOperand(0);
19717 EVT MaskVT = Mask.getValueType();
19719 // Validate that the Mask operand is a vector sra node.
19720 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
19721 // there is no psrai.b
19722 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
19723 unsigned SraAmt = ~0;
19724 if (Mask.getOpcode() == ISD::SRA) {
19725 SDValue Amt = Mask.getOperand(1);
19726 if (isSplatVector(Amt.getNode())) {
19727 SDValue SclrAmt = Amt->getOperand(0);
19728 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
19729 SraAmt = C->getZExtValue();
19731 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
19732 SDValue SraC = Mask.getOperand(1);
19733 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
19735 if ((SraAmt + 1) != EltBits)
19740 // Now we know we at least have a plendvb with the mask val. See if
19741 // we can form a psignb/w/d.
19742 // psign = x.type == y.type == mask.type && y = sub(0, x);
19743 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
19744 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
19745 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
19746 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
19747 "Unsupported VT for PSIGN");
19748 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
19749 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
19751 // PBLENDVB only available on SSE 4.1
19752 if (!Subtarget->hasSSE41())
19755 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
19757 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
19758 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
19759 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
19760 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
19761 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
19765 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
19768 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
19769 MachineFunction &MF = DAG.getMachineFunction();
19770 bool OptForSize = MF.getFunction()->getAttributes().
19771 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
19773 // SHLD/SHRD instructions have lower register pressure, but on some
19774 // platforms they have higher latency than the equivalent
19775 // series of shifts/or that would otherwise be generated.
19776 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
19777 // have higher latencies and we are not optimizing for size.
19778 if (!OptForSize && Subtarget->isSHLDSlow())
19781 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
19783 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
19785 if (!N0.hasOneUse() || !N1.hasOneUse())
19788 SDValue ShAmt0 = N0.getOperand(1);
19789 if (ShAmt0.getValueType() != MVT::i8)
19791 SDValue ShAmt1 = N1.getOperand(1);
19792 if (ShAmt1.getValueType() != MVT::i8)
19794 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
19795 ShAmt0 = ShAmt0.getOperand(0);
19796 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
19797 ShAmt1 = ShAmt1.getOperand(0);
19800 unsigned Opc = X86ISD::SHLD;
19801 SDValue Op0 = N0.getOperand(0);
19802 SDValue Op1 = N1.getOperand(0);
19803 if (ShAmt0.getOpcode() == ISD::SUB) {
19804 Opc = X86ISD::SHRD;
19805 std::swap(Op0, Op1);
19806 std::swap(ShAmt0, ShAmt1);
19809 unsigned Bits = VT.getSizeInBits();
19810 if (ShAmt1.getOpcode() == ISD::SUB) {
19811 SDValue Sum = ShAmt1.getOperand(0);
19812 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
19813 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
19814 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
19815 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
19816 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
19817 return DAG.getNode(Opc, DL, VT,
19819 DAG.getNode(ISD::TRUNCATE, DL,
19822 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
19823 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
19825 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
19826 return DAG.getNode(Opc, DL, VT,
19827 N0.getOperand(0), N1.getOperand(0),
19828 DAG.getNode(ISD::TRUNCATE, DL,
19835 // Generate NEG and CMOV for integer abs.
19836 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
19837 EVT VT = N->getValueType(0);
19839 // Since X86 does not have CMOV for 8-bit integer, we don't convert
19840 // 8-bit integer abs to NEG and CMOV.
19841 if (VT.isInteger() && VT.getSizeInBits() == 8)
19844 SDValue N0 = N->getOperand(0);
19845 SDValue N1 = N->getOperand(1);
19848 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
19849 // and change it to SUB and CMOV.
19850 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
19851 N0.getOpcode() == ISD::ADD &&
19852 N0.getOperand(1) == N1 &&
19853 N1.getOpcode() == ISD::SRA &&
19854 N1.getOperand(0) == N0.getOperand(0))
19855 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
19856 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
19857 // Generate SUB & CMOV.
19858 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
19859 DAG.getConstant(0, VT), N0.getOperand(0));
19861 SDValue Ops[] = { N0.getOperand(0), Neg,
19862 DAG.getConstant(X86::COND_GE, MVT::i8),
19863 SDValue(Neg.getNode(), 1) };
19864 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
19869 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
19870 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
19871 TargetLowering::DAGCombinerInfo &DCI,
19872 const X86Subtarget *Subtarget) {
19873 if (DCI.isBeforeLegalizeOps())
19876 if (Subtarget->hasCMov()) {
19877 SDValue RV = performIntegerAbsCombine(N, DAG);
19885 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
19886 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
19887 TargetLowering::DAGCombinerInfo &DCI,
19888 const X86Subtarget *Subtarget) {
19889 LoadSDNode *Ld = cast<LoadSDNode>(N);
19890 EVT RegVT = Ld->getValueType(0);
19891 EVT MemVT = Ld->getMemoryVT();
19893 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19894 unsigned RegSz = RegVT.getSizeInBits();
19896 // On Sandybridge unaligned 256bit loads are inefficient.
19897 ISD::LoadExtType Ext = Ld->getExtensionType();
19898 unsigned Alignment = Ld->getAlignment();
19899 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
19900 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
19901 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
19902 unsigned NumElems = RegVT.getVectorNumElements();
19906 SDValue Ptr = Ld->getBasePtr();
19907 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
19909 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19911 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
19912 Ld->getPointerInfo(), Ld->isVolatile(),
19913 Ld->isNonTemporal(), Ld->isInvariant(),
19915 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19916 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
19917 Ld->getPointerInfo(), Ld->isVolatile(),
19918 Ld->isNonTemporal(), Ld->isInvariant(),
19919 std::min(16U, Alignment));
19920 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19922 Load2.getValue(1));
19924 SDValue NewVec = DAG.getUNDEF(RegVT);
19925 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
19926 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
19927 return DCI.CombineTo(N, NewVec, TF, true);
19930 // If this is a vector EXT Load then attempt to optimize it using a
19931 // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
19932 // expansion is still better than scalar code.
19933 // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
19934 // emit a shuffle and a arithmetic shift.
19935 // TODO: It is possible to support ZExt by zeroing the undef values
19936 // during the shuffle phase or after the shuffle.
19937 if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
19938 (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
19939 assert(MemVT != RegVT && "Cannot extend to the same type");
19940 assert(MemVT.isVector() && "Must load a vector from memory");
19942 unsigned NumElems = RegVT.getVectorNumElements();
19943 unsigned MemSz = MemVT.getSizeInBits();
19944 assert(RegSz > MemSz && "Register size must be greater than the mem size");
19946 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
19949 // All sizes must be a power of two.
19950 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
19953 // Attempt to load the original value using scalar loads.
19954 // Find the largest scalar type that divides the total loaded size.
19955 MVT SclrLoadTy = MVT::i8;
19956 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19957 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19958 MVT Tp = (MVT::SimpleValueType)tp;
19959 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
19964 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19965 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
19967 SclrLoadTy = MVT::f64;
19969 // Calculate the number of scalar loads that we need to perform
19970 // in order to load our vector from memory.
19971 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
19972 if (Ext == ISD::SEXTLOAD && NumLoads > 1)
19975 unsigned loadRegZize = RegSz;
19976 if (Ext == ISD::SEXTLOAD && RegSz == 256)
19979 // Represent our vector as a sequence of elements which are the
19980 // largest scalar that we can load.
19981 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
19982 loadRegZize/SclrLoadTy.getSizeInBits());
19984 // Represent the data using the same element type that is stored in
19985 // memory. In practice, we ''widen'' MemVT.
19987 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19988 loadRegZize/MemVT.getScalarType().getSizeInBits());
19990 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
19991 "Invalid vector type");
19993 // We can't shuffle using an illegal type.
19994 if (!TLI.isTypeLegal(WideVecVT))
19997 SmallVector<SDValue, 8> Chains;
19998 SDValue Ptr = Ld->getBasePtr();
19999 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
20000 TLI.getPointerTy());
20001 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
20003 for (unsigned i = 0; i < NumLoads; ++i) {
20004 // Perform a single load.
20005 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
20006 Ptr, Ld->getPointerInfo(),
20007 Ld->isVolatile(), Ld->isNonTemporal(),
20008 Ld->isInvariant(), Ld->getAlignment());
20009 Chains.push_back(ScalarLoad.getValue(1));
20010 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
20011 // another round of DAGCombining.
20013 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
20015 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
20016 ScalarLoad, DAG.getIntPtrConstant(i));
20018 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
20021 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
20023 // Bitcast the loaded value to a vector of the original element type, in
20024 // the size of the target vector type.
20025 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
20026 unsigned SizeRatio = RegSz/MemSz;
20028 if (Ext == ISD::SEXTLOAD) {
20029 // If we have SSE4.1 we can directly emit a VSEXT node.
20030 if (Subtarget->hasSSE41()) {
20031 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
20032 return DCI.CombineTo(N, Sext, TF, true);
20035 // Otherwise we'll shuffle the small elements in the high bits of the
20036 // larger type and perform an arithmetic shift. If the shift is not legal
20037 // it's better to scalarize.
20038 if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
20041 // Redistribute the loaded elements into the different locations.
20042 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
20043 for (unsigned i = 0; i != NumElems; ++i)
20044 ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
20046 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
20047 DAG.getUNDEF(WideVecVT),
20050 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
20052 // Build the arithmetic shift.
20053 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
20054 MemVT.getVectorElementType().getSizeInBits();
20055 Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
20056 DAG.getConstant(Amt, RegVT));
20058 return DCI.CombineTo(N, Shuff, TF, true);
20061 // Redistribute the loaded elements into the different locations.
20062 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
20063 for (unsigned i = 0; i != NumElems; ++i)
20064 ShuffleVec[i*SizeRatio] = i;
20066 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
20067 DAG.getUNDEF(WideVecVT),
20070 // Bitcast to the requested type.
20071 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
20072 // Replace the original load with the new sequence
20073 // and return the new chain.
20074 return DCI.CombineTo(N, Shuff, TF, true);
20080 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
20081 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
20082 const X86Subtarget *Subtarget) {
20083 StoreSDNode *St = cast<StoreSDNode>(N);
20084 EVT VT = St->getValue().getValueType();
20085 EVT StVT = St->getMemoryVT();
20087 SDValue StoredVal = St->getOperand(1);
20088 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20090 // If we are saving a concatenation of two XMM registers, perform two stores.
20091 // On Sandy Bridge, 256-bit memory operations are executed by two
20092 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
20093 // memory operation.
20094 unsigned Alignment = St->getAlignment();
20095 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
20096 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
20097 StVT == VT && !IsAligned) {
20098 unsigned NumElems = VT.getVectorNumElements();
20102 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
20103 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
20105 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
20106 SDValue Ptr0 = St->getBasePtr();
20107 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
20109 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
20110 St->getPointerInfo(), St->isVolatile(),
20111 St->isNonTemporal(), Alignment);
20112 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
20113 St->getPointerInfo(), St->isVolatile(),
20114 St->isNonTemporal(),
20115 std::min(16U, Alignment));
20116 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
20119 // Optimize trunc store (of multiple scalars) to shuffle and store.
20120 // First, pack all of the elements in one place. Next, store to memory
20121 // in fewer chunks.
20122 if (St->isTruncatingStore() && VT.isVector()) {
20123 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20124 unsigned NumElems = VT.getVectorNumElements();
20125 assert(StVT != VT && "Cannot truncate to the same type");
20126 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
20127 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
20129 // From, To sizes and ElemCount must be pow of two
20130 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
20131 // We are going to use the original vector elt for storing.
20132 // Accumulated smaller vector elements must be a multiple of the store size.
20133 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
20135 unsigned SizeRatio = FromSz / ToSz;
20137 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
20139 // Create a type on which we perform the shuffle
20140 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
20141 StVT.getScalarType(), NumElems*SizeRatio);
20143 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
20145 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
20146 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
20147 for (unsigned i = 0; i != NumElems; ++i)
20148 ShuffleVec[i] = i * SizeRatio;
20150 // Can't shuffle using an illegal type.
20151 if (!TLI.isTypeLegal(WideVecVT))
20154 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
20155 DAG.getUNDEF(WideVecVT),
20157 // At this point all of the data is stored at the bottom of the
20158 // register. We now need to save it to mem.
20160 // Find the largest store unit
20161 MVT StoreType = MVT::i8;
20162 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
20163 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
20164 MVT Tp = (MVT::SimpleValueType)tp;
20165 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
20169 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
20170 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
20171 (64 <= NumElems * ToSz))
20172 StoreType = MVT::f64;
20174 // Bitcast the original vector into a vector of store-size units
20175 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
20176 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
20177 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
20178 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
20179 SmallVector<SDValue, 8> Chains;
20180 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
20181 TLI.getPointerTy());
20182 SDValue Ptr = St->getBasePtr();
20184 // Perform one or more big stores into memory.
20185 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
20186 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
20187 StoreType, ShuffWide,
20188 DAG.getIntPtrConstant(i));
20189 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
20190 St->getPointerInfo(), St->isVolatile(),
20191 St->isNonTemporal(), St->getAlignment());
20192 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
20193 Chains.push_back(Ch);
20196 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
20199 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
20200 // the FP state in cases where an emms may be missing.
20201 // A preferable solution to the general problem is to figure out the right
20202 // places to insert EMMS. This qualifies as a quick hack.
20204 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
20205 if (VT.getSizeInBits() != 64)
20208 const Function *F = DAG.getMachineFunction().getFunction();
20209 bool NoImplicitFloatOps = F->getAttributes().
20210 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
20211 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
20212 && Subtarget->hasSSE2();
20213 if ((VT.isVector() ||
20214 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
20215 isa<LoadSDNode>(St->getValue()) &&
20216 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
20217 St->getChain().hasOneUse() && !St->isVolatile()) {
20218 SDNode* LdVal = St->getValue().getNode();
20219 LoadSDNode *Ld = nullptr;
20220 int TokenFactorIndex = -1;
20221 SmallVector<SDValue, 8> Ops;
20222 SDNode* ChainVal = St->getChain().getNode();
20223 // Must be a store of a load. We currently handle two cases: the load
20224 // is a direct child, and it's under an intervening TokenFactor. It is
20225 // possible to dig deeper under nested TokenFactors.
20226 if (ChainVal == LdVal)
20227 Ld = cast<LoadSDNode>(St->getChain());
20228 else if (St->getValue().hasOneUse() &&
20229 ChainVal->getOpcode() == ISD::TokenFactor) {
20230 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
20231 if (ChainVal->getOperand(i).getNode() == LdVal) {
20232 TokenFactorIndex = i;
20233 Ld = cast<LoadSDNode>(St->getValue());
20235 Ops.push_back(ChainVal->getOperand(i));
20239 if (!Ld || !ISD::isNormalLoad(Ld))
20242 // If this is not the MMX case, i.e. we are just turning i64 load/store
20243 // into f64 load/store, avoid the transformation if there are multiple
20244 // uses of the loaded value.
20245 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
20250 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
20251 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
20253 if (Subtarget->is64Bit() || F64IsLegal) {
20254 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
20255 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
20256 Ld->getPointerInfo(), Ld->isVolatile(),
20257 Ld->isNonTemporal(), Ld->isInvariant(),
20258 Ld->getAlignment());
20259 SDValue NewChain = NewLd.getValue(1);
20260 if (TokenFactorIndex != -1) {
20261 Ops.push_back(NewChain);
20262 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
20264 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
20265 St->getPointerInfo(),
20266 St->isVolatile(), St->isNonTemporal(),
20267 St->getAlignment());
20270 // Otherwise, lower to two pairs of 32-bit loads / stores.
20271 SDValue LoAddr = Ld->getBasePtr();
20272 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
20273 DAG.getConstant(4, MVT::i32));
20275 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
20276 Ld->getPointerInfo(),
20277 Ld->isVolatile(), Ld->isNonTemporal(),
20278 Ld->isInvariant(), Ld->getAlignment());
20279 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
20280 Ld->getPointerInfo().getWithOffset(4),
20281 Ld->isVolatile(), Ld->isNonTemporal(),
20283 MinAlign(Ld->getAlignment(), 4));
20285 SDValue NewChain = LoLd.getValue(1);
20286 if (TokenFactorIndex != -1) {
20287 Ops.push_back(LoLd);
20288 Ops.push_back(HiLd);
20289 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
20292 LoAddr = St->getBasePtr();
20293 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
20294 DAG.getConstant(4, MVT::i32));
20296 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
20297 St->getPointerInfo(),
20298 St->isVolatile(), St->isNonTemporal(),
20299 St->getAlignment());
20300 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
20301 St->getPointerInfo().getWithOffset(4),
20303 St->isNonTemporal(),
20304 MinAlign(St->getAlignment(), 4));
20305 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
20310 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
20311 /// and return the operands for the horizontal operation in LHS and RHS. A
20312 /// horizontal operation performs the binary operation on successive elements
20313 /// of its first operand, then on successive elements of its second operand,
20314 /// returning the resulting values in a vector. For example, if
20315 /// A = < float a0, float a1, float a2, float a3 >
20317 /// B = < float b0, float b1, float b2, float b3 >
20318 /// then the result of doing a horizontal operation on A and B is
20319 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
20320 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
20321 /// A horizontal-op B, for some already available A and B, and if so then LHS is
20322 /// set to A, RHS to B, and the routine returns 'true'.
20323 /// Note that the binary operation should have the property that if one of the
20324 /// operands is UNDEF then the result is UNDEF.
20325 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
20326 // Look for the following pattern: if
20327 // A = < float a0, float a1, float a2, float a3 >
20328 // B = < float b0, float b1, float b2, float b3 >
20330 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
20331 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
20332 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
20333 // which is A horizontal-op B.
20335 // At least one of the operands should be a vector shuffle.
20336 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
20337 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
20340 MVT VT = LHS.getSimpleValueType();
20342 assert((VT.is128BitVector() || VT.is256BitVector()) &&
20343 "Unsupported vector type for horizontal add/sub");
20345 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
20346 // operate independently on 128-bit lanes.
20347 unsigned NumElts = VT.getVectorNumElements();
20348 unsigned NumLanes = VT.getSizeInBits()/128;
20349 unsigned NumLaneElts = NumElts / NumLanes;
20350 assert((NumLaneElts % 2 == 0) &&
20351 "Vector type should have an even number of elements in each lane");
20352 unsigned HalfLaneElts = NumLaneElts/2;
20354 // View LHS in the form
20355 // LHS = VECTOR_SHUFFLE A, B, LMask
20356 // If LHS is not a shuffle then pretend it is the shuffle
20357 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
20358 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
20361 SmallVector<int, 16> LMask(NumElts);
20362 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
20363 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
20364 A = LHS.getOperand(0);
20365 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
20366 B = LHS.getOperand(1);
20367 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
20368 std::copy(Mask.begin(), Mask.end(), LMask.begin());
20370 if (LHS.getOpcode() != ISD::UNDEF)
20372 for (unsigned i = 0; i != NumElts; ++i)
20376 // Likewise, view RHS in the form
20377 // RHS = VECTOR_SHUFFLE C, D, RMask
20379 SmallVector<int, 16> RMask(NumElts);
20380 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
20381 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
20382 C = RHS.getOperand(0);
20383 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
20384 D = RHS.getOperand(1);
20385 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
20386 std::copy(Mask.begin(), Mask.end(), RMask.begin());
20388 if (RHS.getOpcode() != ISD::UNDEF)
20390 for (unsigned i = 0; i != NumElts; ++i)
20394 // Check that the shuffles are both shuffling the same vectors.
20395 if (!(A == C && B == D) && !(A == D && B == C))
20398 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
20399 if (!A.getNode() && !B.getNode())
20402 // If A and B occur in reverse order in RHS, then "swap" them (which means
20403 // rewriting the mask).
20405 CommuteVectorShuffleMask(RMask, NumElts);
20407 // At this point LHS and RHS are equivalent to
20408 // LHS = VECTOR_SHUFFLE A, B, LMask
20409 // RHS = VECTOR_SHUFFLE A, B, RMask
20410 // Check that the masks correspond to performing a horizontal operation.
20411 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
20412 for (unsigned i = 0; i != NumLaneElts; ++i) {
20413 int LIdx = LMask[i+l], RIdx = RMask[i+l];
20415 // Ignore any UNDEF components.
20416 if (LIdx < 0 || RIdx < 0 ||
20417 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
20418 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
20421 // Check that successive elements are being operated on. If not, this is
20422 // not a horizontal operation.
20423 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
20424 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
20425 if (!(LIdx == Index && RIdx == Index + 1) &&
20426 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
20431 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
20432 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
20436 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
20437 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
20438 const X86Subtarget *Subtarget) {
20439 EVT VT = N->getValueType(0);
20440 SDValue LHS = N->getOperand(0);
20441 SDValue RHS = N->getOperand(1);
20443 // Try to synthesize horizontal adds from adds of shuffles.
20444 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
20445 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
20446 isHorizontalBinOp(LHS, RHS, true))
20447 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
20451 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
20452 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
20453 const X86Subtarget *Subtarget) {
20454 EVT VT = N->getValueType(0);
20455 SDValue LHS = N->getOperand(0);
20456 SDValue RHS = N->getOperand(1);
20458 // Try to synthesize horizontal subs from subs of shuffles.
20459 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
20460 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
20461 isHorizontalBinOp(LHS, RHS, false))
20462 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
20466 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
20467 /// X86ISD::FXOR nodes.
20468 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
20469 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
20470 // F[X]OR(0.0, x) -> x
20471 // F[X]OR(x, 0.0) -> x
20472 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20473 if (C->getValueAPF().isPosZero())
20474 return N->getOperand(1);
20475 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20476 if (C->getValueAPF().isPosZero())
20477 return N->getOperand(0);
20481 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
20482 /// X86ISD::FMAX nodes.
20483 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
20484 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
20486 // Only perform optimizations if UnsafeMath is used.
20487 if (!DAG.getTarget().Options.UnsafeFPMath)
20490 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
20491 // into FMINC and FMAXC, which are Commutative operations.
20492 unsigned NewOp = 0;
20493 switch (N->getOpcode()) {
20494 default: llvm_unreachable("unknown opcode");
20495 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
20496 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
20499 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
20500 N->getOperand(0), N->getOperand(1));
20503 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
20504 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
20505 // FAND(0.0, x) -> 0.0
20506 // FAND(x, 0.0) -> 0.0
20507 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20508 if (C->getValueAPF().isPosZero())
20509 return N->getOperand(0);
20510 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20511 if (C->getValueAPF().isPosZero())
20512 return N->getOperand(1);
20516 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
20517 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
20518 // FANDN(x, 0.0) -> 0.0
20519 // FANDN(0.0, x) -> x
20520 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20521 if (C->getValueAPF().isPosZero())
20522 return N->getOperand(1);
20523 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20524 if (C->getValueAPF().isPosZero())
20525 return N->getOperand(1);
20529 static SDValue PerformBTCombine(SDNode *N,
20531 TargetLowering::DAGCombinerInfo &DCI) {
20532 // BT ignores high bits in the bit index operand.
20533 SDValue Op1 = N->getOperand(1);
20534 if (Op1.hasOneUse()) {
20535 unsigned BitWidth = Op1.getValueSizeInBits();
20536 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
20537 APInt KnownZero, KnownOne;
20538 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
20539 !DCI.isBeforeLegalizeOps());
20540 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20541 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
20542 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
20543 DCI.CommitTargetLoweringOpt(TLO);
20548 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
20549 SDValue Op = N->getOperand(0);
20550 if (Op.getOpcode() == ISD::BITCAST)
20551 Op = Op.getOperand(0);
20552 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
20553 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
20554 VT.getVectorElementType().getSizeInBits() ==
20555 OpVT.getVectorElementType().getSizeInBits()) {
20556 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
20561 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
20562 const X86Subtarget *Subtarget) {
20563 EVT VT = N->getValueType(0);
20564 if (!VT.isVector())
20567 SDValue N0 = N->getOperand(0);
20568 SDValue N1 = N->getOperand(1);
20569 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
20572 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
20573 // both SSE and AVX2 since there is no sign-extended shift right
20574 // operation on a vector with 64-bit elements.
20575 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
20576 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
20577 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
20578 N0.getOpcode() == ISD::SIGN_EXTEND)) {
20579 SDValue N00 = N0.getOperand(0);
20581 // EXTLOAD has a better solution on AVX2,
20582 // it may be replaced with X86ISD::VSEXT node.
20583 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
20584 if (!ISD::isNormalLoad(N00.getNode()))
20587 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
20588 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
20590 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
20596 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
20597 TargetLowering::DAGCombinerInfo &DCI,
20598 const X86Subtarget *Subtarget) {
20599 if (!DCI.isBeforeLegalizeOps())
20602 if (!Subtarget->hasFp256())
20605 EVT VT = N->getValueType(0);
20606 if (VT.isVector() && VT.getSizeInBits() == 256) {
20607 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
20615 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
20616 const X86Subtarget* Subtarget) {
20618 EVT VT = N->getValueType(0);
20620 // Let legalize expand this if it isn't a legal type yet.
20621 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
20624 EVT ScalarVT = VT.getScalarType();
20625 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
20626 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
20629 SDValue A = N->getOperand(0);
20630 SDValue B = N->getOperand(1);
20631 SDValue C = N->getOperand(2);
20633 bool NegA = (A.getOpcode() == ISD::FNEG);
20634 bool NegB = (B.getOpcode() == ISD::FNEG);
20635 bool NegC = (C.getOpcode() == ISD::FNEG);
20637 // Negative multiplication when NegA xor NegB
20638 bool NegMul = (NegA != NegB);
20640 A = A.getOperand(0);
20642 B = B.getOperand(0);
20644 C = C.getOperand(0);
20648 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
20650 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
20652 return DAG.getNode(Opcode, dl, VT, A, B, C);
20655 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
20656 TargetLowering::DAGCombinerInfo &DCI,
20657 const X86Subtarget *Subtarget) {
20658 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
20659 // (and (i32 x86isd::setcc_carry), 1)
20660 // This eliminates the zext. This transformation is necessary because
20661 // ISD::SETCC is always legalized to i8.
20663 SDValue N0 = N->getOperand(0);
20664 EVT VT = N->getValueType(0);
20666 if (N0.getOpcode() == ISD::AND &&
20668 N0.getOperand(0).hasOneUse()) {
20669 SDValue N00 = N0.getOperand(0);
20670 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
20671 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
20672 if (!C || C->getZExtValue() != 1)
20674 return DAG.getNode(ISD::AND, dl, VT,
20675 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
20676 N00.getOperand(0), N00.getOperand(1)),
20677 DAG.getConstant(1, VT));
20681 if (N0.getOpcode() == ISD::TRUNCATE &&
20683 N0.getOperand(0).hasOneUse()) {
20684 SDValue N00 = N0.getOperand(0);
20685 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
20686 return DAG.getNode(ISD::AND, dl, VT,
20687 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
20688 N00.getOperand(0), N00.getOperand(1)),
20689 DAG.getConstant(1, VT));
20692 if (VT.is256BitVector()) {
20693 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
20701 // Optimize x == -y --> x+y == 0
20702 // x != -y --> x+y != 0
20703 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
20704 const X86Subtarget* Subtarget) {
20705 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
20706 SDValue LHS = N->getOperand(0);
20707 SDValue RHS = N->getOperand(1);
20708 EVT VT = N->getValueType(0);
20711 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
20712 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
20713 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
20714 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
20715 LHS.getValueType(), RHS, LHS.getOperand(1));
20716 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
20717 addV, DAG.getConstant(0, addV.getValueType()), CC);
20719 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
20720 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
20721 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
20722 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
20723 RHS.getValueType(), LHS, RHS.getOperand(1));
20724 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
20725 addV, DAG.getConstant(0, addV.getValueType()), CC);
20728 if (VT.getScalarType() == MVT::i1) {
20729 bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
20730 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
20731 bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
20732 if (!IsSEXT0 && !IsVZero0)
20734 bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
20735 (RHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
20736 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
20738 if (!IsSEXT1 && !IsVZero1)
20741 if (IsSEXT0 && IsVZero1) {
20742 assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
20743 if (CC == ISD::SETEQ)
20744 return DAG.getNOT(DL, LHS.getOperand(0), VT);
20745 return LHS.getOperand(0);
20747 if (IsSEXT1 && IsVZero0) {
20748 assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
20749 if (CC == ISD::SETEQ)
20750 return DAG.getNOT(DL, RHS.getOperand(0), VT);
20751 return RHS.getOperand(0);
20758 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
20759 const X86Subtarget *Subtarget) {
20761 MVT VT = N->getOperand(1)->getSimpleValueType(0);
20762 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
20763 "X86insertps is only defined for v4x32");
20765 SDValue Ld = N->getOperand(1);
20766 if (MayFoldLoad(Ld)) {
20767 // Extract the countS bits from the immediate so we can get the proper
20768 // address when narrowing the vector load to a specific element.
20769 // When the second source op is a memory address, interps doesn't use
20770 // countS and just gets an f32 from that address.
20771 unsigned DestIndex =
20772 cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
20773 Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
20777 // Create this as a scalar to vector to match the instruction pattern.
20778 SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
20779 // countS bits are ignored when loading from memory on insertps, which
20780 // means we don't need to explicitly set them to 0.
20781 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
20782 LoadScalarToVector, N->getOperand(2));
20785 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
20786 // as "sbb reg,reg", since it can be extended without zext and produces
20787 // an all-ones bit which is more useful than 0/1 in some cases.
20788 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
20791 return DAG.getNode(ISD::AND, DL, VT,
20792 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
20793 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
20794 DAG.getConstant(1, VT));
20795 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
20796 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
20797 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
20798 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
20801 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
20802 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
20803 TargetLowering::DAGCombinerInfo &DCI,
20804 const X86Subtarget *Subtarget) {
20806 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
20807 SDValue EFLAGS = N->getOperand(1);
20809 if (CC == X86::COND_A) {
20810 // Try to convert COND_A into COND_B in an attempt to facilitate
20811 // materializing "setb reg".
20813 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
20814 // cannot take an immediate as its first operand.
20816 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
20817 EFLAGS.getValueType().isInteger() &&
20818 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
20819 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
20820 EFLAGS.getNode()->getVTList(),
20821 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
20822 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
20823 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
20827 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
20828 // a zext and produces an all-ones bit which is more useful than 0/1 in some
20830 if (CC == X86::COND_B)
20831 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
20835 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
20836 if (Flags.getNode()) {
20837 SDValue Cond = DAG.getConstant(CC, MVT::i8);
20838 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
20844 // Optimize branch condition evaluation.
20846 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
20847 TargetLowering::DAGCombinerInfo &DCI,
20848 const X86Subtarget *Subtarget) {
20850 SDValue Chain = N->getOperand(0);
20851 SDValue Dest = N->getOperand(1);
20852 SDValue EFLAGS = N->getOperand(3);
20853 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
20857 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
20858 if (Flags.getNode()) {
20859 SDValue Cond = DAG.getConstant(CC, MVT::i8);
20860 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
20867 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
20868 const X86TargetLowering *XTLI) {
20869 SDValue Op0 = N->getOperand(0);
20870 EVT InVT = Op0->getValueType(0);
20872 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
20873 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
20875 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
20876 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
20877 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
20880 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
20881 // a 32-bit target where SSE doesn't support i64->FP operations.
20882 if (Op0.getOpcode() == ISD::LOAD) {
20883 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
20884 EVT VT = Ld->getValueType(0);
20885 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
20886 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
20887 !XTLI->getSubtarget()->is64Bit() &&
20889 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
20890 Ld->getChain(), Op0, DAG);
20891 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
20898 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
20899 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
20900 X86TargetLowering::DAGCombinerInfo &DCI) {
20901 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
20902 // the result is either zero or one (depending on the input carry bit).
20903 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
20904 if (X86::isZeroNode(N->getOperand(0)) &&
20905 X86::isZeroNode(N->getOperand(1)) &&
20906 // We don't have a good way to replace an EFLAGS use, so only do this when
20908 SDValue(N, 1).use_empty()) {
20910 EVT VT = N->getValueType(0);
20911 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
20912 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
20913 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
20914 DAG.getConstant(X86::COND_B,MVT::i8),
20916 DAG.getConstant(1, VT));
20917 return DCI.CombineTo(N, Res1, CarryOut);
20923 // fold (add Y, (sete X, 0)) -> adc 0, Y
20924 // (add Y, (setne X, 0)) -> sbb -1, Y
20925 // (sub (sete X, 0), Y) -> sbb 0, Y
20926 // (sub (setne X, 0), Y) -> adc -1, Y
20927 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
20930 // Look through ZExts.
20931 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
20932 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
20935 SDValue SetCC = Ext.getOperand(0);
20936 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
20939 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
20940 if (CC != X86::COND_E && CC != X86::COND_NE)
20943 SDValue Cmp = SetCC.getOperand(1);
20944 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
20945 !X86::isZeroNode(Cmp.getOperand(1)) ||
20946 !Cmp.getOperand(0).getValueType().isInteger())
20949 SDValue CmpOp0 = Cmp.getOperand(0);
20950 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
20951 DAG.getConstant(1, CmpOp0.getValueType()));
20953 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
20954 if (CC == X86::COND_NE)
20955 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
20956 DL, OtherVal.getValueType(), OtherVal,
20957 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
20958 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
20959 DL, OtherVal.getValueType(), OtherVal,
20960 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
20963 /// PerformADDCombine - Do target-specific dag combines on integer adds.
20964 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
20965 const X86Subtarget *Subtarget) {
20966 EVT VT = N->getValueType(0);
20967 SDValue Op0 = N->getOperand(0);
20968 SDValue Op1 = N->getOperand(1);
20970 // Try to synthesize horizontal adds from adds of shuffles.
20971 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20972 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20973 isHorizontalBinOp(Op0, Op1, true))
20974 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
20976 return OptimizeConditionalInDecrement(N, DAG);
20979 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
20980 const X86Subtarget *Subtarget) {
20981 SDValue Op0 = N->getOperand(0);
20982 SDValue Op1 = N->getOperand(1);
20984 // X86 can't encode an immediate LHS of a sub. See if we can push the
20985 // negation into a preceding instruction.
20986 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
20987 // If the RHS of the sub is a XOR with one use and a constant, invert the
20988 // immediate. Then add one to the LHS of the sub so we can turn
20989 // X-Y -> X+~Y+1, saving one register.
20990 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
20991 isa<ConstantSDNode>(Op1.getOperand(1))) {
20992 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
20993 EVT VT = Op0.getValueType();
20994 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
20996 DAG.getConstant(~XorC, VT));
20997 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
20998 DAG.getConstant(C->getAPIntValue()+1, VT));
21002 // Try to synthesize horizontal adds from adds of shuffles.
21003 EVT VT = N->getValueType(0);
21004 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
21005 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
21006 isHorizontalBinOp(Op0, Op1, true))
21007 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
21009 return OptimizeConditionalInDecrement(N, DAG);
21012 /// performVZEXTCombine - Performs build vector combines
21013 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
21014 TargetLowering::DAGCombinerInfo &DCI,
21015 const X86Subtarget *Subtarget) {
21016 // (vzext (bitcast (vzext (x)) -> (vzext x)
21017 SDValue In = N->getOperand(0);
21018 while (In.getOpcode() == ISD::BITCAST)
21019 In = In.getOperand(0);
21021 if (In.getOpcode() != X86ISD::VZEXT)
21024 return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
21028 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
21029 DAGCombinerInfo &DCI) const {
21030 SelectionDAG &DAG = DCI.DAG;
21031 switch (N->getOpcode()) {
21033 case ISD::EXTRACT_VECTOR_ELT:
21034 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
21036 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
21037 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
21038 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
21039 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
21040 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
21041 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
21044 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
21045 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
21046 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
21047 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
21048 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
21049 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
21050 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
21051 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
21052 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
21054 case X86ISD::FOR: return PerformFORCombine(N, DAG);
21056 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
21057 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
21058 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
21059 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
21060 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
21061 case ISD::ANY_EXTEND:
21062 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
21063 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
21064 case ISD::SIGN_EXTEND_INREG:
21065 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
21066 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
21067 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
21068 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
21069 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
21070 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
21071 case X86ISD::SHUFP: // Handle all target specific shuffles
21072 case X86ISD::PALIGNR:
21073 case X86ISD::UNPCKH:
21074 case X86ISD::UNPCKL:
21075 case X86ISD::MOVHLPS:
21076 case X86ISD::MOVLHPS:
21077 case X86ISD::PSHUFD:
21078 case X86ISD::PSHUFHW:
21079 case X86ISD::PSHUFLW:
21080 case X86ISD::MOVSS:
21081 case X86ISD::MOVSD:
21082 case X86ISD::VPERMILP:
21083 case X86ISD::VPERM2X128:
21084 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
21085 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
21086 case ISD::INTRINSIC_WO_CHAIN:
21087 return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
21088 case X86ISD::INSERTPS:
21089 return PerformINSERTPSCombine(N, DAG, Subtarget);
21090 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
21096 /// isTypeDesirableForOp - Return true if the target has native support for
21097 /// the specified value type and it is 'desirable' to use the type for the
21098 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
21099 /// instruction encodings are longer and some i16 instructions are slow.
21100 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
21101 if (!isTypeLegal(VT))
21103 if (VT != MVT::i16)
21110 case ISD::SIGN_EXTEND:
21111 case ISD::ZERO_EXTEND:
21112 case ISD::ANY_EXTEND:
21125 /// IsDesirableToPromoteOp - This method query the target whether it is
21126 /// beneficial for dag combiner to promote the specified node. If true, it
21127 /// should return the desired promotion type by reference.
21128 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
21129 EVT VT = Op.getValueType();
21130 if (VT != MVT::i16)
21133 bool Promote = false;
21134 bool Commute = false;
21135 switch (Op.getOpcode()) {
21138 LoadSDNode *LD = cast<LoadSDNode>(Op);
21139 // If the non-extending load has a single use and it's not live out, then it
21140 // might be folded.
21141 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
21142 Op.hasOneUse()*/) {
21143 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
21144 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
21145 // The only case where we'd want to promote LOAD (rather then it being
21146 // promoted as an operand is when it's only use is liveout.
21147 if (UI->getOpcode() != ISD::CopyToReg)
21154 case ISD::SIGN_EXTEND:
21155 case ISD::ZERO_EXTEND:
21156 case ISD::ANY_EXTEND:
21161 SDValue N0 = Op.getOperand(0);
21162 // Look out for (store (shl (load), x)).
21163 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
21176 SDValue N0 = Op.getOperand(0);
21177 SDValue N1 = Op.getOperand(1);
21178 if (!Commute && MayFoldLoad(N1))
21180 // Avoid disabling potential load folding opportunities.
21181 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
21183 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
21193 //===----------------------------------------------------------------------===//
21194 // X86 Inline Assembly Support
21195 //===----------------------------------------------------------------------===//
21198 // Helper to match a string separated by whitespace.
21199 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
21200 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
21202 for (unsigned i = 0, e = args.size(); i != e; ++i) {
21203 StringRef piece(*args[i]);
21204 if (!s.startswith(piece)) // Check if the piece matches.
21207 s = s.substr(piece.size());
21208 StringRef::size_type pos = s.find_first_not_of(" \t");
21209 if (pos == 0) // We matched a prefix.
21217 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
21220 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
21222 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
21223 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
21224 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
21225 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
21227 if (AsmPieces.size() == 3)
21229 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
21236 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
21237 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
21239 std::string AsmStr = IA->getAsmString();
21241 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
21242 if (!Ty || Ty->getBitWidth() % 16 != 0)
21245 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
21246 SmallVector<StringRef, 4> AsmPieces;
21247 SplitString(AsmStr, AsmPieces, ";\n");
21249 switch (AsmPieces.size()) {
21250 default: return false;
21252 // FIXME: this should verify that we are targeting a 486 or better. If not,
21253 // we will turn this bswap into something that will be lowered to logical
21254 // ops instead of emitting the bswap asm. For now, we don't support 486 or
21255 // lower so don't worry about this.
21257 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
21258 matchAsm(AsmPieces[0], "bswapl", "$0") ||
21259 matchAsm(AsmPieces[0], "bswapq", "$0") ||
21260 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
21261 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
21262 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
21263 // No need to check constraints, nothing other than the equivalent of
21264 // "=r,0" would be valid here.
21265 return IntrinsicLowering::LowerToByteSwap(CI);
21268 // rorw $$8, ${0:w} --> llvm.bswap.i16
21269 if (CI->getType()->isIntegerTy(16) &&
21270 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
21271 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
21272 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
21274 const std::string &ConstraintsStr = IA->getConstraintString();
21275 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
21276 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
21277 if (clobbersFlagRegisters(AsmPieces))
21278 return IntrinsicLowering::LowerToByteSwap(CI);
21282 if (CI->getType()->isIntegerTy(32) &&
21283 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
21284 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
21285 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
21286 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
21288 const std::string &ConstraintsStr = IA->getConstraintString();
21289 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
21290 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
21291 if (clobbersFlagRegisters(AsmPieces))
21292 return IntrinsicLowering::LowerToByteSwap(CI);
21295 if (CI->getType()->isIntegerTy(64)) {
21296 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
21297 if (Constraints.size() >= 2 &&
21298 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
21299 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
21300 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
21301 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
21302 matchAsm(AsmPieces[1], "bswap", "%edx") &&
21303 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
21304 return IntrinsicLowering::LowerToByteSwap(CI);
21312 /// getConstraintType - Given a constraint letter, return the type of
21313 /// constraint it is for this target.
21314 X86TargetLowering::ConstraintType
21315 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
21316 if (Constraint.size() == 1) {
21317 switch (Constraint[0]) {
21328 return C_RegisterClass;
21352 return TargetLowering::getConstraintType(Constraint);
21355 /// Examine constraint type and operand type and determine a weight value.
21356 /// This object must already have been set up with the operand type
21357 /// and the current alternative constraint selected.
21358 TargetLowering::ConstraintWeight
21359 X86TargetLowering::getSingleConstraintMatchWeight(
21360 AsmOperandInfo &info, const char *constraint) const {
21361 ConstraintWeight weight = CW_Invalid;
21362 Value *CallOperandVal = info.CallOperandVal;
21363 // If we don't have a value, we can't do a match,
21364 // but allow it at the lowest weight.
21365 if (!CallOperandVal)
21367 Type *type = CallOperandVal->getType();
21368 // Look at the constraint type.
21369 switch (*constraint) {
21371 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
21382 if (CallOperandVal->getType()->isIntegerTy())
21383 weight = CW_SpecificReg;
21388 if (type->isFloatingPointTy())
21389 weight = CW_SpecificReg;
21392 if (type->isX86_MMXTy() && Subtarget->hasMMX())
21393 weight = CW_SpecificReg;
21397 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
21398 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
21399 weight = CW_Register;
21402 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
21403 if (C->getZExtValue() <= 31)
21404 weight = CW_Constant;
21408 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21409 if (C->getZExtValue() <= 63)
21410 weight = CW_Constant;
21414 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21415 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
21416 weight = CW_Constant;
21420 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21421 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
21422 weight = CW_Constant;
21426 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21427 if (C->getZExtValue() <= 3)
21428 weight = CW_Constant;
21432 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21433 if (C->getZExtValue() <= 0xff)
21434 weight = CW_Constant;
21439 if (dyn_cast<ConstantFP>(CallOperandVal)) {
21440 weight = CW_Constant;
21444 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21445 if ((C->getSExtValue() >= -0x80000000LL) &&
21446 (C->getSExtValue() <= 0x7fffffffLL))
21447 weight = CW_Constant;
21451 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21452 if (C->getZExtValue() <= 0xffffffff)
21453 weight = CW_Constant;
21460 /// LowerXConstraint - try to replace an X constraint, which matches anything,
21461 /// with another that has more specific requirements based on the type of the
21462 /// corresponding operand.
21463 const char *X86TargetLowering::
21464 LowerXConstraint(EVT ConstraintVT) const {
21465 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
21466 // 'f' like normal targets.
21467 if (ConstraintVT.isFloatingPoint()) {
21468 if (Subtarget->hasSSE2())
21470 if (Subtarget->hasSSE1())
21474 return TargetLowering::LowerXConstraint(ConstraintVT);
21477 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
21478 /// vector. If it is invalid, don't add anything to Ops.
21479 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
21480 std::string &Constraint,
21481 std::vector<SDValue>&Ops,
21482 SelectionDAG &DAG) const {
21485 // Only support length 1 constraints for now.
21486 if (Constraint.length() > 1) return;
21488 char ConstraintLetter = Constraint[0];
21489 switch (ConstraintLetter) {
21492 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21493 if (C->getZExtValue() <= 31) {
21494 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21500 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21501 if (C->getZExtValue() <= 63) {
21502 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21508 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21509 if (isInt<8>(C->getSExtValue())) {
21510 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21516 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21517 if (C->getZExtValue() <= 255) {
21518 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21524 // 32-bit signed value
21525 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21526 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
21527 C->getSExtValue())) {
21528 // Widen to 64 bits here to get it sign extended.
21529 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
21532 // FIXME gcc accepts some relocatable values here too, but only in certain
21533 // memory models; it's complicated.
21538 // 32-bit unsigned value
21539 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21540 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
21541 C->getZExtValue())) {
21542 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21546 // FIXME gcc accepts some relocatable values here too, but only in certain
21547 // memory models; it's complicated.
21551 // Literal immediates are always ok.
21552 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
21553 // Widen to 64 bits here to get it sign extended.
21554 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
21558 // In any sort of PIC mode addresses need to be computed at runtime by
21559 // adding in a register or some sort of table lookup. These can't
21560 // be used as immediates.
21561 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
21564 // If we are in non-pic codegen mode, we allow the address of a global (with
21565 // an optional displacement) to be used with 'i'.
21566 GlobalAddressSDNode *GA = nullptr;
21567 int64_t Offset = 0;
21569 // Match either (GA), (GA+C), (GA+C1+C2), etc.
21571 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
21572 Offset += GA->getOffset();
21574 } else if (Op.getOpcode() == ISD::ADD) {
21575 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
21576 Offset += C->getZExtValue();
21577 Op = Op.getOperand(0);
21580 } else if (Op.getOpcode() == ISD::SUB) {
21581 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
21582 Offset += -C->getZExtValue();
21583 Op = Op.getOperand(0);
21588 // Otherwise, this isn't something we can handle, reject it.
21592 const GlobalValue *GV = GA->getGlobal();
21593 // If we require an extra load to get this address, as in PIC mode, we
21594 // can't accept it.
21595 if (isGlobalStubReference(
21596 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
21599 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
21600 GA->getValueType(0), Offset);
21605 if (Result.getNode()) {
21606 Ops.push_back(Result);
21609 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
21612 std::pair<unsigned, const TargetRegisterClass*>
21613 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
21615 // First, see if this is a constraint that directly corresponds to an LLVM
21617 if (Constraint.size() == 1) {
21618 // GCC Constraint Letters
21619 switch (Constraint[0]) {
21621 // TODO: Slight differences here in allocation order and leaving
21622 // RIP in the class. Do they matter any more here than they do
21623 // in the normal allocation?
21624 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
21625 if (Subtarget->is64Bit()) {
21626 if (VT == MVT::i32 || VT == MVT::f32)
21627 return std::make_pair(0U, &X86::GR32RegClass);
21628 if (VT == MVT::i16)
21629 return std::make_pair(0U, &X86::GR16RegClass);
21630 if (VT == MVT::i8 || VT == MVT::i1)
21631 return std::make_pair(0U, &X86::GR8RegClass);
21632 if (VT == MVT::i64 || VT == MVT::f64)
21633 return std::make_pair(0U, &X86::GR64RegClass);
21636 // 32-bit fallthrough
21637 case 'Q': // Q_REGS
21638 if (VT == MVT::i32 || VT == MVT::f32)
21639 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
21640 if (VT == MVT::i16)
21641 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
21642 if (VT == MVT::i8 || VT == MVT::i1)
21643 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
21644 if (VT == MVT::i64)
21645 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
21647 case 'r': // GENERAL_REGS
21648 case 'l': // INDEX_REGS
21649 if (VT == MVT::i8 || VT == MVT::i1)
21650 return std::make_pair(0U, &X86::GR8RegClass);
21651 if (VT == MVT::i16)
21652 return std::make_pair(0U, &X86::GR16RegClass);
21653 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
21654 return std::make_pair(0U, &X86::GR32RegClass);
21655 return std::make_pair(0U, &X86::GR64RegClass);
21656 case 'R': // LEGACY_REGS
21657 if (VT == MVT::i8 || VT == MVT::i1)
21658 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
21659 if (VT == MVT::i16)
21660 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
21661 if (VT == MVT::i32 || !Subtarget->is64Bit())
21662 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
21663 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
21664 case 'f': // FP Stack registers.
21665 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
21666 // value to the correct fpstack register class.
21667 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
21668 return std::make_pair(0U, &X86::RFP32RegClass);
21669 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
21670 return std::make_pair(0U, &X86::RFP64RegClass);
21671 return std::make_pair(0U, &X86::RFP80RegClass);
21672 case 'y': // MMX_REGS if MMX allowed.
21673 if (!Subtarget->hasMMX()) break;
21674 return std::make_pair(0U, &X86::VR64RegClass);
21675 case 'Y': // SSE_REGS if SSE2 allowed
21676 if (!Subtarget->hasSSE2()) break;
21678 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
21679 if (!Subtarget->hasSSE1()) break;
21681 switch (VT.SimpleTy) {
21683 // Scalar SSE types.
21686 return std::make_pair(0U, &X86::FR32RegClass);
21689 return std::make_pair(0U, &X86::FR64RegClass);
21697 return std::make_pair(0U, &X86::VR128RegClass);
21705 return std::make_pair(0U, &X86::VR256RegClass);
21710 return std::make_pair(0U, &X86::VR512RegClass);
21716 // Use the default implementation in TargetLowering to convert the register
21717 // constraint into a member of a register class.
21718 std::pair<unsigned, const TargetRegisterClass*> Res;
21719 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
21721 // Not found as a standard register?
21723 // Map st(0) -> st(7) -> ST0
21724 if (Constraint.size() == 7 && Constraint[0] == '{' &&
21725 tolower(Constraint[1]) == 's' &&
21726 tolower(Constraint[2]) == 't' &&
21727 Constraint[3] == '(' &&
21728 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
21729 Constraint[5] == ')' &&
21730 Constraint[6] == '}') {
21732 Res.first = X86::ST0+Constraint[4]-'0';
21733 Res.second = &X86::RFP80RegClass;
21737 // GCC allows "st(0)" to be called just plain "st".
21738 if (StringRef("{st}").equals_lower(Constraint)) {
21739 Res.first = X86::ST0;
21740 Res.second = &X86::RFP80RegClass;
21745 if (StringRef("{flags}").equals_lower(Constraint)) {
21746 Res.first = X86::EFLAGS;
21747 Res.second = &X86::CCRRegClass;
21751 // 'A' means EAX + EDX.
21752 if (Constraint == "A") {
21753 Res.first = X86::EAX;
21754 Res.second = &X86::GR32_ADRegClass;
21760 // Otherwise, check to see if this is a register class of the wrong value
21761 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
21762 // turn into {ax},{dx}.
21763 if (Res.second->hasType(VT))
21764 return Res; // Correct type already, nothing to do.
21766 // All of the single-register GCC register classes map their values onto
21767 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
21768 // really want an 8-bit or 32-bit register, map to the appropriate register
21769 // class and return the appropriate register.
21770 if (Res.second == &X86::GR16RegClass) {
21771 if (VT == MVT::i8 || VT == MVT::i1) {
21772 unsigned DestReg = 0;
21773 switch (Res.first) {
21775 case X86::AX: DestReg = X86::AL; break;
21776 case X86::DX: DestReg = X86::DL; break;
21777 case X86::CX: DestReg = X86::CL; break;
21778 case X86::BX: DestReg = X86::BL; break;
21781 Res.first = DestReg;
21782 Res.second = &X86::GR8RegClass;
21784 } else if (VT == MVT::i32 || VT == MVT::f32) {
21785 unsigned DestReg = 0;
21786 switch (Res.first) {
21788 case X86::AX: DestReg = X86::EAX; break;
21789 case X86::DX: DestReg = X86::EDX; break;
21790 case X86::CX: DestReg = X86::ECX; break;
21791 case X86::BX: DestReg = X86::EBX; break;
21792 case X86::SI: DestReg = X86::ESI; break;
21793 case X86::DI: DestReg = X86::EDI; break;
21794 case X86::BP: DestReg = X86::EBP; break;
21795 case X86::SP: DestReg = X86::ESP; break;
21798 Res.first = DestReg;
21799 Res.second = &X86::GR32RegClass;
21801 } else if (VT == MVT::i64 || VT == MVT::f64) {
21802 unsigned DestReg = 0;
21803 switch (Res.first) {
21805 case X86::AX: DestReg = X86::RAX; break;
21806 case X86::DX: DestReg = X86::RDX; break;
21807 case X86::CX: DestReg = X86::RCX; break;
21808 case X86::BX: DestReg = X86::RBX; break;
21809 case X86::SI: DestReg = X86::RSI; break;
21810 case X86::DI: DestReg = X86::RDI; break;
21811 case X86::BP: DestReg = X86::RBP; break;
21812 case X86::SP: DestReg = X86::RSP; break;
21815 Res.first = DestReg;
21816 Res.second = &X86::GR64RegClass;
21819 } else if (Res.second == &X86::FR32RegClass ||
21820 Res.second == &X86::FR64RegClass ||
21821 Res.second == &X86::VR128RegClass ||
21822 Res.second == &X86::VR256RegClass ||
21823 Res.second == &X86::FR32XRegClass ||
21824 Res.second == &X86::FR64XRegClass ||
21825 Res.second == &X86::VR128XRegClass ||
21826 Res.second == &X86::VR256XRegClass ||
21827 Res.second == &X86::VR512RegClass) {
21828 // Handle references to XMM physical registers that got mapped into the
21829 // wrong class. This can happen with constraints like {xmm0} where the
21830 // target independent register mapper will just pick the first match it can
21831 // find, ignoring the required type.
21833 if (VT == MVT::f32 || VT == MVT::i32)
21834 Res.second = &X86::FR32RegClass;
21835 else if (VT == MVT::f64 || VT == MVT::i64)
21836 Res.second = &X86::FR64RegClass;
21837 else if (X86::VR128RegClass.hasType(VT))
21838 Res.second = &X86::VR128RegClass;
21839 else if (X86::VR256RegClass.hasType(VT))
21840 Res.second = &X86::VR256RegClass;
21841 else if (X86::VR512RegClass.hasType(VT))
21842 Res.second = &X86::VR512RegClass;
21848 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
21850 // Scaling factors are not free at all.
21851 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
21852 // will take 2 allocations in the out of order engine instead of 1
21853 // for plain addressing mode, i.e. inst (reg1).
21855 // vaddps (%rsi,%drx), %ymm0, %ymm1
21856 // Requires two allocations (one for the load, one for the computation)
21858 // vaddps (%rsi), %ymm0, %ymm1
21859 // Requires just 1 allocation, i.e., freeing allocations for other operations
21860 // and having less micro operations to execute.
21862 // For some X86 architectures, this is even worse because for instance for
21863 // stores, the complex addressing mode forces the instruction to use the
21864 // "load" ports instead of the dedicated "store" port.
21865 // E.g., on Haswell:
21866 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
21867 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
21868 if (isLegalAddressingMode(AM, Ty))
21869 // Scale represents reg2 * scale, thus account for 1
21870 // as soon as we use a second register.
21871 return AM.Scale != 0;
21875 bool X86TargetLowering::isTargetFTOL() const {
21876 return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();