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/VariadicFunction.h"
26 #include "llvm/CodeGen/IntrinsicLowering.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineJumpTableInfo.h"
31 #include "llvm/CodeGen/MachineModuleInfo.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/IR/CallSite.h"
34 #include "llvm/IR/CallingConv.h"
35 #include "llvm/IR/Constants.h"
36 #include "llvm/IR/DerivedTypes.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/IR/GlobalAlias.h"
39 #include "llvm/IR/GlobalVariable.h"
40 #include "llvm/IR/Instructions.h"
41 #include "llvm/IR/Intrinsics.h"
42 #include "llvm/MC/MCAsmInfo.h"
43 #include "llvm/MC/MCContext.h"
44 #include "llvm/MC/MCExpr.h"
45 #include "llvm/MC/MCSymbol.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/MathExtras.h"
49 #include "llvm/Target/TargetOptions.h"
54 #define DEBUG_TYPE "x86-isel"
56 STATISTIC(NumTailCalls, "Number of tail calls");
58 // Forward declarations.
59 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
62 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
63 SelectionDAG &DAG, SDLoc dl,
64 unsigned vectorWidth) {
65 assert((vectorWidth == 128 || vectorWidth == 256) &&
66 "Unsupported vector width");
67 EVT VT = Vec.getValueType();
68 EVT ElVT = VT.getVectorElementType();
69 unsigned Factor = VT.getSizeInBits()/vectorWidth;
70 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
71 VT.getVectorNumElements()/Factor);
73 // Extract from UNDEF is UNDEF.
74 if (Vec.getOpcode() == ISD::UNDEF)
75 return DAG.getUNDEF(ResultVT);
77 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
78 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
80 // This is the index of the first element of the vectorWidth-bit chunk
82 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
85 // If the input is a buildvector just emit a smaller one.
86 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
87 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
88 Vec->op_begin()+NormalizedIdxVal, ElemsPerChunk);
90 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
91 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
97 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
98 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
99 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
100 /// instructions or a simple subregister reference. Idx is an index in the
101 /// 128 bits we want. It need not be aligned to a 128-bit bounday. That makes
102 /// lowering EXTRACT_VECTOR_ELT operations easier.
103 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
104 SelectionDAG &DAG, SDLoc dl) {
105 assert((Vec.getValueType().is256BitVector() ||
106 Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
107 return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
110 /// Generate a DAG to grab 256-bits from a 512-bit vector.
111 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
112 SelectionDAG &DAG, SDLoc dl) {
113 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
114 return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
117 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
118 unsigned IdxVal, SelectionDAG &DAG,
119 SDLoc dl, unsigned vectorWidth) {
120 assert((vectorWidth == 128 || vectorWidth == 256) &&
121 "Unsupported vector width");
122 // Inserting UNDEF is Result
123 if (Vec.getOpcode() == ISD::UNDEF)
125 EVT VT = Vec.getValueType();
126 EVT ElVT = VT.getVectorElementType();
127 EVT ResultVT = Result.getValueType();
129 // Insert the relevant vectorWidth bits.
130 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
132 // This is the index of the first element of the vectorWidth-bit chunk
134 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
137 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
138 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
141 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
142 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
143 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
144 /// simple superregister reference. Idx is an index in the 128 bits
145 /// we want. It need not be aligned to a 128-bit bounday. That makes
146 /// lowering INSERT_VECTOR_ELT operations easier.
147 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
148 unsigned IdxVal, SelectionDAG &DAG,
150 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
151 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
154 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
155 unsigned IdxVal, SelectionDAG &DAG,
157 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
158 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
161 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
162 /// instructions. This is used because creating CONCAT_VECTOR nodes of
163 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
164 /// large BUILD_VECTORS.
165 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
166 unsigned NumElems, SelectionDAG &DAG,
168 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
169 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
172 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
173 unsigned NumElems, SelectionDAG &DAG,
175 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
176 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
179 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
180 const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
181 bool is64Bit = Subtarget->is64Bit();
183 if (Subtarget->isTargetMacho()) {
185 return new X86_64MachoTargetObjectFile();
186 return new TargetLoweringObjectFileMachO();
189 if (Subtarget->isTargetLinux())
190 return new X86LinuxTargetObjectFile();
191 if (Subtarget->isTargetELF())
192 return new TargetLoweringObjectFileELF();
193 if (Subtarget->isTargetKnownWindowsMSVC())
194 return new X86WindowsTargetObjectFile();
195 if (Subtarget->isTargetCOFF())
196 return new TargetLoweringObjectFileCOFF();
197 llvm_unreachable("unknown subtarget type");
200 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
201 : TargetLowering(TM, createTLOF(TM)) {
202 Subtarget = &TM.getSubtarget<X86Subtarget>();
203 X86ScalarSSEf64 = Subtarget->hasSSE2();
204 X86ScalarSSEf32 = Subtarget->hasSSE1();
205 TD = getDataLayout();
207 resetOperationActions();
210 void X86TargetLowering::resetOperationActions() {
211 const TargetMachine &TM = getTargetMachine();
212 static bool FirstTimeThrough = true;
214 // If none of the target options have changed, then we don't need to reset the
215 // operation actions.
216 if (!FirstTimeThrough && TO == TM.Options) return;
218 if (!FirstTimeThrough) {
219 // Reinitialize the actions.
221 FirstTimeThrough = false;
226 // Set up the TargetLowering object.
227 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
229 // X86 is weird, it always uses i8 for shift amounts and setcc results.
230 setBooleanContents(ZeroOrOneBooleanContent);
231 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
232 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
234 // For 64-bit since we have so many registers use the ILP scheduler, for
235 // 32-bit code use the register pressure specific scheduling.
236 // For Atom, always use ILP scheduling.
237 if (Subtarget->isAtom())
238 setSchedulingPreference(Sched::ILP);
239 else if (Subtarget->is64Bit())
240 setSchedulingPreference(Sched::ILP);
242 setSchedulingPreference(Sched::RegPressure);
243 const X86RegisterInfo *RegInfo =
244 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
245 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
247 // Bypass expensive divides on Atom when compiling with O2
248 if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
249 addBypassSlowDiv(32, 8);
250 if (Subtarget->is64Bit())
251 addBypassSlowDiv(64, 16);
254 if (Subtarget->isTargetKnownWindowsMSVC()) {
255 // Setup Windows compiler runtime calls.
256 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
257 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
258 setLibcallName(RTLIB::SREM_I64, "_allrem");
259 setLibcallName(RTLIB::UREM_I64, "_aullrem");
260 setLibcallName(RTLIB::MUL_I64, "_allmul");
261 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
262 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
263 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
264 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
265 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
267 // The _ftol2 runtime function has an unusual calling conv, which
268 // is modeled by a special pseudo-instruction.
269 setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
270 setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
271 setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
272 setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
275 if (Subtarget->isTargetDarwin()) {
276 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
277 setUseUnderscoreSetJmp(false);
278 setUseUnderscoreLongJmp(false);
279 } else if (Subtarget->isTargetWindowsGNU()) {
280 // MS runtime is weird: it exports _setjmp, but longjmp!
281 setUseUnderscoreSetJmp(true);
282 setUseUnderscoreLongJmp(false);
284 setUseUnderscoreSetJmp(true);
285 setUseUnderscoreLongJmp(true);
288 // Set up the register classes.
289 addRegisterClass(MVT::i8, &X86::GR8RegClass);
290 addRegisterClass(MVT::i16, &X86::GR16RegClass);
291 addRegisterClass(MVT::i32, &X86::GR32RegClass);
292 if (Subtarget->is64Bit())
293 addRegisterClass(MVT::i64, &X86::GR64RegClass);
295 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
297 // We don't accept any truncstore of integer registers.
298 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
299 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
300 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
301 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
302 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
303 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
305 // SETOEQ and SETUNE require checking two conditions.
306 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
307 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
308 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
309 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
310 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
311 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
313 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
315 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
316 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
317 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
319 if (Subtarget->is64Bit()) {
320 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
321 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
322 } else if (!TM.Options.UseSoftFloat) {
323 // We have an algorithm for SSE2->double, and we turn this into a
324 // 64-bit FILD followed by conditional FADD for other targets.
325 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
326 // We have an algorithm for SSE2, and we turn this into a 64-bit
327 // FILD for other targets.
328 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
331 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
333 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
334 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
336 if (!TM.Options.UseSoftFloat) {
337 // SSE has no i16 to fp conversion, only i32
338 if (X86ScalarSSEf32) {
339 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
340 // f32 and f64 cases are Legal, f80 case is not
341 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
343 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
344 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
347 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
348 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
351 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
352 // are Legal, f80 is custom lowered.
353 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
354 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
356 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
358 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
359 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
361 if (X86ScalarSSEf32) {
362 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
363 // f32 and f64 cases are Legal, f80 case is not
364 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
366 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
367 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
370 // Handle FP_TO_UINT by promoting the destination to a larger signed
372 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
373 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
374 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
376 if (Subtarget->is64Bit()) {
377 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
378 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
379 } else if (!TM.Options.UseSoftFloat) {
380 // Since AVX is a superset of SSE3, only check for SSE here.
381 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
382 // Expand FP_TO_UINT into a select.
383 // FIXME: We would like to use a Custom expander here eventually to do
384 // the optimal thing for SSE vs. the default expansion in the legalizer.
385 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
387 // With SSE3 we can use fisttpll to convert to a signed i64; without
388 // SSE, we're stuck with a fistpll.
389 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
392 if (isTargetFTOL()) {
393 // Use the _ftol2 runtime function, which has a pseudo-instruction
394 // to handle its weird calling convention.
395 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
398 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
399 if (!X86ScalarSSEf64) {
400 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
401 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
402 if (Subtarget->is64Bit()) {
403 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
404 // Without SSE, i64->f64 goes through memory.
405 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
409 // Scalar integer divide and remainder are lowered to use operations that
410 // produce two results, to match the available instructions. This exposes
411 // the two-result form to trivial CSE, which is able to combine x/y and x%y
412 // into a single instruction.
414 // Scalar integer multiply-high is also lowered to use two-result
415 // operations, to match the available instructions. However, plain multiply
416 // (low) operations are left as Legal, as there are single-result
417 // instructions for this in x86. Using the two-result multiply instructions
418 // when both high and low results are needed must be arranged by dagcombine.
419 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
421 setOperationAction(ISD::MULHS, VT, Expand);
422 setOperationAction(ISD::MULHU, VT, Expand);
423 setOperationAction(ISD::SDIV, VT, Expand);
424 setOperationAction(ISD::UDIV, VT, Expand);
425 setOperationAction(ISD::SREM, VT, Expand);
426 setOperationAction(ISD::UREM, VT, Expand);
428 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
429 setOperationAction(ISD::ADDC, VT, Custom);
430 setOperationAction(ISD::ADDE, VT, Custom);
431 setOperationAction(ISD::SUBC, VT, Custom);
432 setOperationAction(ISD::SUBE, VT, Custom);
435 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
436 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
437 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
438 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
439 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
440 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
441 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
442 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
443 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
444 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
445 if (Subtarget->is64Bit())
446 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
447 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
448 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
449 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
450 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
451 setOperationAction(ISD::FREM , MVT::f32 , Expand);
452 setOperationAction(ISD::FREM , MVT::f64 , Expand);
453 setOperationAction(ISD::FREM , MVT::f80 , Expand);
454 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
456 // Promote the i8 variants and force them on up to i32 which has a shorter
458 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
459 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
460 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
461 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
462 if (Subtarget->hasBMI()) {
463 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
464 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
465 if (Subtarget->is64Bit())
466 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
468 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
469 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
470 if (Subtarget->is64Bit())
471 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
474 if (Subtarget->hasLZCNT()) {
475 // When promoting the i8 variants, force them to i32 for a shorter
477 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
478 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
479 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
480 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
481 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
482 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
483 if (Subtarget->is64Bit())
484 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
486 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
487 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
488 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
489 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
490 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
491 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
492 if (Subtarget->is64Bit()) {
493 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
494 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
498 if (Subtarget->hasPOPCNT()) {
499 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
501 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
502 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
503 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
504 if (Subtarget->is64Bit())
505 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
508 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
510 if (!Subtarget->hasMOVBE())
511 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
513 // These should be promoted to a larger select which is supported.
514 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
515 // X86 wants to expand cmov itself.
516 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
517 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
518 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
519 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
520 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
521 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
522 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
523 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
524 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
525 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
526 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
527 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
528 if (Subtarget->is64Bit()) {
529 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
530 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
532 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
533 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
534 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
535 // support continuation, user-level threading, and etc.. As a result, no
536 // other SjLj exception interfaces are implemented and please don't build
537 // your own exception handling based on them.
538 // LLVM/Clang supports zero-cost DWARF exception handling.
539 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
540 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
543 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
544 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
545 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
546 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
547 if (Subtarget->is64Bit())
548 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
549 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
550 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
551 if (Subtarget->is64Bit()) {
552 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
553 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
554 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
555 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
556 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
558 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
559 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
560 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
561 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
562 if (Subtarget->is64Bit()) {
563 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
564 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
565 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
568 if (Subtarget->hasSSE1())
569 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
571 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
573 // Expand certain atomics
574 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
576 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
577 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
578 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
581 if (!Subtarget->is64Bit()) {
582 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
583 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
584 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
585 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
586 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
587 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
588 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
589 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
590 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
591 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
592 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
593 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
596 if (Subtarget->hasCmpxchg16b()) {
597 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
600 // FIXME - use subtarget debug flags
601 if (!Subtarget->isTargetDarwin() &&
602 !Subtarget->isTargetELF() &&
603 !Subtarget->isTargetCygMing()) {
604 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
607 if (Subtarget->is64Bit()) {
608 setExceptionPointerRegister(X86::RAX);
609 setExceptionSelectorRegister(X86::RDX);
611 setExceptionPointerRegister(X86::EAX);
612 setExceptionSelectorRegister(X86::EDX);
614 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
615 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
617 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
618 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
620 setOperationAction(ISD::TRAP, MVT::Other, Legal);
621 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
623 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
624 setOperationAction(ISD::VASTART , MVT::Other, Custom);
625 setOperationAction(ISD::VAEND , MVT::Other, Expand);
626 if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
627 // TargetInfo::X86_64ABIBuiltinVaList
628 setOperationAction(ISD::VAARG , MVT::Other, Custom);
629 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
631 // TargetInfo::CharPtrBuiltinVaList
632 setOperationAction(ISD::VAARG , MVT::Other, Expand);
633 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
636 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
637 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
639 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
640 MVT::i64 : MVT::i32, Custom);
642 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
643 // f32 and f64 use SSE.
644 // Set up the FP register classes.
645 addRegisterClass(MVT::f32, &X86::FR32RegClass);
646 addRegisterClass(MVT::f64, &X86::FR64RegClass);
648 // Use ANDPD to simulate FABS.
649 setOperationAction(ISD::FABS , MVT::f64, Custom);
650 setOperationAction(ISD::FABS , MVT::f32, Custom);
652 // Use XORP to simulate FNEG.
653 setOperationAction(ISD::FNEG , MVT::f64, Custom);
654 setOperationAction(ISD::FNEG , MVT::f32, Custom);
656 // Use ANDPD and ORPD to simulate FCOPYSIGN.
657 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
658 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
660 // Lower this to FGETSIGNx86 plus an AND.
661 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
662 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
664 // We don't support sin/cos/fmod
665 setOperationAction(ISD::FSIN , MVT::f64, Expand);
666 setOperationAction(ISD::FCOS , MVT::f64, Expand);
667 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
668 setOperationAction(ISD::FSIN , MVT::f32, Expand);
669 setOperationAction(ISD::FCOS , MVT::f32, Expand);
670 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
672 // Expand FP immediates into loads from the stack, except for the special
674 addLegalFPImmediate(APFloat(+0.0)); // xorpd
675 addLegalFPImmediate(APFloat(+0.0f)); // xorps
676 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
677 // Use SSE for f32, x87 for f64.
678 // Set up the FP register classes.
679 addRegisterClass(MVT::f32, &X86::FR32RegClass);
680 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
682 // Use ANDPS to simulate FABS.
683 setOperationAction(ISD::FABS , MVT::f32, Custom);
685 // Use XORP to simulate FNEG.
686 setOperationAction(ISD::FNEG , MVT::f32, Custom);
688 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
690 // Use ANDPS and ORPS to simulate FCOPYSIGN.
691 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
692 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
694 // We don't support sin/cos/fmod
695 setOperationAction(ISD::FSIN , MVT::f32, Expand);
696 setOperationAction(ISD::FCOS , MVT::f32, Expand);
697 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
699 // Special cases we handle for FP constants.
700 addLegalFPImmediate(APFloat(+0.0f)); // xorps
701 addLegalFPImmediate(APFloat(+0.0)); // FLD0
702 addLegalFPImmediate(APFloat(+1.0)); // FLD1
703 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
704 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
706 if (!TM.Options.UnsafeFPMath) {
707 setOperationAction(ISD::FSIN , MVT::f64, Expand);
708 setOperationAction(ISD::FCOS , MVT::f64, Expand);
709 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
711 } else if (!TM.Options.UseSoftFloat) {
712 // f32 and f64 in x87.
713 // Set up the FP register classes.
714 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
715 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
717 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
718 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
719 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
720 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
722 if (!TM.Options.UnsafeFPMath) {
723 setOperationAction(ISD::FSIN , MVT::f64, Expand);
724 setOperationAction(ISD::FSIN , MVT::f32, Expand);
725 setOperationAction(ISD::FCOS , MVT::f64, Expand);
726 setOperationAction(ISD::FCOS , MVT::f32, Expand);
727 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
728 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
730 addLegalFPImmediate(APFloat(+0.0)); // FLD0
731 addLegalFPImmediate(APFloat(+1.0)); // FLD1
732 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
733 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
734 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
735 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
736 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
737 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
740 // We don't support FMA.
741 setOperationAction(ISD::FMA, MVT::f64, Expand);
742 setOperationAction(ISD::FMA, MVT::f32, Expand);
744 // Long double always uses X87.
745 if (!TM.Options.UseSoftFloat) {
746 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
747 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
748 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
750 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
751 addLegalFPImmediate(TmpFlt); // FLD0
753 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
756 APFloat TmpFlt2(+1.0);
757 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
759 addLegalFPImmediate(TmpFlt2); // FLD1
760 TmpFlt2.changeSign();
761 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
764 if (!TM.Options.UnsafeFPMath) {
765 setOperationAction(ISD::FSIN , MVT::f80, Expand);
766 setOperationAction(ISD::FCOS , MVT::f80, Expand);
767 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
770 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
771 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
772 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
773 setOperationAction(ISD::FRINT, MVT::f80, Expand);
774 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
775 setOperationAction(ISD::FMA, MVT::f80, Expand);
778 // Always use a library call for pow.
779 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
780 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
781 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
783 setOperationAction(ISD::FLOG, MVT::f80, Expand);
784 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
785 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
786 setOperationAction(ISD::FEXP, MVT::f80, Expand);
787 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
789 // First set operation action for all vector types to either promote
790 // (for widening) or expand (for scalarization). Then we will selectively
791 // turn on ones that can be effectively codegen'd.
792 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
793 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
794 MVT VT = (MVT::SimpleValueType)i;
795 setOperationAction(ISD::ADD , VT, Expand);
796 setOperationAction(ISD::SUB , VT, Expand);
797 setOperationAction(ISD::FADD, VT, Expand);
798 setOperationAction(ISD::FNEG, VT, Expand);
799 setOperationAction(ISD::FSUB, VT, Expand);
800 setOperationAction(ISD::MUL , VT, Expand);
801 setOperationAction(ISD::FMUL, VT, Expand);
802 setOperationAction(ISD::SDIV, VT, Expand);
803 setOperationAction(ISD::UDIV, VT, Expand);
804 setOperationAction(ISD::FDIV, VT, Expand);
805 setOperationAction(ISD::SREM, VT, Expand);
806 setOperationAction(ISD::UREM, VT, Expand);
807 setOperationAction(ISD::LOAD, VT, Expand);
808 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
809 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
810 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
811 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
812 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
813 setOperationAction(ISD::FABS, VT, Expand);
814 setOperationAction(ISD::FSIN, VT, Expand);
815 setOperationAction(ISD::FSINCOS, VT, Expand);
816 setOperationAction(ISD::FCOS, VT, Expand);
817 setOperationAction(ISD::FSINCOS, VT, Expand);
818 setOperationAction(ISD::FREM, VT, Expand);
819 setOperationAction(ISD::FMA, VT, Expand);
820 setOperationAction(ISD::FPOWI, VT, Expand);
821 setOperationAction(ISD::FSQRT, VT, Expand);
822 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
823 setOperationAction(ISD::FFLOOR, VT, Expand);
824 setOperationAction(ISD::FCEIL, VT, Expand);
825 setOperationAction(ISD::FTRUNC, VT, Expand);
826 setOperationAction(ISD::FRINT, VT, Expand);
827 setOperationAction(ISD::FNEARBYINT, VT, Expand);
828 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
829 setOperationAction(ISD::MULHS, VT, Expand);
830 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
831 setOperationAction(ISD::MULHU, VT, Expand);
832 setOperationAction(ISD::SDIVREM, VT, Expand);
833 setOperationAction(ISD::UDIVREM, VT, Expand);
834 setOperationAction(ISD::FPOW, VT, Expand);
835 setOperationAction(ISD::CTPOP, VT, Expand);
836 setOperationAction(ISD::CTTZ, VT, Expand);
837 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
838 setOperationAction(ISD::CTLZ, VT, Expand);
839 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
840 setOperationAction(ISD::SHL, VT, Expand);
841 setOperationAction(ISD::SRA, VT, Expand);
842 setOperationAction(ISD::SRL, VT, Expand);
843 setOperationAction(ISD::ROTL, VT, Expand);
844 setOperationAction(ISD::ROTR, VT, Expand);
845 setOperationAction(ISD::BSWAP, VT, Expand);
846 setOperationAction(ISD::SETCC, VT, Expand);
847 setOperationAction(ISD::FLOG, VT, Expand);
848 setOperationAction(ISD::FLOG2, VT, Expand);
849 setOperationAction(ISD::FLOG10, VT, Expand);
850 setOperationAction(ISD::FEXP, VT, Expand);
851 setOperationAction(ISD::FEXP2, VT, Expand);
852 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
853 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
854 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
855 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
856 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
857 setOperationAction(ISD::TRUNCATE, VT, Expand);
858 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
859 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
860 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
861 setOperationAction(ISD::VSELECT, VT, Expand);
862 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
863 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
864 setTruncStoreAction(VT,
865 (MVT::SimpleValueType)InnerVT, Expand);
866 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
867 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
868 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
871 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
872 // with -msoft-float, disable use of MMX as well.
873 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
874 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
875 // No operations on x86mmx supported, everything uses intrinsics.
878 // MMX-sized vectors (other than x86mmx) are expected to be expanded
879 // into smaller operations.
880 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
881 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
882 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
883 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
884 setOperationAction(ISD::AND, MVT::v8i8, Expand);
885 setOperationAction(ISD::AND, MVT::v4i16, Expand);
886 setOperationAction(ISD::AND, MVT::v2i32, Expand);
887 setOperationAction(ISD::AND, MVT::v1i64, Expand);
888 setOperationAction(ISD::OR, MVT::v8i8, Expand);
889 setOperationAction(ISD::OR, MVT::v4i16, Expand);
890 setOperationAction(ISD::OR, MVT::v2i32, Expand);
891 setOperationAction(ISD::OR, MVT::v1i64, Expand);
892 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
893 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
894 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
895 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
896 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
897 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
898 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
899 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
900 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
901 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
902 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
903 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
904 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
905 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
906 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
907 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
908 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
910 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
911 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
913 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
914 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
915 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
916 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
917 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
918 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
919 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
920 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
921 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
922 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
923 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
924 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
927 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
928 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
930 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
931 // registers cannot be used even for integer operations.
932 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
933 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
934 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
935 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
937 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
938 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
939 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
940 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
941 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
942 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
943 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
944 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
945 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
946 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
947 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
948 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
949 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
950 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
951 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
952 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
953 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
954 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
955 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
956 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
957 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
959 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
960 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
961 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
962 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
964 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
965 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
966 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
967 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
968 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
970 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
971 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
972 MVT VT = (MVT::SimpleValueType)i;
973 // Do not attempt to custom lower non-power-of-2 vectors
974 if (!isPowerOf2_32(VT.getVectorNumElements()))
976 // Do not attempt to custom lower non-128-bit vectors
977 if (!VT.is128BitVector())
979 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
980 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
981 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
984 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
985 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
986 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
987 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
988 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
989 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
991 if (Subtarget->is64Bit()) {
992 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
993 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
996 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
997 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
998 MVT VT = (MVT::SimpleValueType)i;
1000 // Do not attempt to promote non-128-bit vectors
1001 if (!VT.is128BitVector())
1004 setOperationAction(ISD::AND, VT, Promote);
1005 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
1006 setOperationAction(ISD::OR, VT, Promote);
1007 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
1008 setOperationAction(ISD::XOR, VT, Promote);
1009 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
1010 setOperationAction(ISD::LOAD, VT, Promote);
1011 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
1012 setOperationAction(ISD::SELECT, VT, Promote);
1013 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1016 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1018 // Custom lower v2i64 and v2f64 selects.
1019 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
1020 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
1021 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
1022 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
1024 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1025 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1027 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1028 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1029 // As there is no 64-bit GPR available, we need build a special custom
1030 // sequence to convert from v2i32 to v2f32.
1031 if (!Subtarget->is64Bit())
1032 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
1034 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1035 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
1037 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
1040 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1041 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1042 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1043 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1044 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1045 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1046 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1047 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1048 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1049 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1050 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1052 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1053 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
1054 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1055 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
1056 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
1057 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
1058 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
1059 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
1060 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
1061 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
1063 // FIXME: Do we need to handle scalar-to-vector here?
1064 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1066 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
1067 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal);
1068 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
1069 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
1070 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
1072 // i8 and i16 vectors are custom , because the source register and source
1073 // source memory operand types are not the same width. f32 vectors are
1074 // custom since the immediate controlling the insert encodes additional
1076 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1077 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1078 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1079 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1081 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1082 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1083 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1084 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1086 // FIXME: these should be Legal but thats only for the case where
1087 // the index is constant. For now custom expand to deal with that.
1088 if (Subtarget->is64Bit()) {
1089 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1090 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1094 if (Subtarget->hasSSE2()) {
1095 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1096 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1098 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1099 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1101 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1102 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1104 // In the customized shift lowering, the legal cases in AVX2 will be
1106 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1107 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1109 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1110 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1112 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1115 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1116 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1117 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1118 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1119 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1120 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1121 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1123 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1124 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1125 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1127 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1128 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1129 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1130 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1131 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1132 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1133 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1134 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1135 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1136 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1137 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1138 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1140 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1141 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1142 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1143 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1144 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1145 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1146 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1147 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1148 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1149 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1150 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1151 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1153 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1154 // even though v8i16 is a legal type.
1155 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1156 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1157 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1159 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1160 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1161 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1163 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1164 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1166 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1168 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1169 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1171 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1172 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1174 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1175 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1177 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1178 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1179 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1180 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1182 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1183 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1184 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1186 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1187 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal);
1188 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal);
1189 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal);
1191 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1192 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1193 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1194 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1195 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1196 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1197 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1198 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1199 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1200 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1201 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1202 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1204 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1205 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1206 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1207 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1208 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1209 setOperationAction(ISD::FMA, MVT::f32, Legal);
1210 setOperationAction(ISD::FMA, MVT::f64, Legal);
1213 if (Subtarget->hasInt256()) {
1214 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1215 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1216 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1217 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1219 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1220 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1221 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1222 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1224 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1225 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1226 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1227 // Don't lower v32i8 because there is no 128-bit byte mul
1229 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1230 setOperationAction(ISD::MULHU, MVT::v16i16, Legal);
1231 setOperationAction(ISD::MULHS, MVT::v16i16, Legal);
1233 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1235 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1236 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1237 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1238 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1240 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1241 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1242 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1243 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1245 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1246 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1247 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1248 // Don't lower v32i8 because there is no 128-bit byte mul
1251 // In the customized shift lowering, the legal cases in AVX2 will be
1253 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1254 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1256 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1257 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1259 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1261 // Custom lower several nodes for 256-bit types.
1262 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1263 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1264 MVT VT = (MVT::SimpleValueType)i;
1266 // Extract subvector is special because the value type
1267 // (result) is 128-bit but the source is 256-bit wide.
1268 if (VT.is128BitVector())
1269 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1271 // Do not attempt to custom lower other non-256-bit vectors
1272 if (!VT.is256BitVector())
1275 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1276 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1277 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1278 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1279 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1280 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1281 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1284 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1285 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1286 MVT VT = (MVT::SimpleValueType)i;
1288 // Do not attempt to promote non-256-bit vectors
1289 if (!VT.is256BitVector())
1292 setOperationAction(ISD::AND, VT, Promote);
1293 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1294 setOperationAction(ISD::OR, VT, Promote);
1295 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1296 setOperationAction(ISD::XOR, VT, Promote);
1297 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1298 setOperationAction(ISD::LOAD, VT, Promote);
1299 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1300 setOperationAction(ISD::SELECT, VT, Promote);
1301 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1305 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1306 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1307 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1308 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1309 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1311 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1312 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1313 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1315 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1316 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1317 setOperationAction(ISD::XOR, MVT::i1, Legal);
1318 setOperationAction(ISD::OR, MVT::i1, Legal);
1319 setOperationAction(ISD::AND, MVT::i1, Legal);
1320 setLoadExtAction(ISD::EXTLOAD, MVT::v8f32, Legal);
1321 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1322 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1323 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1324 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1325 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1327 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1328 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1329 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1330 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1331 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1332 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1334 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1335 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1336 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1337 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1338 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1339 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1340 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1341 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1343 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1344 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1345 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1346 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1347 if (Subtarget->is64Bit()) {
1348 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1349 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1350 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1351 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1353 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1354 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1355 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1356 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1357 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1358 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1359 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1360 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1361 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1362 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1364 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1365 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1366 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1367 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1368 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1369 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1370 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1371 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1372 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1373 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1374 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1375 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1376 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1378 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1379 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1380 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1381 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1382 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1383 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1385 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1386 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1388 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1390 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1391 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1392 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1393 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1394 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1395 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1396 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1397 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1398 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1400 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1401 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1403 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1404 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1406 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1408 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1409 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1411 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1412 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1414 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1415 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1417 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1418 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1419 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1420 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1421 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1422 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1424 // Custom lower several nodes.
1425 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1426 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1427 MVT VT = (MVT::SimpleValueType)i;
1429 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1430 // Extract subvector is special because the value type
1431 // (result) is 256/128-bit but the source is 512-bit wide.
1432 if (VT.is128BitVector() || VT.is256BitVector())
1433 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1435 if (VT.getVectorElementType() == MVT::i1)
1436 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1438 // Do not attempt to custom lower other non-512-bit vectors
1439 if (!VT.is512BitVector())
1442 if ( EltSize >= 32) {
1443 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1444 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1445 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1446 setOperationAction(ISD::VSELECT, VT, Legal);
1447 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1448 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1449 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1452 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1453 MVT VT = (MVT::SimpleValueType)i;
1455 // Do not attempt to promote non-256-bit vectors
1456 if (!VT.is512BitVector())
1459 setOperationAction(ISD::SELECT, VT, Promote);
1460 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1464 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1465 // of this type with custom code.
1466 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1467 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1468 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1472 // We want to custom lower some of our intrinsics.
1473 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1474 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1475 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1476 if (!Subtarget->is64Bit())
1477 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1479 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1480 // handle type legalization for these operations here.
1482 // FIXME: We really should do custom legalization for addition and
1483 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1484 // than generic legalization for 64-bit multiplication-with-overflow, though.
1485 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1486 // Add/Sub/Mul with overflow operations are custom lowered.
1488 setOperationAction(ISD::SADDO, VT, Custom);
1489 setOperationAction(ISD::UADDO, VT, Custom);
1490 setOperationAction(ISD::SSUBO, VT, Custom);
1491 setOperationAction(ISD::USUBO, VT, Custom);
1492 setOperationAction(ISD::SMULO, VT, Custom);
1493 setOperationAction(ISD::UMULO, VT, Custom);
1496 // There are no 8-bit 3-address imul/mul instructions
1497 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1498 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1500 if (!Subtarget->is64Bit()) {
1501 // These libcalls are not available in 32-bit.
1502 setLibcallName(RTLIB::SHL_I128, nullptr);
1503 setLibcallName(RTLIB::SRL_I128, nullptr);
1504 setLibcallName(RTLIB::SRA_I128, nullptr);
1507 // Combine sin / cos into one node or libcall if possible.
1508 if (Subtarget->hasSinCos()) {
1509 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1510 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1511 if (Subtarget->isTargetDarwin()) {
1512 // For MacOSX, we don't want to the normal expansion of a libcall to
1513 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1515 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1516 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1520 // We have target-specific dag combine patterns for the following nodes:
1521 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1522 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1523 setTargetDAGCombine(ISD::VSELECT);
1524 setTargetDAGCombine(ISD::SELECT);
1525 setTargetDAGCombine(ISD::SHL);
1526 setTargetDAGCombine(ISD::SRA);
1527 setTargetDAGCombine(ISD::SRL);
1528 setTargetDAGCombine(ISD::OR);
1529 setTargetDAGCombine(ISD::AND);
1530 setTargetDAGCombine(ISD::ADD);
1531 setTargetDAGCombine(ISD::FADD);
1532 setTargetDAGCombine(ISD::FSUB);
1533 setTargetDAGCombine(ISD::FMA);
1534 setTargetDAGCombine(ISD::SUB);
1535 setTargetDAGCombine(ISD::LOAD);
1536 setTargetDAGCombine(ISD::STORE);
1537 setTargetDAGCombine(ISD::ZERO_EXTEND);
1538 setTargetDAGCombine(ISD::ANY_EXTEND);
1539 setTargetDAGCombine(ISD::SIGN_EXTEND);
1540 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1541 setTargetDAGCombine(ISD::TRUNCATE);
1542 setTargetDAGCombine(ISD::SINT_TO_FP);
1543 setTargetDAGCombine(ISD::SETCC);
1544 if (Subtarget->is64Bit())
1545 setTargetDAGCombine(ISD::MUL);
1546 setTargetDAGCombine(ISD::XOR);
1548 computeRegisterProperties();
1550 // On Darwin, -Os means optimize for size without hurting performance,
1551 // do not reduce the limit.
1552 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1553 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1554 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1555 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1556 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1557 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1558 setPrefLoopAlignment(4); // 2^4 bytes.
1560 // Predictable cmov don't hurt on atom because it's in-order.
1561 PredictableSelectIsExpensive = !Subtarget->isAtom();
1563 setPrefFunctionAlignment(4); // 2^4 bytes.
1566 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1568 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1570 if (Subtarget->hasAVX512())
1571 switch(VT.getVectorNumElements()) {
1572 case 8: return MVT::v8i1;
1573 case 16: return MVT::v16i1;
1576 return VT.changeVectorElementTypeToInteger();
1579 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1580 /// the desired ByVal argument alignment.
1581 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1584 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1585 if (VTy->getBitWidth() == 128)
1587 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1588 unsigned EltAlign = 0;
1589 getMaxByValAlign(ATy->getElementType(), EltAlign);
1590 if (EltAlign > MaxAlign)
1591 MaxAlign = EltAlign;
1592 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1593 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1594 unsigned EltAlign = 0;
1595 getMaxByValAlign(STy->getElementType(i), EltAlign);
1596 if (EltAlign > MaxAlign)
1597 MaxAlign = EltAlign;
1604 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1605 /// function arguments in the caller parameter area. For X86, aggregates
1606 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1607 /// are at 4-byte boundaries.
1608 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1609 if (Subtarget->is64Bit()) {
1610 // Max of 8 and alignment of type.
1611 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1618 if (Subtarget->hasSSE1())
1619 getMaxByValAlign(Ty, Align);
1623 /// getOptimalMemOpType - Returns the target specific optimal type for load
1624 /// and store operations as a result of memset, memcpy, and memmove
1625 /// lowering. If DstAlign is zero that means it's safe to destination
1626 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1627 /// means there isn't a need to check it against alignment requirement,
1628 /// probably because the source does not need to be loaded. If 'IsMemset' is
1629 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1630 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1631 /// source is constant so it does not need to be loaded.
1632 /// It returns EVT::Other if the type should be determined using generic
1633 /// target-independent logic.
1635 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1636 unsigned DstAlign, unsigned SrcAlign,
1637 bool IsMemset, bool ZeroMemset,
1639 MachineFunction &MF) const {
1640 const Function *F = MF.getFunction();
1641 if ((!IsMemset || ZeroMemset) &&
1642 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1643 Attribute::NoImplicitFloat)) {
1645 (Subtarget->isUnalignedMemAccessFast() ||
1646 ((DstAlign == 0 || DstAlign >= 16) &&
1647 (SrcAlign == 0 || SrcAlign >= 16)))) {
1649 if (Subtarget->hasInt256())
1651 if (Subtarget->hasFp256())
1654 if (Subtarget->hasSSE2())
1656 if (Subtarget->hasSSE1())
1658 } else if (!MemcpyStrSrc && Size >= 8 &&
1659 !Subtarget->is64Bit() &&
1660 Subtarget->hasSSE2()) {
1661 // Do not use f64 to lower memcpy if source is string constant. It's
1662 // better to use i32 to avoid the loads.
1666 if (Subtarget->is64Bit() && Size >= 8)
1671 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1673 return X86ScalarSSEf32;
1674 else if (VT == MVT::f64)
1675 return X86ScalarSSEf64;
1680 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1684 *Fast = Subtarget->isUnalignedMemAccessFast();
1688 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1689 /// current function. The returned value is a member of the
1690 /// MachineJumpTableInfo::JTEntryKind enum.
1691 unsigned X86TargetLowering::getJumpTableEncoding() const {
1692 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1694 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1695 Subtarget->isPICStyleGOT())
1696 return MachineJumpTableInfo::EK_Custom32;
1698 // Otherwise, use the normal jump table encoding heuristics.
1699 return TargetLowering::getJumpTableEncoding();
1703 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1704 const MachineBasicBlock *MBB,
1705 unsigned uid,MCContext &Ctx) const{
1706 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1707 Subtarget->isPICStyleGOT());
1708 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1710 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1711 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1714 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1716 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1717 SelectionDAG &DAG) const {
1718 if (!Subtarget->is64Bit())
1719 // This doesn't have SDLoc associated with it, but is not really the
1720 // same as a Register.
1721 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1725 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1726 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1728 const MCExpr *X86TargetLowering::
1729 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1730 MCContext &Ctx) const {
1731 // X86-64 uses RIP relative addressing based on the jump table label.
1732 if (Subtarget->isPICStyleRIPRel())
1733 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1735 // Otherwise, the reference is relative to the PIC base.
1736 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1739 // FIXME: Why this routine is here? Move to RegInfo!
1740 std::pair<const TargetRegisterClass*, uint8_t>
1741 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1742 const TargetRegisterClass *RRC = nullptr;
1744 switch (VT.SimpleTy) {
1746 return TargetLowering::findRepresentativeClass(VT);
1747 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1748 RRC = Subtarget->is64Bit() ?
1749 (const TargetRegisterClass*)&X86::GR64RegClass :
1750 (const TargetRegisterClass*)&X86::GR32RegClass;
1753 RRC = &X86::VR64RegClass;
1755 case MVT::f32: case MVT::f64:
1756 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1757 case MVT::v4f32: case MVT::v2f64:
1758 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1760 RRC = &X86::VR128RegClass;
1763 return std::make_pair(RRC, Cost);
1766 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1767 unsigned &Offset) const {
1768 if (!Subtarget->isTargetLinux())
1771 if (Subtarget->is64Bit()) {
1772 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1774 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1786 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1787 unsigned DestAS) const {
1788 assert(SrcAS != DestAS && "Expected different address spaces!");
1790 return SrcAS < 256 && DestAS < 256;
1793 //===----------------------------------------------------------------------===//
1794 // Return Value Calling Convention Implementation
1795 //===----------------------------------------------------------------------===//
1797 #include "X86GenCallingConv.inc"
1800 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1801 MachineFunction &MF, bool isVarArg,
1802 const SmallVectorImpl<ISD::OutputArg> &Outs,
1803 LLVMContext &Context) const {
1804 SmallVector<CCValAssign, 16> RVLocs;
1805 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1807 return CCInfo.CheckReturn(Outs, RetCC_X86);
1810 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1811 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1816 X86TargetLowering::LowerReturn(SDValue Chain,
1817 CallingConv::ID CallConv, bool isVarArg,
1818 const SmallVectorImpl<ISD::OutputArg> &Outs,
1819 const SmallVectorImpl<SDValue> &OutVals,
1820 SDLoc dl, SelectionDAG &DAG) const {
1821 MachineFunction &MF = DAG.getMachineFunction();
1822 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1824 SmallVector<CCValAssign, 16> RVLocs;
1825 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1826 RVLocs, *DAG.getContext());
1827 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1830 SmallVector<SDValue, 6> RetOps;
1831 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1832 // Operand #1 = Bytes To Pop
1833 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1836 // Copy the result values into the output registers.
1837 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1838 CCValAssign &VA = RVLocs[i];
1839 assert(VA.isRegLoc() && "Can only return in registers!");
1840 SDValue ValToCopy = OutVals[i];
1841 EVT ValVT = ValToCopy.getValueType();
1843 // Promote values to the appropriate types
1844 if (VA.getLocInfo() == CCValAssign::SExt)
1845 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1846 else if (VA.getLocInfo() == CCValAssign::ZExt)
1847 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1848 else if (VA.getLocInfo() == CCValAssign::AExt)
1849 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1850 else if (VA.getLocInfo() == CCValAssign::BCvt)
1851 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1853 assert(VA.getLocInfo() != CCValAssign::FPExt &&
1854 "Unexpected FP-extend for return value.");
1856 // If this is x86-64, and we disabled SSE, we can't return FP values,
1857 // or SSE or MMX vectors.
1858 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1859 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1860 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1861 report_fatal_error("SSE register return with SSE disabled");
1863 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1864 // llvm-gcc has never done it right and no one has noticed, so this
1865 // should be OK for now.
1866 if (ValVT == MVT::f64 &&
1867 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1868 report_fatal_error("SSE2 register return with SSE2 disabled");
1870 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1871 // the RET instruction and handled by the FP Stackifier.
1872 if (VA.getLocReg() == X86::ST0 ||
1873 VA.getLocReg() == X86::ST1) {
1874 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1875 // change the value to the FP stack register class.
1876 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1877 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1878 RetOps.push_back(ValToCopy);
1879 // Don't emit a copytoreg.
1883 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1884 // which is returned in RAX / RDX.
1885 if (Subtarget->is64Bit()) {
1886 if (ValVT == MVT::x86mmx) {
1887 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1888 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1889 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1891 // If we don't have SSE2 available, convert to v4f32 so the generated
1892 // register is legal.
1893 if (!Subtarget->hasSSE2())
1894 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1899 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1900 Flag = Chain.getValue(1);
1901 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1904 // The x86-64 ABIs require that for returning structs by value we copy
1905 // the sret argument into %rax/%eax (depending on ABI) for the return.
1906 // Win32 requires us to put the sret argument to %eax as well.
1907 // We saved the argument into a virtual register in the entry block,
1908 // so now we copy the value out and into %rax/%eax.
1909 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1910 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1911 MachineFunction &MF = DAG.getMachineFunction();
1912 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1913 unsigned Reg = FuncInfo->getSRetReturnReg();
1915 "SRetReturnReg should have been set in LowerFormalArguments().");
1916 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1919 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1920 X86::RAX : X86::EAX;
1921 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1922 Flag = Chain.getValue(1);
1924 // RAX/EAX now acts like a return value.
1925 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1928 RetOps[0] = Chain; // Update chain.
1930 // Add the flag if we have it.
1932 RetOps.push_back(Flag);
1934 return DAG.getNode(X86ISD::RET_FLAG, dl,
1935 MVT::Other, &RetOps[0], RetOps.size());
1938 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1939 if (N->getNumValues() != 1)
1941 if (!N->hasNUsesOfValue(1, 0))
1944 SDValue TCChain = Chain;
1945 SDNode *Copy = *N->use_begin();
1946 if (Copy->getOpcode() == ISD::CopyToReg) {
1947 // If the copy has a glue operand, we conservatively assume it isn't safe to
1948 // perform a tail call.
1949 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1951 TCChain = Copy->getOperand(0);
1952 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1955 bool HasRet = false;
1956 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1958 if (UI->getOpcode() != X86ISD::RET_FLAG)
1971 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1972 ISD::NodeType ExtendKind) const {
1974 // TODO: Is this also valid on 32-bit?
1975 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1976 ReturnMVT = MVT::i8;
1978 ReturnMVT = MVT::i32;
1980 MVT MinVT = getRegisterType(ReturnMVT);
1981 return VT.bitsLT(MinVT) ? MinVT : VT;
1984 /// LowerCallResult - Lower the result values of a call into the
1985 /// appropriate copies out of appropriate physical registers.
1988 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1989 CallingConv::ID CallConv, bool isVarArg,
1990 const SmallVectorImpl<ISD::InputArg> &Ins,
1991 SDLoc dl, SelectionDAG &DAG,
1992 SmallVectorImpl<SDValue> &InVals) const {
1994 // Assign locations to each value returned by this call.
1995 SmallVector<CCValAssign, 16> RVLocs;
1996 bool Is64Bit = Subtarget->is64Bit();
1997 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1998 getTargetMachine(), RVLocs, *DAG.getContext());
1999 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2001 // Copy all of the result registers out of their specified physreg.
2002 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2003 CCValAssign &VA = RVLocs[i];
2004 EVT CopyVT = VA.getValVT();
2006 // If this is x86-64, and we disabled SSE, we can't return FP values
2007 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2008 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2009 report_fatal_error("SSE register return with SSE disabled");
2014 // If this is a call to a function that returns an fp value on the floating
2015 // point stack, we must guarantee the value is popped from the stack, so
2016 // a CopyFromReg is not good enough - the copy instruction may be eliminated
2017 // if the return value is not used. We use the FpPOP_RETVAL instruction
2019 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2020 // If we prefer to use the value in xmm registers, copy it out as f80 and
2021 // use a truncate to move it from fp stack reg to xmm reg.
2022 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2023 SDValue Ops[] = { Chain, InFlag };
2024 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2025 MVT::Other, MVT::Glue, Ops), 1);
2026 Val = Chain.getValue(0);
2028 // Round the f80 to the right size, which also moves it to the appropriate
2030 if (CopyVT != VA.getValVT())
2031 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2032 // This truncation won't change the value.
2033 DAG.getIntPtrConstant(1));
2035 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2036 CopyVT, InFlag).getValue(1);
2037 Val = Chain.getValue(0);
2039 InFlag = Chain.getValue(2);
2040 InVals.push_back(Val);
2046 //===----------------------------------------------------------------------===//
2047 // C & StdCall & Fast Calling Convention implementation
2048 //===----------------------------------------------------------------------===//
2049 // StdCall calling convention seems to be standard for many Windows' API
2050 // routines and around. It differs from C calling convention just a little:
2051 // callee should clean up the stack, not caller. Symbols should be also
2052 // decorated in some fancy way :) It doesn't support any vector arguments.
2053 // For info on fast calling convention see Fast Calling Convention (tail call)
2054 // implementation LowerX86_32FastCCCallTo.
2056 /// CallIsStructReturn - Determines whether a call uses struct return
2058 enum StructReturnType {
2063 static StructReturnType
2064 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2066 return NotStructReturn;
2068 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2069 if (!Flags.isSRet())
2070 return NotStructReturn;
2071 if (Flags.isInReg())
2072 return RegStructReturn;
2073 return StackStructReturn;
2076 /// ArgsAreStructReturn - Determines whether a function uses struct
2077 /// return semantics.
2078 static StructReturnType
2079 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2081 return NotStructReturn;
2083 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2084 if (!Flags.isSRet())
2085 return NotStructReturn;
2086 if (Flags.isInReg())
2087 return RegStructReturn;
2088 return StackStructReturn;
2091 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2092 /// by "Src" to address "Dst" with size and alignment information specified by
2093 /// the specific parameter attribute. The copy will be passed as a byval
2094 /// function parameter.
2096 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2097 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2099 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2101 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2102 /*isVolatile*/false, /*AlwaysInline=*/true,
2103 MachinePointerInfo(), MachinePointerInfo());
2106 /// IsTailCallConvention - Return true if the calling convention is one that
2107 /// supports tail call optimization.
2108 static bool IsTailCallConvention(CallingConv::ID CC) {
2109 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2110 CC == CallingConv::HiPE);
2113 /// \brief Return true if the calling convention is a C calling convention.
2114 static bool IsCCallConvention(CallingConv::ID CC) {
2115 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2116 CC == CallingConv::X86_64_SysV);
2119 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2120 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2124 CallingConv::ID CalleeCC = CS.getCallingConv();
2125 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2131 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2132 /// a tailcall target by changing its ABI.
2133 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2134 bool GuaranteedTailCallOpt) {
2135 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2139 X86TargetLowering::LowerMemArgument(SDValue Chain,
2140 CallingConv::ID CallConv,
2141 const SmallVectorImpl<ISD::InputArg> &Ins,
2142 SDLoc dl, SelectionDAG &DAG,
2143 const CCValAssign &VA,
2144 MachineFrameInfo *MFI,
2146 // Create the nodes corresponding to a load from this parameter slot.
2147 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2148 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2149 getTargetMachine().Options.GuaranteedTailCallOpt);
2150 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2153 // If value is passed by pointer we have address passed instead of the value
2155 if (VA.getLocInfo() == CCValAssign::Indirect)
2156 ValVT = VA.getLocVT();
2158 ValVT = VA.getValVT();
2160 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2161 // changed with more analysis.
2162 // In case of tail call optimization mark all arguments mutable. Since they
2163 // could be overwritten by lowering of arguments in case of a tail call.
2164 if (Flags.isByVal()) {
2165 unsigned Bytes = Flags.getByValSize();
2166 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2167 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2168 return DAG.getFrameIndex(FI, getPointerTy());
2170 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2171 VA.getLocMemOffset(), isImmutable);
2172 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2173 return DAG.getLoad(ValVT, dl, Chain, FIN,
2174 MachinePointerInfo::getFixedStack(FI),
2175 false, false, false, 0);
2180 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2181 CallingConv::ID CallConv,
2183 const SmallVectorImpl<ISD::InputArg> &Ins,
2186 SmallVectorImpl<SDValue> &InVals)
2188 MachineFunction &MF = DAG.getMachineFunction();
2189 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2191 const Function* Fn = MF.getFunction();
2192 if (Fn->hasExternalLinkage() &&
2193 Subtarget->isTargetCygMing() &&
2194 Fn->getName() == "main")
2195 FuncInfo->setForceFramePointer(true);
2197 MachineFrameInfo *MFI = MF.getFrameInfo();
2198 bool Is64Bit = Subtarget->is64Bit();
2199 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2201 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2202 "Var args not supported with calling convention fastcc, ghc or hipe");
2204 // Assign locations to all of the incoming arguments.
2205 SmallVector<CCValAssign, 16> ArgLocs;
2206 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2207 ArgLocs, *DAG.getContext());
2209 // Allocate shadow area for Win64
2211 CCInfo.AllocateStack(32, 8);
2213 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2215 unsigned LastVal = ~0U;
2217 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2218 CCValAssign &VA = ArgLocs[i];
2219 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2221 assert(VA.getValNo() != LastVal &&
2222 "Don't support value assigned to multiple locs yet");
2224 LastVal = VA.getValNo();
2226 if (VA.isRegLoc()) {
2227 EVT RegVT = VA.getLocVT();
2228 const TargetRegisterClass *RC;
2229 if (RegVT == MVT::i32)
2230 RC = &X86::GR32RegClass;
2231 else if (Is64Bit && RegVT == MVT::i64)
2232 RC = &X86::GR64RegClass;
2233 else if (RegVT == MVT::f32)
2234 RC = &X86::FR32RegClass;
2235 else if (RegVT == MVT::f64)
2236 RC = &X86::FR64RegClass;
2237 else if (RegVT.is512BitVector())
2238 RC = &X86::VR512RegClass;
2239 else if (RegVT.is256BitVector())
2240 RC = &X86::VR256RegClass;
2241 else if (RegVT.is128BitVector())
2242 RC = &X86::VR128RegClass;
2243 else if (RegVT == MVT::x86mmx)
2244 RC = &X86::VR64RegClass;
2245 else if (RegVT == MVT::i1)
2246 RC = &X86::VK1RegClass;
2247 else if (RegVT == MVT::v8i1)
2248 RC = &X86::VK8RegClass;
2249 else if (RegVT == MVT::v16i1)
2250 RC = &X86::VK16RegClass;
2252 llvm_unreachable("Unknown argument type!");
2254 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2255 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2257 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2258 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2260 if (VA.getLocInfo() == CCValAssign::SExt)
2261 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2262 DAG.getValueType(VA.getValVT()));
2263 else if (VA.getLocInfo() == CCValAssign::ZExt)
2264 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2265 DAG.getValueType(VA.getValVT()));
2266 else if (VA.getLocInfo() == CCValAssign::BCvt)
2267 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2269 if (VA.isExtInLoc()) {
2270 // Handle MMX values passed in XMM regs.
2271 if (RegVT.isVector())
2272 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2274 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2277 assert(VA.isMemLoc());
2278 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2281 // If value is passed via pointer - do a load.
2282 if (VA.getLocInfo() == CCValAssign::Indirect)
2283 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2284 MachinePointerInfo(), false, false, false, 0);
2286 InVals.push_back(ArgValue);
2289 // The x86-64 ABIs require that for returning structs by value we copy
2290 // the sret argument into %rax/%eax (depending on ABI) for the return.
2291 // Win32 requires us to put the sret argument to %eax as well.
2292 // Save the argument into a virtual register so that we can access it
2293 // from the return points.
2294 if (MF.getFunction()->hasStructRetAttr() &&
2295 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2296 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2297 unsigned Reg = FuncInfo->getSRetReturnReg();
2299 MVT PtrTy = getPointerTy();
2300 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2301 FuncInfo->setSRetReturnReg(Reg);
2303 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2304 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2307 unsigned StackSize = CCInfo.getNextStackOffset();
2308 // Align stack specially for tail calls.
2309 if (FuncIsMadeTailCallSafe(CallConv,
2310 MF.getTarget().Options.GuaranteedTailCallOpt))
2311 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2313 // If the function takes variable number of arguments, make a frame index for
2314 // the start of the first vararg value... for expansion of llvm.va_start.
2316 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2317 CallConv != CallingConv::X86_ThisCall)) {
2318 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2321 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2323 // FIXME: We should really autogenerate these arrays
2324 static const MCPhysReg GPR64ArgRegsWin64[] = {
2325 X86::RCX, X86::RDX, X86::R8, X86::R9
2327 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2328 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2330 static const MCPhysReg XMMArgRegs64Bit[] = {
2331 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2332 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2334 const MCPhysReg *GPR64ArgRegs;
2335 unsigned NumXMMRegs = 0;
2338 // The XMM registers which might contain var arg parameters are shadowed
2339 // in their paired GPR. So we only need to save the GPR to their home
2341 TotalNumIntRegs = 4;
2342 GPR64ArgRegs = GPR64ArgRegsWin64;
2344 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2345 GPR64ArgRegs = GPR64ArgRegs64Bit;
2347 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2350 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2353 bool NoImplicitFloatOps = Fn->getAttributes().
2354 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2355 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2356 "SSE register cannot be used when SSE is disabled!");
2357 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2358 NoImplicitFloatOps) &&
2359 "SSE register cannot be used when SSE is disabled!");
2360 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2361 !Subtarget->hasSSE1())
2362 // Kernel mode asks for SSE to be disabled, so don't push them
2364 TotalNumXMMRegs = 0;
2367 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2368 // Get to the caller-allocated home save location. Add 8 to account
2369 // for the return address.
2370 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2371 FuncInfo->setRegSaveFrameIndex(
2372 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2373 // Fixup to set vararg frame on shadow area (4 x i64).
2375 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2377 // For X86-64, if there are vararg parameters that are passed via
2378 // registers, then we must store them to their spots on the stack so
2379 // they may be loaded by deferencing the result of va_next.
2380 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2381 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2382 FuncInfo->setRegSaveFrameIndex(
2383 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2387 // Store the integer parameter registers.
2388 SmallVector<SDValue, 8> MemOps;
2389 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2391 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2392 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2393 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2394 DAG.getIntPtrConstant(Offset));
2395 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2396 &X86::GR64RegClass);
2397 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2399 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2400 MachinePointerInfo::getFixedStack(
2401 FuncInfo->getRegSaveFrameIndex(), Offset),
2403 MemOps.push_back(Store);
2407 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2408 // Now store the XMM (fp + vector) parameter registers.
2409 SmallVector<SDValue, 11> SaveXMMOps;
2410 SaveXMMOps.push_back(Chain);
2412 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2413 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2414 SaveXMMOps.push_back(ALVal);
2416 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2417 FuncInfo->getRegSaveFrameIndex()));
2418 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2419 FuncInfo->getVarArgsFPOffset()));
2421 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2422 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2423 &X86::VR128RegClass);
2424 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2425 SaveXMMOps.push_back(Val);
2427 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2429 &SaveXMMOps[0], SaveXMMOps.size()));
2432 if (!MemOps.empty())
2433 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2434 &MemOps[0], MemOps.size());
2438 // Some CCs need callee pop.
2439 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2440 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2441 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2443 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2444 // If this is an sret function, the return should pop the hidden pointer.
2445 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2446 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2447 argsAreStructReturn(Ins) == StackStructReturn)
2448 FuncInfo->setBytesToPopOnReturn(4);
2452 // RegSaveFrameIndex is X86-64 only.
2453 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2454 if (CallConv == CallingConv::X86_FastCall ||
2455 CallConv == CallingConv::X86_ThisCall)
2456 // fastcc functions can't have varargs.
2457 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2460 FuncInfo->setArgumentStackSize(StackSize);
2466 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2467 SDValue StackPtr, SDValue Arg,
2468 SDLoc dl, SelectionDAG &DAG,
2469 const CCValAssign &VA,
2470 ISD::ArgFlagsTy Flags) const {
2471 unsigned LocMemOffset = VA.getLocMemOffset();
2472 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2473 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2474 if (Flags.isByVal())
2475 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2477 return DAG.getStore(Chain, dl, Arg, PtrOff,
2478 MachinePointerInfo::getStack(LocMemOffset),
2482 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2483 /// optimization is performed and it is required.
2485 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2486 SDValue &OutRetAddr, SDValue Chain,
2487 bool IsTailCall, bool Is64Bit,
2488 int FPDiff, SDLoc dl) const {
2489 // Adjust the Return address stack slot.
2490 EVT VT = getPointerTy();
2491 OutRetAddr = getReturnAddressFrameIndex(DAG);
2493 // Load the "old" Return address.
2494 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2495 false, false, false, 0);
2496 return SDValue(OutRetAddr.getNode(), 1);
2499 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2500 /// optimization is performed and it is required (FPDiff!=0).
2502 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2503 SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2504 unsigned SlotSize, int FPDiff, SDLoc dl) {
2505 // Store the return address to the appropriate stack slot.
2506 if (!FPDiff) return Chain;
2507 // Calculate the new stack slot for the return address.
2508 int NewReturnAddrFI =
2509 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2511 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2512 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2513 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2519 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2520 SmallVectorImpl<SDValue> &InVals) const {
2521 SelectionDAG &DAG = CLI.DAG;
2523 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2524 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2525 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2526 SDValue Chain = CLI.Chain;
2527 SDValue Callee = CLI.Callee;
2528 CallingConv::ID CallConv = CLI.CallConv;
2529 bool &isTailCall = CLI.IsTailCall;
2530 bool isVarArg = CLI.IsVarArg;
2532 MachineFunction &MF = DAG.getMachineFunction();
2533 bool Is64Bit = Subtarget->is64Bit();
2534 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2535 StructReturnType SR = callIsStructReturn(Outs);
2536 bool IsSibcall = false;
2538 if (MF.getTarget().Options.DisableTailCalls)
2542 // Check if it's really possible to do a tail call.
2543 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2544 isVarArg, SR != NotStructReturn,
2545 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2546 Outs, OutVals, Ins, DAG);
2548 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
2549 report_fatal_error("failed to perform tail call elimination on a call "
2550 "site marked musttail");
2552 // Sibcalls are automatically detected tailcalls which do not require
2554 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2561 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2562 "Var args not supported with calling convention fastcc, ghc or hipe");
2564 // Analyze operands of the call, assigning locations to each operand.
2565 SmallVector<CCValAssign, 16> ArgLocs;
2566 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2567 ArgLocs, *DAG.getContext());
2569 // Allocate shadow area for Win64
2571 CCInfo.AllocateStack(32, 8);
2573 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2575 // Get a count of how many bytes are to be pushed on the stack.
2576 unsigned NumBytes = CCInfo.getNextStackOffset();
2578 // This is a sibcall. The memory operands are available in caller's
2579 // own caller's stack.
2581 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2582 IsTailCallConvention(CallConv))
2583 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2586 if (isTailCall && !IsSibcall) {
2587 // Lower arguments at fp - stackoffset + fpdiff.
2588 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2589 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2591 FPDiff = NumBytesCallerPushed - NumBytes;
2593 // Set the delta of movement of the returnaddr stackslot.
2594 // But only set if delta is greater than previous delta.
2595 if (FPDiff < X86Info->getTCReturnAddrDelta())
2596 X86Info->setTCReturnAddrDelta(FPDiff);
2599 unsigned NumBytesToPush = NumBytes;
2600 unsigned NumBytesToPop = NumBytes;
2602 // If we have an inalloca argument, all stack space has already been allocated
2603 // for us and be right at the top of the stack. We don't support multiple
2604 // arguments passed in memory when using inalloca.
2605 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2607 assert(ArgLocs.back().getLocMemOffset() == 0 &&
2608 "an inalloca argument must be the only memory argument");
2612 Chain = DAG.getCALLSEQ_START(
2613 Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2615 SDValue RetAddrFrIdx;
2616 // Load return address for tail calls.
2617 if (isTailCall && FPDiff)
2618 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2619 Is64Bit, FPDiff, dl);
2621 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2622 SmallVector<SDValue, 8> MemOpChains;
2625 // Walk the register/memloc assignments, inserting copies/loads. In the case
2626 // of tail call optimization arguments are handle later.
2627 const X86RegisterInfo *RegInfo =
2628 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2629 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2630 // Skip inalloca arguments, they have already been written.
2631 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2632 if (Flags.isInAlloca())
2635 CCValAssign &VA = ArgLocs[i];
2636 EVT RegVT = VA.getLocVT();
2637 SDValue Arg = OutVals[i];
2638 bool isByVal = Flags.isByVal();
2640 // Promote the value if needed.
2641 switch (VA.getLocInfo()) {
2642 default: llvm_unreachable("Unknown loc info!");
2643 case CCValAssign::Full: break;
2644 case CCValAssign::SExt:
2645 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2647 case CCValAssign::ZExt:
2648 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2650 case CCValAssign::AExt:
2651 if (RegVT.is128BitVector()) {
2652 // Special case: passing MMX values in XMM registers.
2653 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2654 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2655 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2657 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2659 case CCValAssign::BCvt:
2660 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2662 case CCValAssign::Indirect: {
2663 // Store the argument.
2664 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2665 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2666 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2667 MachinePointerInfo::getFixedStack(FI),
2674 if (VA.isRegLoc()) {
2675 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2676 if (isVarArg && IsWin64) {
2677 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2678 // shadow reg if callee is a varargs function.
2679 unsigned ShadowReg = 0;
2680 switch (VA.getLocReg()) {
2681 case X86::XMM0: ShadowReg = X86::RCX; break;
2682 case X86::XMM1: ShadowReg = X86::RDX; break;
2683 case X86::XMM2: ShadowReg = X86::R8; break;
2684 case X86::XMM3: ShadowReg = X86::R9; break;
2687 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2689 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2690 assert(VA.isMemLoc());
2691 if (!StackPtr.getNode())
2692 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2694 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2695 dl, DAG, VA, Flags));
2699 if (!MemOpChains.empty())
2700 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2701 &MemOpChains[0], MemOpChains.size());
2703 if (Subtarget->isPICStyleGOT()) {
2704 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2707 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2708 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2710 // If we are tail calling and generating PIC/GOT style code load the
2711 // address of the callee into ECX. The value in ecx is used as target of
2712 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2713 // for tail calls on PIC/GOT architectures. Normally we would just put the
2714 // address of GOT into ebx and then call target@PLT. But for tail calls
2715 // ebx would be restored (since ebx is callee saved) before jumping to the
2718 // Note: The actual moving to ECX is done further down.
2719 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2720 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2721 !G->getGlobal()->hasProtectedVisibility())
2722 Callee = LowerGlobalAddress(Callee, DAG);
2723 else if (isa<ExternalSymbolSDNode>(Callee))
2724 Callee = LowerExternalSymbol(Callee, DAG);
2728 if (Is64Bit && isVarArg && !IsWin64) {
2729 // From AMD64 ABI document:
2730 // For calls that may call functions that use varargs or stdargs
2731 // (prototype-less calls or calls to functions containing ellipsis (...) in
2732 // the declaration) %al is used as hidden argument to specify the number
2733 // of SSE registers used. The contents of %al do not need to match exactly
2734 // the number of registers, but must be an ubound on the number of SSE
2735 // registers used and is in the range 0 - 8 inclusive.
2737 // Count the number of XMM registers allocated.
2738 static const MCPhysReg XMMArgRegs[] = {
2739 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2740 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2742 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2743 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2744 && "SSE registers cannot be used when SSE is disabled");
2746 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2747 DAG.getConstant(NumXMMRegs, MVT::i8)));
2750 // For tail calls lower the arguments to the 'real' stack slot.
2752 // Force all the incoming stack arguments to be loaded from the stack
2753 // before any new outgoing arguments are stored to the stack, because the
2754 // outgoing stack slots may alias the incoming argument stack slots, and
2755 // the alias isn't otherwise explicit. This is slightly more conservative
2756 // than necessary, because it means that each store effectively depends
2757 // on every argument instead of just those arguments it would clobber.
2758 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2760 SmallVector<SDValue, 8> MemOpChains2;
2763 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2764 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2765 CCValAssign &VA = ArgLocs[i];
2768 assert(VA.isMemLoc());
2769 SDValue Arg = OutVals[i];
2770 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2771 // Create frame index.
2772 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2773 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2774 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2775 FIN = DAG.getFrameIndex(FI, getPointerTy());
2777 if (Flags.isByVal()) {
2778 // Copy relative to framepointer.
2779 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2780 if (!StackPtr.getNode())
2781 StackPtr = DAG.getCopyFromReg(Chain, dl,
2782 RegInfo->getStackRegister(),
2784 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2786 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2790 // Store relative to framepointer.
2791 MemOpChains2.push_back(
2792 DAG.getStore(ArgChain, dl, Arg, FIN,
2793 MachinePointerInfo::getFixedStack(FI),
2799 if (!MemOpChains2.empty())
2800 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2801 &MemOpChains2[0], MemOpChains2.size());
2803 // Store the return address to the appropriate stack slot.
2804 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2805 getPointerTy(), RegInfo->getSlotSize(),
2809 // Build a sequence of copy-to-reg nodes chained together with token chain
2810 // and flag operands which copy the outgoing args into registers.
2812 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2813 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2814 RegsToPass[i].second, InFlag);
2815 InFlag = Chain.getValue(1);
2818 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2819 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2820 // In the 64-bit large code model, we have to make all calls
2821 // through a register, since the call instruction's 32-bit
2822 // pc-relative offset may not be large enough to hold the whole
2824 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2825 // If the callee is a GlobalAddress node (quite common, every direct call
2826 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2829 // We should use extra load for direct calls to dllimported functions in
2831 const GlobalValue *GV = G->getGlobal();
2832 if (!GV->hasDLLImportStorageClass()) {
2833 unsigned char OpFlags = 0;
2834 bool ExtraLoad = false;
2835 unsigned WrapperKind = ISD::DELETED_NODE;
2837 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2838 // external symbols most go through the PLT in PIC mode. If the symbol
2839 // has hidden or protected visibility, or if it is static or local, then
2840 // we don't need to use the PLT - we can directly call it.
2841 if (Subtarget->isTargetELF() &&
2842 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2843 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2844 OpFlags = X86II::MO_PLT;
2845 } else if (Subtarget->isPICStyleStubAny() &&
2846 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2847 (!Subtarget->getTargetTriple().isMacOSX() ||
2848 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2849 // PC-relative references to external symbols should go through $stub,
2850 // unless we're building with the leopard linker or later, which
2851 // automatically synthesizes these stubs.
2852 OpFlags = X86II::MO_DARWIN_STUB;
2853 } else if (Subtarget->isPICStyleRIPRel() &&
2854 isa<Function>(GV) &&
2855 cast<Function>(GV)->getAttributes().
2856 hasAttribute(AttributeSet::FunctionIndex,
2857 Attribute::NonLazyBind)) {
2858 // If the function is marked as non-lazy, generate an indirect call
2859 // which loads from the GOT directly. This avoids runtime overhead
2860 // at the cost of eager binding (and one extra byte of encoding).
2861 OpFlags = X86II::MO_GOTPCREL;
2862 WrapperKind = X86ISD::WrapperRIP;
2866 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2867 G->getOffset(), OpFlags);
2869 // Add a wrapper if needed.
2870 if (WrapperKind != ISD::DELETED_NODE)
2871 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2872 // Add extra indirection if needed.
2874 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2875 MachinePointerInfo::getGOT(),
2876 false, false, false, 0);
2878 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2879 unsigned char OpFlags = 0;
2881 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2882 // external symbols should go through the PLT.
2883 if (Subtarget->isTargetELF() &&
2884 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2885 OpFlags = X86II::MO_PLT;
2886 } else if (Subtarget->isPICStyleStubAny() &&
2887 (!Subtarget->getTargetTriple().isMacOSX() ||
2888 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2889 // PC-relative references to external symbols should go through $stub,
2890 // unless we're building with the leopard linker or later, which
2891 // automatically synthesizes these stubs.
2892 OpFlags = X86II::MO_DARWIN_STUB;
2895 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2899 // Returns a chain & a flag for retval copy to use.
2900 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2901 SmallVector<SDValue, 8> Ops;
2903 if (!IsSibcall && isTailCall) {
2904 Chain = DAG.getCALLSEQ_END(Chain,
2905 DAG.getIntPtrConstant(NumBytesToPop, true),
2906 DAG.getIntPtrConstant(0, true), InFlag, dl);
2907 InFlag = Chain.getValue(1);
2910 Ops.push_back(Chain);
2911 Ops.push_back(Callee);
2914 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2916 // Add argument registers to the end of the list so that they are known live
2918 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2919 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2920 RegsToPass[i].second.getValueType()));
2922 // Add a register mask operand representing the call-preserved registers.
2923 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2924 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2925 assert(Mask && "Missing call preserved mask for calling convention");
2926 Ops.push_back(DAG.getRegisterMask(Mask));
2928 if (InFlag.getNode())
2929 Ops.push_back(InFlag);
2933 //// If this is the first return lowered for this function, add the regs
2934 //// to the liveout set for the function.
2935 // This isn't right, although it's probably harmless on x86; liveouts
2936 // should be computed from returns not tail calls. Consider a void
2937 // function making a tail call to a function returning int.
2938 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
2941 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2942 InFlag = Chain.getValue(1);
2944 // Create the CALLSEQ_END node.
2945 unsigned NumBytesForCalleeToPop;
2946 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2947 getTargetMachine().Options.GuaranteedTailCallOpt))
2948 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
2949 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2950 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2951 SR == StackStructReturn)
2952 // If this is a call to a struct-return function, the callee
2953 // pops the hidden struct pointer, so we have to push it back.
2954 // This is common for Darwin/X86, Linux & Mingw32 targets.
2955 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2956 NumBytesForCalleeToPop = 4;
2958 NumBytesForCalleeToPop = 0; // Callee pops nothing.
2960 // Returns a flag for retval copy to use.
2962 Chain = DAG.getCALLSEQ_END(Chain,
2963 DAG.getIntPtrConstant(NumBytesToPop, true),
2964 DAG.getIntPtrConstant(NumBytesForCalleeToPop,
2967 InFlag = Chain.getValue(1);
2970 // Handle result values, copying them out of physregs into vregs that we
2972 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2973 Ins, dl, DAG, InVals);
2976 //===----------------------------------------------------------------------===//
2977 // Fast Calling Convention (tail call) implementation
2978 //===----------------------------------------------------------------------===//
2980 // Like std call, callee cleans arguments, convention except that ECX is
2981 // reserved for storing the tail called function address. Only 2 registers are
2982 // free for argument passing (inreg). Tail call optimization is performed
2984 // * tailcallopt is enabled
2985 // * caller/callee are fastcc
2986 // On X86_64 architecture with GOT-style position independent code only local
2987 // (within module) calls are supported at the moment.
2988 // To keep the stack aligned according to platform abi the function
2989 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2990 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2991 // If a tail called function callee has more arguments than the caller the
2992 // caller needs to make sure that there is room to move the RETADDR to. This is
2993 // achieved by reserving an area the size of the argument delta right after the
2994 // original REtADDR, but before the saved framepointer or the spilled registers
2995 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3007 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3008 /// for a 16 byte align requirement.
3010 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3011 SelectionDAG& DAG) const {
3012 MachineFunction &MF = DAG.getMachineFunction();
3013 const TargetMachine &TM = MF.getTarget();
3014 const X86RegisterInfo *RegInfo =
3015 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3016 const TargetFrameLowering &TFI = *TM.getFrameLowering();
3017 unsigned StackAlignment = TFI.getStackAlignment();
3018 uint64_t AlignMask = StackAlignment - 1;
3019 int64_t Offset = StackSize;
3020 unsigned SlotSize = RegInfo->getSlotSize();
3021 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3022 // Number smaller than 12 so just add the difference.
3023 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3025 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3026 Offset = ((~AlignMask) & Offset) + StackAlignment +
3027 (StackAlignment-SlotSize);
3032 /// MatchingStackOffset - Return true if the given stack call argument is
3033 /// already available in the same position (relatively) of the caller's
3034 /// incoming argument stack.
3036 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3037 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3038 const X86InstrInfo *TII) {
3039 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3041 if (Arg.getOpcode() == ISD::CopyFromReg) {
3042 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3043 if (!TargetRegisterInfo::isVirtualRegister(VR))
3045 MachineInstr *Def = MRI->getVRegDef(VR);
3048 if (!Flags.isByVal()) {
3049 if (!TII->isLoadFromStackSlot(Def, FI))
3052 unsigned Opcode = Def->getOpcode();
3053 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3054 Def->getOperand(1).isFI()) {
3055 FI = Def->getOperand(1).getIndex();
3056 Bytes = Flags.getByValSize();
3060 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3061 if (Flags.isByVal())
3062 // ByVal argument is passed in as a pointer but it's now being
3063 // dereferenced. e.g.
3064 // define @foo(%struct.X* %A) {
3065 // tail call @bar(%struct.X* byval %A)
3068 SDValue Ptr = Ld->getBasePtr();
3069 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3072 FI = FINode->getIndex();
3073 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3074 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3075 FI = FINode->getIndex();
3076 Bytes = Flags.getByValSize();
3080 assert(FI != INT_MAX);
3081 if (!MFI->isFixedObjectIndex(FI))
3083 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3086 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3087 /// for tail call optimization. Targets which want to do tail call
3088 /// optimization should implement this function.
3090 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3091 CallingConv::ID CalleeCC,
3093 bool isCalleeStructRet,
3094 bool isCallerStructRet,
3096 const SmallVectorImpl<ISD::OutputArg> &Outs,
3097 const SmallVectorImpl<SDValue> &OutVals,
3098 const SmallVectorImpl<ISD::InputArg> &Ins,
3099 SelectionDAG &DAG) const {
3100 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3103 // If -tailcallopt is specified, make fastcc functions tail-callable.
3104 const MachineFunction &MF = DAG.getMachineFunction();
3105 const Function *CallerF = MF.getFunction();
3107 // If the function return type is x86_fp80 and the callee return type is not,
3108 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3109 // perform a tailcall optimization here.
3110 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3113 CallingConv::ID CallerCC = CallerF->getCallingConv();
3114 bool CCMatch = CallerCC == CalleeCC;
3115 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3116 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3118 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3119 if (IsTailCallConvention(CalleeCC) && CCMatch)
3124 // Look for obvious safe cases to perform tail call optimization that do not
3125 // require ABI changes. This is what gcc calls sibcall.
3127 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3128 // emit a special epilogue.
3129 const X86RegisterInfo *RegInfo =
3130 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3131 if (RegInfo->needsStackRealignment(MF))
3134 // Also avoid sibcall optimization if either caller or callee uses struct
3135 // return semantics.
3136 if (isCalleeStructRet || isCallerStructRet)
3139 // An stdcall/thiscall caller is expected to clean up its arguments; the
3140 // callee isn't going to do that.
3141 // FIXME: this is more restrictive than needed. We could produce a tailcall
3142 // when the stack adjustment matches. For example, with a thiscall that takes
3143 // only one argument.
3144 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3145 CallerCC == CallingConv::X86_ThisCall))
3148 // Do not sibcall optimize vararg calls unless all arguments are passed via
3150 if (isVarArg && !Outs.empty()) {
3152 // Optimizing for varargs on Win64 is unlikely to be safe without
3153 // additional testing.
3154 if (IsCalleeWin64 || IsCallerWin64)
3157 SmallVector<CCValAssign, 16> ArgLocs;
3158 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3159 getTargetMachine(), ArgLocs, *DAG.getContext());
3161 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3162 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3163 if (!ArgLocs[i].isRegLoc())
3167 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3168 // stack. Therefore, if it's not used by the call it is not safe to optimize
3169 // this into a sibcall.
3170 bool Unused = false;
3171 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3178 SmallVector<CCValAssign, 16> RVLocs;
3179 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3180 getTargetMachine(), RVLocs, *DAG.getContext());
3181 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3182 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3183 CCValAssign &VA = RVLocs[i];
3184 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3189 // If the calling conventions do not match, then we'd better make sure the
3190 // results are returned in the same way as what the caller expects.
3192 SmallVector<CCValAssign, 16> RVLocs1;
3193 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3194 getTargetMachine(), RVLocs1, *DAG.getContext());
3195 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3197 SmallVector<CCValAssign, 16> RVLocs2;
3198 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3199 getTargetMachine(), RVLocs2, *DAG.getContext());
3200 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3202 if (RVLocs1.size() != RVLocs2.size())
3204 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3205 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3207 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3209 if (RVLocs1[i].isRegLoc()) {
3210 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3213 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3219 // If the callee takes no arguments then go on to check the results of the
3221 if (!Outs.empty()) {
3222 // Check if stack adjustment is needed. For now, do not do this if any
3223 // argument is passed on the stack.
3224 SmallVector<CCValAssign, 16> ArgLocs;
3225 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3226 getTargetMachine(), ArgLocs, *DAG.getContext());
3228 // Allocate shadow area for Win64
3230 CCInfo.AllocateStack(32, 8);
3232 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3233 if (CCInfo.getNextStackOffset()) {
3234 MachineFunction &MF = DAG.getMachineFunction();
3235 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3238 // Check if the arguments are already laid out in the right way as
3239 // the caller's fixed stack objects.
3240 MachineFrameInfo *MFI = MF.getFrameInfo();
3241 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3242 const X86InstrInfo *TII =
3243 ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3244 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3245 CCValAssign &VA = ArgLocs[i];
3246 SDValue Arg = OutVals[i];
3247 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3248 if (VA.getLocInfo() == CCValAssign::Indirect)
3250 if (!VA.isRegLoc()) {
3251 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3258 // If the tailcall address may be in a register, then make sure it's
3259 // possible to register allocate for it. In 32-bit, the call address can
3260 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3261 // callee-saved registers are restored. These happen to be the same
3262 // registers used to pass 'inreg' arguments so watch out for those.
3263 if (!Subtarget->is64Bit() &&
3264 ((!isa<GlobalAddressSDNode>(Callee) &&
3265 !isa<ExternalSymbolSDNode>(Callee)) ||
3266 getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3267 unsigned NumInRegs = 0;
3268 // In PIC we need an extra register to formulate the address computation
3270 unsigned MaxInRegs =
3271 (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3273 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3274 CCValAssign &VA = ArgLocs[i];
3277 unsigned Reg = VA.getLocReg();
3280 case X86::EAX: case X86::EDX: case X86::ECX:
3281 if (++NumInRegs == MaxInRegs)
3293 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3294 const TargetLibraryInfo *libInfo) const {
3295 return X86::createFastISel(funcInfo, libInfo);
3298 //===----------------------------------------------------------------------===//
3299 // Other Lowering Hooks
3300 //===----------------------------------------------------------------------===//
3302 static bool MayFoldLoad(SDValue Op) {
3303 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3306 static bool MayFoldIntoStore(SDValue Op) {
3307 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3310 static bool isTargetShuffle(unsigned Opcode) {
3312 default: return false;
3313 case X86ISD::PSHUFD:
3314 case X86ISD::PSHUFHW:
3315 case X86ISD::PSHUFLW:
3317 case X86ISD::PALIGNR:
3318 case X86ISD::MOVLHPS:
3319 case X86ISD::MOVLHPD:
3320 case X86ISD::MOVHLPS:
3321 case X86ISD::MOVLPS:
3322 case X86ISD::MOVLPD:
3323 case X86ISD::MOVSHDUP:
3324 case X86ISD::MOVSLDUP:
3325 case X86ISD::MOVDDUP:
3328 case X86ISD::UNPCKL:
3329 case X86ISD::UNPCKH:
3330 case X86ISD::VPERMILP:
3331 case X86ISD::VPERM2X128:
3332 case X86ISD::VPERMI:
3337 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3338 SDValue V1, SelectionDAG &DAG) {
3340 default: llvm_unreachable("Unknown x86 shuffle node");
3341 case X86ISD::MOVSHDUP:
3342 case X86ISD::MOVSLDUP:
3343 case X86ISD::MOVDDUP:
3344 return DAG.getNode(Opc, dl, VT, V1);
3348 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3349 SDValue V1, unsigned TargetMask,
3350 SelectionDAG &DAG) {
3352 default: llvm_unreachable("Unknown x86 shuffle node");
3353 case X86ISD::PSHUFD:
3354 case X86ISD::PSHUFHW:
3355 case X86ISD::PSHUFLW:
3356 case X86ISD::VPERMILP:
3357 case X86ISD::VPERMI:
3358 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3362 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3363 SDValue V1, SDValue V2, unsigned TargetMask,
3364 SelectionDAG &DAG) {
3366 default: llvm_unreachable("Unknown x86 shuffle node");
3367 case X86ISD::PALIGNR:
3369 case X86ISD::VPERM2X128:
3370 return DAG.getNode(Opc, dl, VT, V1, V2,
3371 DAG.getConstant(TargetMask, MVT::i8));
3375 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3376 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3378 default: llvm_unreachable("Unknown x86 shuffle node");
3379 case X86ISD::MOVLHPS:
3380 case X86ISD::MOVLHPD:
3381 case X86ISD::MOVHLPS:
3382 case X86ISD::MOVLPS:
3383 case X86ISD::MOVLPD:
3386 case X86ISD::UNPCKL:
3387 case X86ISD::UNPCKH:
3388 return DAG.getNode(Opc, dl, VT, V1, V2);
3392 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3393 MachineFunction &MF = DAG.getMachineFunction();
3394 const X86RegisterInfo *RegInfo =
3395 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3396 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3397 int ReturnAddrIndex = FuncInfo->getRAIndex();
3399 if (ReturnAddrIndex == 0) {
3400 // Set up a frame object for the return address.
3401 unsigned SlotSize = RegInfo->getSlotSize();
3402 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3405 FuncInfo->setRAIndex(ReturnAddrIndex);
3408 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3411 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3412 bool hasSymbolicDisplacement) {
3413 // Offset should fit into 32 bit immediate field.
3414 if (!isInt<32>(Offset))
3417 // If we don't have a symbolic displacement - we don't have any extra
3419 if (!hasSymbolicDisplacement)
3422 // FIXME: Some tweaks might be needed for medium code model.
3423 if (M != CodeModel::Small && M != CodeModel::Kernel)
3426 // For small code model we assume that latest object is 16MB before end of 31
3427 // bits boundary. We may also accept pretty large negative constants knowing
3428 // that all objects are in the positive half of address space.
3429 if (M == CodeModel::Small && Offset < 16*1024*1024)
3432 // For kernel code model we know that all object resist in the negative half
3433 // of 32bits address space. We may not accept negative offsets, since they may
3434 // be just off and we may accept pretty large positive ones.
3435 if (M == CodeModel::Kernel && Offset > 0)
3441 /// isCalleePop - Determines whether the callee is required to pop its
3442 /// own arguments. Callee pop is necessary to support tail calls.
3443 bool X86::isCalleePop(CallingConv::ID CallingConv,
3444 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3448 switch (CallingConv) {
3451 case CallingConv::X86_StdCall:
3453 case CallingConv::X86_FastCall:
3455 case CallingConv::X86_ThisCall:
3457 case CallingConv::Fast:
3459 case CallingConv::GHC:
3461 case CallingConv::HiPE:
3466 /// \brief Return true if the condition is an unsigned comparison operation.
3467 static bool isX86CCUnsigned(unsigned X86CC) {
3469 default: llvm_unreachable("Invalid integer condition!");
3470 case X86::COND_E: return true;
3471 case X86::COND_G: return false;
3472 case X86::COND_GE: return false;
3473 case X86::COND_L: return false;
3474 case X86::COND_LE: return false;
3475 case X86::COND_NE: return true;
3476 case X86::COND_B: return true;
3477 case X86::COND_A: return true;
3478 case X86::COND_BE: return true;
3479 case X86::COND_AE: return true;
3481 llvm_unreachable("covered switch fell through?!");
3484 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3485 /// specific condition code, returning the condition code and the LHS/RHS of the
3486 /// comparison to make.
3487 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3488 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3490 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3491 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3492 // X > -1 -> X == 0, jump !sign.
3493 RHS = DAG.getConstant(0, RHS.getValueType());
3494 return X86::COND_NS;
3496 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3497 // X < 0 -> X == 0, jump on sign.
3500 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3502 RHS = DAG.getConstant(0, RHS.getValueType());
3503 return X86::COND_LE;
3507 switch (SetCCOpcode) {
3508 default: llvm_unreachable("Invalid integer condition!");
3509 case ISD::SETEQ: return X86::COND_E;
3510 case ISD::SETGT: return X86::COND_G;
3511 case ISD::SETGE: return X86::COND_GE;
3512 case ISD::SETLT: return X86::COND_L;
3513 case ISD::SETLE: return X86::COND_LE;
3514 case ISD::SETNE: return X86::COND_NE;
3515 case ISD::SETULT: return X86::COND_B;
3516 case ISD::SETUGT: return X86::COND_A;
3517 case ISD::SETULE: return X86::COND_BE;
3518 case ISD::SETUGE: return X86::COND_AE;
3522 // First determine if it is required or is profitable to flip the operands.
3524 // If LHS is a foldable load, but RHS is not, flip the condition.
3525 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3526 !ISD::isNON_EXTLoad(RHS.getNode())) {
3527 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3528 std::swap(LHS, RHS);
3531 switch (SetCCOpcode) {
3537 std::swap(LHS, RHS);
3541 // On a floating point condition, the flags are set as follows:
3543 // 0 | 0 | 0 | X > Y
3544 // 0 | 0 | 1 | X < Y
3545 // 1 | 0 | 0 | X == Y
3546 // 1 | 1 | 1 | unordered
3547 switch (SetCCOpcode) {
3548 default: llvm_unreachable("Condcode should be pre-legalized away");
3550 case ISD::SETEQ: return X86::COND_E;
3551 case ISD::SETOLT: // flipped
3553 case ISD::SETGT: return X86::COND_A;
3554 case ISD::SETOLE: // flipped
3556 case ISD::SETGE: return X86::COND_AE;
3557 case ISD::SETUGT: // flipped
3559 case ISD::SETLT: return X86::COND_B;
3560 case ISD::SETUGE: // flipped
3562 case ISD::SETLE: return X86::COND_BE;
3564 case ISD::SETNE: return X86::COND_NE;
3565 case ISD::SETUO: return X86::COND_P;
3566 case ISD::SETO: return X86::COND_NP;
3568 case ISD::SETUNE: return X86::COND_INVALID;
3572 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3573 /// code. Current x86 isa includes the following FP cmov instructions:
3574 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3575 static bool hasFPCMov(unsigned X86CC) {
3591 /// isFPImmLegal - Returns true if the target can instruction select the
3592 /// specified FP immediate natively. If false, the legalizer will
3593 /// materialize the FP immediate as a load from a constant pool.
3594 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3595 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3596 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3602 /// \brief Returns true if it is beneficial to convert a load of a constant
3603 /// to just the constant itself.
3604 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3606 assert(Ty->isIntegerTy());
3608 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3609 if (BitSize == 0 || BitSize > 64)
3614 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3615 /// the specified range (L, H].
3616 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3617 return (Val < 0) || (Val >= Low && Val < Hi);
3620 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3621 /// specified value.
3622 static bool isUndefOrEqual(int Val, int CmpVal) {
3623 return (Val < 0 || Val == CmpVal);
3626 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3627 /// from position Pos and ending in Pos+Size, falls within the specified
3628 /// sequential range (L, L+Pos]. or is undef.
3629 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3630 unsigned Pos, unsigned Size, int Low) {
3631 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3632 if (!isUndefOrEqual(Mask[i], Low))
3637 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3638 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3639 /// the second operand.
3640 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3641 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3642 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3643 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3644 return (Mask[0] < 2 && Mask[1] < 2);
3648 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3649 /// is suitable for input to PSHUFHW.
3650 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3651 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3654 // Lower quadword copied in order or undef.
3655 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3658 // Upper quadword shuffled.
3659 for (unsigned i = 4; i != 8; ++i)
3660 if (!isUndefOrInRange(Mask[i], 4, 8))
3663 if (VT == MVT::v16i16) {
3664 // Lower quadword copied in order or undef.
3665 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3668 // Upper quadword shuffled.
3669 for (unsigned i = 12; i != 16; ++i)
3670 if (!isUndefOrInRange(Mask[i], 12, 16))
3677 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3678 /// is suitable for input to PSHUFLW.
3679 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3680 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3683 // Upper quadword copied in order.
3684 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3687 // Lower quadword shuffled.
3688 for (unsigned i = 0; i != 4; ++i)
3689 if (!isUndefOrInRange(Mask[i], 0, 4))
3692 if (VT == MVT::v16i16) {
3693 // Upper quadword copied in order.
3694 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3697 // Lower quadword shuffled.
3698 for (unsigned i = 8; i != 12; ++i)
3699 if (!isUndefOrInRange(Mask[i], 8, 12))
3706 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3707 /// is suitable for input to PALIGNR.
3708 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3709 const X86Subtarget *Subtarget) {
3710 if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3711 (VT.is256BitVector() && !Subtarget->hasInt256()))
3714 unsigned NumElts = VT.getVectorNumElements();
3715 unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3716 unsigned NumLaneElts = NumElts/NumLanes;
3718 // Do not handle 64-bit element shuffles with palignr.
3719 if (NumLaneElts == 2)
3722 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3724 for (i = 0; i != NumLaneElts; ++i) {
3729 // Lane is all undef, go to next lane
3730 if (i == NumLaneElts)
3733 int Start = Mask[i+l];
3735 // Make sure its in this lane in one of the sources
3736 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3737 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3740 // If not lane 0, then we must match lane 0
3741 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3744 // Correct second source to be contiguous with first source
3745 if (Start >= (int)NumElts)
3746 Start -= NumElts - NumLaneElts;
3748 // Make sure we're shifting in the right direction.
3749 if (Start <= (int)(i+l))
3754 // Check the rest of the elements to see if they are consecutive.
3755 for (++i; i != NumLaneElts; ++i) {
3756 int Idx = Mask[i+l];
3758 // Make sure its in this lane
3759 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3760 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3763 // If not lane 0, then we must match lane 0
3764 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3767 if (Idx >= (int)NumElts)
3768 Idx -= NumElts - NumLaneElts;
3770 if (!isUndefOrEqual(Idx, Start+i))
3779 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3780 /// the two vector operands have swapped position.
3781 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3782 unsigned NumElems) {
3783 for (unsigned i = 0; i != NumElems; ++i) {
3787 else if (idx < (int)NumElems)
3788 Mask[i] = idx + NumElems;
3790 Mask[i] = idx - NumElems;
3794 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3795 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3796 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3797 /// reverse of what x86 shuffles want.
3798 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3800 unsigned NumElems = VT.getVectorNumElements();
3801 unsigned NumLanes = VT.getSizeInBits()/128;
3802 unsigned NumLaneElems = NumElems/NumLanes;
3804 if (NumLaneElems != 2 && NumLaneElems != 4)
3807 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3808 bool symetricMaskRequired =
3809 (VT.getSizeInBits() >= 256) && (EltSize == 32);
3811 // VSHUFPSY divides the resulting vector into 4 chunks.
3812 // The sources are also splitted into 4 chunks, and each destination
3813 // chunk must come from a different source chunk.
3815 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3816 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3818 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3819 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3821 // VSHUFPDY divides the resulting vector into 4 chunks.
3822 // The sources are also splitted into 4 chunks, and each destination
3823 // chunk must come from a different source chunk.
3825 // SRC1 => X3 X2 X1 X0
3826 // SRC2 => Y3 Y2 Y1 Y0
3828 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3830 SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3831 unsigned HalfLaneElems = NumLaneElems/2;
3832 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3833 for (unsigned i = 0; i != NumLaneElems; ++i) {
3834 int Idx = Mask[i+l];
3835 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3836 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3838 // For VSHUFPSY, the mask of the second half must be the same as the
3839 // first but with the appropriate offsets. This works in the same way as
3840 // VPERMILPS works with masks.
3841 if (!symetricMaskRequired || Idx < 0)
3843 if (MaskVal[i] < 0) {
3844 MaskVal[i] = Idx - l;
3847 if ((signed)(Idx - l) != MaskVal[i])
3855 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3856 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3857 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3858 if (!VT.is128BitVector())
3861 unsigned NumElems = VT.getVectorNumElements();
3866 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3867 return isUndefOrEqual(Mask[0], 6) &&
3868 isUndefOrEqual(Mask[1], 7) &&
3869 isUndefOrEqual(Mask[2], 2) &&
3870 isUndefOrEqual(Mask[3], 3);
3873 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3874 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3876 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3877 if (!VT.is128BitVector())
3880 unsigned NumElems = VT.getVectorNumElements();
3885 return isUndefOrEqual(Mask[0], 2) &&
3886 isUndefOrEqual(Mask[1], 3) &&
3887 isUndefOrEqual(Mask[2], 2) &&
3888 isUndefOrEqual(Mask[3], 3);
3891 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3892 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3893 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3894 if (!VT.is128BitVector())
3897 unsigned NumElems = VT.getVectorNumElements();
3899 if (NumElems != 2 && NumElems != 4)
3902 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3903 if (!isUndefOrEqual(Mask[i], i + NumElems))
3906 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3907 if (!isUndefOrEqual(Mask[i], i))
3913 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3914 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3915 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3916 if (!VT.is128BitVector())
3919 unsigned NumElems = VT.getVectorNumElements();
3921 if (NumElems != 2 && NumElems != 4)
3924 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3925 if (!isUndefOrEqual(Mask[i], i))
3928 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3929 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3935 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
3936 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
3937 /// i. e: If all but one element come from the same vector.
3938 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
3939 // TODO: Deal with AVX's VINSERTPS
3940 if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
3943 unsigned CorrectPosV1 = 0;
3944 unsigned CorrectPosV2 = 0;
3945 for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i)
3948 else if (Mask[i] == i + 4)
3951 if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
3952 // We have 3 elements from one vector, and one from another.
3959 // Some special combinations that can be optimized.
3962 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3963 SelectionDAG &DAG) {
3964 MVT VT = SVOp->getSimpleValueType(0);
3967 if (VT != MVT::v8i32 && VT != MVT::v8f32)
3970 ArrayRef<int> Mask = SVOp->getMask();
3972 // These are the special masks that may be optimized.
3973 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3974 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
3975 bool MatchEvenMask = true;
3976 bool MatchOddMask = true;
3977 for (int i=0; i<8; ++i) {
3978 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3979 MatchEvenMask = false;
3980 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3981 MatchOddMask = false;
3984 if (!MatchEvenMask && !MatchOddMask)
3987 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3989 SDValue Op0 = SVOp->getOperand(0);
3990 SDValue Op1 = SVOp->getOperand(1);
3992 if (MatchEvenMask) {
3993 // Shift the second operand right to 32 bits.
3994 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3995 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3997 // Shift the first operand left to 32 bits.
3998 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3999 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4001 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4002 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4005 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4006 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4007 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4008 bool HasInt256, bool V2IsSplat = false) {
4010 assert(VT.getSizeInBits() >= 128 &&
4011 "Unsupported vector type for unpckl");
4013 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4015 unsigned NumOf256BitLanes;
4016 unsigned NumElts = VT.getVectorNumElements();
4017 if (VT.is256BitVector()) {
4018 if (NumElts != 4 && NumElts != 8 &&
4019 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4022 NumOf256BitLanes = 1;
4023 } else if (VT.is512BitVector()) {
4024 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4025 "Unsupported vector type for unpckh");
4027 NumOf256BitLanes = 2;
4030 NumOf256BitLanes = 1;
4033 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4034 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4036 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4037 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4038 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4039 int BitI = Mask[l256*NumEltsInStride+l+i];
4040 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4041 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4043 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4045 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4053 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4054 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4055 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4056 bool HasInt256, bool V2IsSplat = false) {
4057 assert(VT.getSizeInBits() >= 128 &&
4058 "Unsupported vector type for unpckh");
4060 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4062 unsigned NumOf256BitLanes;
4063 unsigned NumElts = VT.getVectorNumElements();
4064 if (VT.is256BitVector()) {
4065 if (NumElts != 4 && NumElts != 8 &&
4066 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4069 NumOf256BitLanes = 1;
4070 } else if (VT.is512BitVector()) {
4071 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4072 "Unsupported vector type for unpckh");
4074 NumOf256BitLanes = 2;
4077 NumOf256BitLanes = 1;
4080 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4081 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4083 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4084 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4085 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4086 int BitI = Mask[l256*NumEltsInStride+l+i];
4087 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4088 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4090 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4092 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4100 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4101 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4103 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4104 unsigned NumElts = VT.getVectorNumElements();
4105 bool Is256BitVec = VT.is256BitVector();
4107 if (VT.is512BitVector())
4109 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4110 "Unsupported vector type for unpckh");
4112 if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4113 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4116 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4117 // FIXME: Need a better way to get rid of this, there's no latency difference
4118 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4119 // the former later. We should also remove the "_undef" special mask.
4120 if (NumElts == 4 && Is256BitVec)
4123 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4124 // independently on 128-bit lanes.
4125 unsigned NumLanes = VT.getSizeInBits()/128;
4126 unsigned NumLaneElts = NumElts/NumLanes;
4128 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4129 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4130 int BitI = Mask[l+i];
4131 int BitI1 = Mask[l+i+1];
4133 if (!isUndefOrEqual(BitI, j))
4135 if (!isUndefOrEqual(BitI1, j))
4143 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4144 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4146 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4147 unsigned NumElts = VT.getVectorNumElements();
4149 if (VT.is512BitVector())
4152 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4153 "Unsupported vector type for unpckh");
4155 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4156 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4159 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4160 // independently on 128-bit lanes.
4161 unsigned NumLanes = VT.getSizeInBits()/128;
4162 unsigned NumLaneElts = NumElts/NumLanes;
4164 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4165 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4166 int BitI = Mask[l+i];
4167 int BitI1 = Mask[l+i+1];
4168 if (!isUndefOrEqual(BitI, j))
4170 if (!isUndefOrEqual(BitI1, j))
4177 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4178 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4179 /// MOVSD, and MOVD, i.e. setting the lowest element.
4180 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4181 if (VT.getVectorElementType().getSizeInBits() < 32)
4183 if (!VT.is128BitVector())
4186 unsigned NumElts = VT.getVectorNumElements();
4188 if (!isUndefOrEqual(Mask[0], NumElts))
4191 for (unsigned i = 1; i != NumElts; ++i)
4192 if (!isUndefOrEqual(Mask[i], i))
4198 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4199 /// as permutations between 128-bit chunks or halves. As an example: this
4201 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4202 /// The first half comes from the second half of V1 and the second half from the
4203 /// the second half of V2.
4204 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4205 if (!HasFp256 || !VT.is256BitVector())
4208 // The shuffle result is divided into half A and half B. In total the two
4209 // sources have 4 halves, namely: C, D, E, F. The final values of A and
4210 // B must come from C, D, E or F.
4211 unsigned HalfSize = VT.getVectorNumElements()/2;
4212 bool MatchA = false, MatchB = false;
4214 // Check if A comes from one of C, D, E, F.
4215 for (unsigned Half = 0; Half != 4; ++Half) {
4216 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4222 // Check if B comes from one of C, D, E, F.
4223 for (unsigned Half = 0; Half != 4; ++Half) {
4224 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4230 return MatchA && MatchB;
4233 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4234 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4235 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4236 MVT VT = SVOp->getSimpleValueType(0);
4238 unsigned HalfSize = VT.getVectorNumElements()/2;
4240 unsigned FstHalf = 0, SndHalf = 0;
4241 for (unsigned i = 0; i < HalfSize; ++i) {
4242 if (SVOp->getMaskElt(i) > 0) {
4243 FstHalf = SVOp->getMaskElt(i)/HalfSize;
4247 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4248 if (SVOp->getMaskElt(i) > 0) {
4249 SndHalf = SVOp->getMaskElt(i)/HalfSize;
4254 return (FstHalf | (SndHalf << 4));
4257 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4258 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4259 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4263 unsigned NumElts = VT.getVectorNumElements();
4265 if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4266 for (unsigned i = 0; i != NumElts; ++i) {
4269 Imm8 |= Mask[i] << (i*2);
4274 unsigned LaneSize = 4;
4275 SmallVector<int, 4> MaskVal(LaneSize, -1);
4277 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4278 for (unsigned i = 0; i != LaneSize; ++i) {
4279 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4283 if (MaskVal[i] < 0) {
4284 MaskVal[i] = Mask[i+l] - l;
4285 Imm8 |= MaskVal[i] << (i*2);
4288 if (Mask[i+l] != (signed)(MaskVal[i]+l))
4295 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4296 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4297 /// Note that VPERMIL mask matching is different depending whether theunderlying
4298 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4299 /// to the same elements of the low, but to the higher half of the source.
4300 /// In VPERMILPD the two lanes could be shuffled independently of each other
4301 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4302 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4303 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4304 if (VT.getSizeInBits() < 256 || EltSize < 32)
4306 bool symetricMaskRequired = (EltSize == 32);
4307 unsigned NumElts = VT.getVectorNumElements();
4309 unsigned NumLanes = VT.getSizeInBits()/128;
4310 unsigned LaneSize = NumElts/NumLanes;
4311 // 2 or 4 elements in one lane
4313 SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4314 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4315 for (unsigned i = 0; i != LaneSize; ++i) {
4316 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4318 if (symetricMaskRequired) {
4319 if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4320 ExpectedMaskVal[i] = Mask[i+l] - l;
4323 if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4331 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4332 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
4333 /// element of vector 2 and the other elements to come from vector 1 in order.
4334 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4335 bool V2IsSplat = false, bool V2IsUndef = false) {
4336 if (!VT.is128BitVector())
4339 unsigned NumOps = VT.getVectorNumElements();
4340 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4343 if (!isUndefOrEqual(Mask[0], 0))
4346 for (unsigned i = 1; i != NumOps; ++i)
4347 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4348 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4349 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4355 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4356 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4357 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4358 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4359 const X86Subtarget *Subtarget) {
4360 if (!Subtarget->hasSSE3())
4363 unsigned NumElems = VT.getVectorNumElements();
4365 if ((VT.is128BitVector() && NumElems != 4) ||
4366 (VT.is256BitVector() && NumElems != 8) ||
4367 (VT.is512BitVector() && NumElems != 16))
4370 // "i+1" is the value the indexed mask element must have
4371 for (unsigned i = 0; i != NumElems; i += 2)
4372 if (!isUndefOrEqual(Mask[i], i+1) ||
4373 !isUndefOrEqual(Mask[i+1], i+1))
4379 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4380 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4381 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4382 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4383 const X86Subtarget *Subtarget) {
4384 if (!Subtarget->hasSSE3())
4387 unsigned NumElems = VT.getVectorNumElements();
4389 if ((VT.is128BitVector() && NumElems != 4) ||
4390 (VT.is256BitVector() && NumElems != 8) ||
4391 (VT.is512BitVector() && NumElems != 16))
4394 // "i" is the value the indexed mask element must have
4395 for (unsigned i = 0; i != NumElems; i += 2)
4396 if (!isUndefOrEqual(Mask[i], i) ||
4397 !isUndefOrEqual(Mask[i+1], i))
4403 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4404 /// specifies a shuffle of elements that is suitable for input to 256-bit
4405 /// version of MOVDDUP.
4406 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4407 if (!HasFp256 || !VT.is256BitVector())
4410 unsigned NumElts = VT.getVectorNumElements();
4414 for (unsigned i = 0; i != NumElts/2; ++i)
4415 if (!isUndefOrEqual(Mask[i], 0))
4417 for (unsigned i = NumElts/2; i != NumElts; ++i)
4418 if (!isUndefOrEqual(Mask[i], NumElts/2))
4423 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4424 /// specifies a shuffle of elements that is suitable for input to 128-bit
4425 /// version of MOVDDUP.
4426 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4427 if (!VT.is128BitVector())
4430 unsigned e = VT.getVectorNumElements() / 2;
4431 for (unsigned i = 0; i != e; ++i)
4432 if (!isUndefOrEqual(Mask[i], i))
4434 for (unsigned i = 0; i != e; ++i)
4435 if (!isUndefOrEqual(Mask[e+i], i))
4440 /// isVEXTRACTIndex - Return true if the specified
4441 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4442 /// suitable for instruction that extract 128 or 256 bit vectors
4443 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4444 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4445 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4448 // The index should be aligned on a vecWidth-bit boundary.
4450 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4452 MVT VT = N->getSimpleValueType(0);
4453 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4454 bool Result = (Index * ElSize) % vecWidth == 0;
4459 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4460 /// operand specifies a subvector insert that is suitable for input to
4461 /// insertion of 128 or 256-bit subvectors
4462 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4463 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4464 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4466 // The index should be aligned on a vecWidth-bit boundary.
4468 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4470 MVT VT = N->getSimpleValueType(0);
4471 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4472 bool Result = (Index * ElSize) % vecWidth == 0;
4477 bool X86::isVINSERT128Index(SDNode *N) {
4478 return isVINSERTIndex(N, 128);
4481 bool X86::isVINSERT256Index(SDNode *N) {
4482 return isVINSERTIndex(N, 256);
4485 bool X86::isVEXTRACT128Index(SDNode *N) {
4486 return isVEXTRACTIndex(N, 128);
4489 bool X86::isVEXTRACT256Index(SDNode *N) {
4490 return isVEXTRACTIndex(N, 256);
4493 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4494 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4495 /// Handles 128-bit and 256-bit.
4496 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4497 MVT VT = N->getSimpleValueType(0);
4499 assert((VT.getSizeInBits() >= 128) &&
4500 "Unsupported vector type for PSHUF/SHUFP");
4502 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4503 // independently on 128-bit lanes.
4504 unsigned NumElts = VT.getVectorNumElements();
4505 unsigned NumLanes = VT.getSizeInBits()/128;
4506 unsigned NumLaneElts = NumElts/NumLanes;
4508 assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4509 "Only supports 2, 4 or 8 elements per lane");
4511 unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4513 for (unsigned i = 0; i != NumElts; ++i) {
4514 int Elt = N->getMaskElt(i);
4515 if (Elt < 0) continue;
4516 Elt &= NumLaneElts - 1;
4517 unsigned ShAmt = (i << Shift) % 8;
4518 Mask |= Elt << ShAmt;
4524 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4525 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4526 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4527 MVT VT = N->getSimpleValueType(0);
4529 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4530 "Unsupported vector type for PSHUFHW");
4532 unsigned NumElts = VT.getVectorNumElements();
4535 for (unsigned l = 0; l != NumElts; l += 8) {
4536 // 8 nodes per lane, but we only care about the last 4.
4537 for (unsigned i = 0; i < 4; ++i) {
4538 int Elt = N->getMaskElt(l+i+4);
4539 if (Elt < 0) continue;
4540 Elt &= 0x3; // only 2-bits.
4541 Mask |= Elt << (i * 2);
4548 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4549 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4550 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4551 MVT VT = N->getSimpleValueType(0);
4553 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4554 "Unsupported vector type for PSHUFHW");
4556 unsigned NumElts = VT.getVectorNumElements();
4559 for (unsigned l = 0; l != NumElts; l += 8) {
4560 // 8 nodes per lane, but we only care about the first 4.
4561 for (unsigned i = 0; i < 4; ++i) {
4562 int Elt = N->getMaskElt(l+i);
4563 if (Elt < 0) continue;
4564 Elt &= 0x3; // only 2-bits
4565 Mask |= Elt << (i * 2);
4572 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4573 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4574 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4575 MVT VT = SVOp->getSimpleValueType(0);
4576 unsigned EltSize = VT.is512BitVector() ? 1 :
4577 VT.getVectorElementType().getSizeInBits() >> 3;
4579 unsigned NumElts = VT.getVectorNumElements();
4580 unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4581 unsigned NumLaneElts = NumElts/NumLanes;
4585 for (i = 0; i != NumElts; ++i) {
4586 Val = SVOp->getMaskElt(i);
4590 if (Val >= (int)NumElts)
4591 Val -= NumElts - NumLaneElts;
4593 assert(Val - i > 0 && "PALIGNR imm should be positive");
4594 return (Val - i) * EltSize;
4597 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4598 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4599 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4600 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4603 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4605 MVT VecVT = N->getOperand(0).getSimpleValueType();
4606 MVT ElVT = VecVT.getVectorElementType();
4608 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4609 return Index / NumElemsPerChunk;
4612 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4613 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4614 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4615 llvm_unreachable("Illegal insert subvector for VINSERT");
4618 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4620 MVT VecVT = N->getSimpleValueType(0);
4621 MVT ElVT = VecVT.getVectorElementType();
4623 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4624 return Index / NumElemsPerChunk;
4627 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4628 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4629 /// and VINSERTI128 instructions.
4630 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4631 return getExtractVEXTRACTImmediate(N, 128);
4634 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4635 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4636 /// and VINSERTI64x4 instructions.
4637 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4638 return getExtractVEXTRACTImmediate(N, 256);
4641 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4642 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4643 /// and VINSERTI128 instructions.
4644 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4645 return getInsertVINSERTImmediate(N, 128);
4648 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4649 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4650 /// and VINSERTI64x4 instructions.
4651 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4652 return getInsertVINSERTImmediate(N, 256);
4655 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4657 bool X86::isZeroNode(SDValue Elt) {
4658 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4659 return CN->isNullValue();
4660 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4661 return CFP->getValueAPF().isPosZero();
4665 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4666 /// their permute mask.
4667 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4668 SelectionDAG &DAG) {
4669 MVT VT = SVOp->getSimpleValueType(0);
4670 unsigned NumElems = VT.getVectorNumElements();
4671 SmallVector<int, 8> MaskVec;
4673 for (unsigned i = 0; i != NumElems; ++i) {
4674 int Idx = SVOp->getMaskElt(i);
4676 if (Idx < (int)NumElems)
4681 MaskVec.push_back(Idx);
4683 return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4684 SVOp->getOperand(0), &MaskVec[0]);
4687 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4688 /// match movhlps. The lower half elements should come from upper half of
4689 /// V1 (and in order), and the upper half elements should come from the upper
4690 /// half of V2 (and in order).
4691 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4692 if (!VT.is128BitVector())
4694 if (VT.getVectorNumElements() != 4)
4696 for (unsigned i = 0, e = 2; i != e; ++i)
4697 if (!isUndefOrEqual(Mask[i], i+2))
4699 for (unsigned i = 2; i != 4; ++i)
4700 if (!isUndefOrEqual(Mask[i], i+4))
4705 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4706 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4708 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4709 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4711 N = N->getOperand(0).getNode();
4712 if (!ISD::isNON_EXTLoad(N))
4715 *LD = cast<LoadSDNode>(N);
4719 // Test whether the given value is a vector value which will be legalized
4721 static bool WillBeConstantPoolLoad(SDNode *N) {
4722 if (N->getOpcode() != ISD::BUILD_VECTOR)
4725 // Check for any non-constant elements.
4726 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4727 switch (N->getOperand(i).getNode()->getOpcode()) {
4729 case ISD::ConstantFP:
4736 // Vectors of all-zeros and all-ones are materialized with special
4737 // instructions rather than being loaded.
4738 return !ISD::isBuildVectorAllZeros(N) &&
4739 !ISD::isBuildVectorAllOnes(N);
4742 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4743 /// match movlp{s|d}. The lower half elements should come from lower half of
4744 /// V1 (and in order), and the upper half elements should come from the upper
4745 /// half of V2 (and in order). And since V1 will become the source of the
4746 /// MOVLP, it must be either a vector load or a scalar load to vector.
4747 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4748 ArrayRef<int> Mask, MVT VT) {
4749 if (!VT.is128BitVector())
4752 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4754 // Is V2 is a vector load, don't do this transformation. We will try to use
4755 // load folding shufps op.
4756 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4759 unsigned NumElems = VT.getVectorNumElements();
4761 if (NumElems != 2 && NumElems != 4)
4763 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4764 if (!isUndefOrEqual(Mask[i], i))
4766 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4767 if (!isUndefOrEqual(Mask[i], i+NumElems))
4772 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4774 static bool isSplatVector(SDNode *N) {
4775 if (N->getOpcode() != ISD::BUILD_VECTOR)
4778 SDValue SplatValue = N->getOperand(0);
4779 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4780 if (N->getOperand(i) != SplatValue)
4785 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4786 /// to an zero vector.
4787 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4788 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4789 SDValue V1 = N->getOperand(0);
4790 SDValue V2 = N->getOperand(1);
4791 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4792 for (unsigned i = 0; i != NumElems; ++i) {
4793 int Idx = N->getMaskElt(i);
4794 if (Idx >= (int)NumElems) {
4795 unsigned Opc = V2.getOpcode();
4796 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4798 if (Opc != ISD::BUILD_VECTOR ||
4799 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4801 } else if (Idx >= 0) {
4802 unsigned Opc = V1.getOpcode();
4803 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4805 if (Opc != ISD::BUILD_VECTOR ||
4806 !X86::isZeroNode(V1.getOperand(Idx)))
4813 /// getZeroVector - Returns a vector of specified type with all zero elements.
4815 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4816 SelectionDAG &DAG, SDLoc dl) {
4817 assert(VT.isVector() && "Expected a vector type");
4819 // Always build SSE zero vectors as <4 x i32> bitcasted
4820 // to their dest type. This ensures they get CSE'd.
4822 if (VT.is128BitVector()) { // SSE
4823 if (Subtarget->hasSSE2()) { // SSE2
4824 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4825 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4827 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4828 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4830 } else if (VT.is256BitVector()) { // AVX
4831 if (Subtarget->hasInt256()) { // AVX2
4832 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4833 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4834 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4835 array_lengthof(Ops));
4837 // 256-bit logic and arithmetic instructions in AVX are all
4838 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4839 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4840 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4841 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops,
4842 array_lengthof(Ops));
4844 } else if (VT.is512BitVector()) { // AVX-512
4845 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4846 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4847 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4848 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops, 16);
4849 } else if (VT.getScalarType() == MVT::i1) {
4850 assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4851 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4852 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4853 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4854 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
4855 Ops, VT.getVectorNumElements());
4857 llvm_unreachable("Unexpected vector type");
4859 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4862 /// getOnesVector - Returns a vector of specified type with all bits set.
4863 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4864 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4865 /// Then bitcast to their original type, ensuring they get CSE'd.
4866 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4868 assert(VT.isVector() && "Expected a vector type");
4870 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4872 if (VT.is256BitVector()) {
4873 if (HasInt256) { // AVX2
4874 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4875 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4876 array_lengthof(Ops));
4878 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4879 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4881 } else if (VT.is128BitVector()) {
4882 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4884 llvm_unreachable("Unexpected vector type");
4886 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4889 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4890 /// that point to V2 points to its first element.
4891 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4892 for (unsigned i = 0; i != NumElems; ++i) {
4893 if (Mask[i] > (int)NumElems) {
4899 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4900 /// operation of specified width.
4901 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4903 unsigned NumElems = VT.getVectorNumElements();
4904 SmallVector<int, 8> Mask;
4905 Mask.push_back(NumElems);
4906 for (unsigned i = 1; i != NumElems; ++i)
4908 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4911 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4912 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4914 unsigned NumElems = VT.getVectorNumElements();
4915 SmallVector<int, 8> Mask;
4916 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4918 Mask.push_back(i + NumElems);
4920 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4923 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4924 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4926 unsigned NumElems = VT.getVectorNumElements();
4927 SmallVector<int, 8> Mask;
4928 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4929 Mask.push_back(i + Half);
4930 Mask.push_back(i + NumElems + Half);
4932 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4935 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4936 // a generic shuffle instruction because the target has no such instructions.
4937 // Generate shuffles which repeat i16 and i8 several times until they can be
4938 // represented by v4f32 and then be manipulated by target suported shuffles.
4939 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4940 MVT VT = V.getSimpleValueType();
4941 int NumElems = VT.getVectorNumElements();
4944 while (NumElems > 4) {
4945 if (EltNo < NumElems/2) {
4946 V = getUnpackl(DAG, dl, VT, V, V);
4948 V = getUnpackh(DAG, dl, VT, V, V);
4949 EltNo -= NumElems/2;
4956 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4957 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4958 MVT VT = V.getSimpleValueType();
4961 if (VT.is128BitVector()) {
4962 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4963 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4964 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4966 } else if (VT.is256BitVector()) {
4967 // To use VPERMILPS to splat scalars, the second half of indicies must
4968 // refer to the higher part, which is a duplication of the lower one,
4969 // because VPERMILPS can only handle in-lane permutations.
4970 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4971 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4973 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4974 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4977 llvm_unreachable("Vector size not supported");
4979 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4982 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4983 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4984 MVT SrcVT = SV->getSimpleValueType(0);
4985 SDValue V1 = SV->getOperand(0);
4988 int EltNo = SV->getSplatIndex();
4989 int NumElems = SrcVT.getVectorNumElements();
4990 bool Is256BitVec = SrcVT.is256BitVector();
4992 assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4993 "Unknown how to promote splat for type");
4995 // Extract the 128-bit part containing the splat element and update
4996 // the splat element index when it refers to the higher register.
4998 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4999 if (EltNo >= NumElems/2)
5000 EltNo -= NumElems/2;
5003 // All i16 and i8 vector types can't be used directly by a generic shuffle
5004 // instruction because the target has no such instruction. Generate shuffles
5005 // which repeat i16 and i8 several times until they fit in i32, and then can
5006 // be manipulated by target suported shuffles.
5007 MVT EltVT = SrcVT.getVectorElementType();
5008 if (EltVT == MVT::i8 || EltVT == MVT::i16)
5009 V1 = PromoteSplati8i16(V1, DAG, EltNo);
5011 // Recreate the 256-bit vector and place the same 128-bit vector
5012 // into the low and high part. This is necessary because we want
5013 // to use VPERM* to shuffle the vectors
5015 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5018 return getLegalSplat(DAG, V1, EltNo);
5021 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5022 /// vector of zero or undef vector. This produces a shuffle where the low
5023 /// element of V2 is swizzled into the zero/undef vector, landing at element
5024 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
5025 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5027 const X86Subtarget *Subtarget,
5028 SelectionDAG &DAG) {
5029 MVT VT = V2.getSimpleValueType();
5031 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5032 unsigned NumElems = VT.getVectorNumElements();
5033 SmallVector<int, 16> MaskVec;
5034 for (unsigned i = 0; i != NumElems; ++i)
5035 // If this is the insertion idx, put the low elt of V2 here.
5036 MaskVec.push_back(i == Idx ? NumElems : i);
5037 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5040 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5041 /// target specific opcode. Returns true if the Mask could be calculated.
5042 /// Sets IsUnary to true if only uses one source.
5043 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5044 SmallVectorImpl<int> &Mask, bool &IsUnary) {
5045 unsigned NumElems = VT.getVectorNumElements();
5049 switch(N->getOpcode()) {
5051 ImmN = N->getOperand(N->getNumOperands()-1);
5052 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5054 case X86ISD::UNPCKH:
5055 DecodeUNPCKHMask(VT, Mask);
5057 case X86ISD::UNPCKL:
5058 DecodeUNPCKLMask(VT, Mask);
5060 case X86ISD::MOVHLPS:
5061 DecodeMOVHLPSMask(NumElems, Mask);
5063 case X86ISD::MOVLHPS:
5064 DecodeMOVLHPSMask(NumElems, Mask);
5066 case X86ISD::PALIGNR:
5067 ImmN = N->getOperand(N->getNumOperands()-1);
5068 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5070 case X86ISD::PSHUFD:
5071 case X86ISD::VPERMILP:
5072 ImmN = N->getOperand(N->getNumOperands()-1);
5073 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5076 case X86ISD::PSHUFHW:
5077 ImmN = N->getOperand(N->getNumOperands()-1);
5078 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5081 case X86ISD::PSHUFLW:
5082 ImmN = N->getOperand(N->getNumOperands()-1);
5083 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5086 case X86ISD::VPERMI:
5087 ImmN = N->getOperand(N->getNumOperands()-1);
5088 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5092 case X86ISD::MOVSD: {
5093 // The index 0 always comes from the first element of the second source,
5094 // this is why MOVSS and MOVSD are used in the first place. The other
5095 // elements come from the other positions of the first source vector
5096 Mask.push_back(NumElems);
5097 for (unsigned i = 1; i != NumElems; ++i) {
5102 case X86ISD::VPERM2X128:
5103 ImmN = N->getOperand(N->getNumOperands()-1);
5104 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5105 if (Mask.empty()) return false;
5107 case X86ISD::MOVDDUP:
5108 case X86ISD::MOVLHPD:
5109 case X86ISD::MOVLPD:
5110 case X86ISD::MOVLPS:
5111 case X86ISD::MOVSHDUP:
5112 case X86ISD::MOVSLDUP:
5113 // Not yet implemented
5115 default: llvm_unreachable("unknown target shuffle node");
5121 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5122 /// element of the result of the vector shuffle.
5123 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5126 return SDValue(); // Limit search depth.
5128 SDValue V = SDValue(N, 0);
5129 EVT VT = V.getValueType();
5130 unsigned Opcode = V.getOpcode();
5132 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5133 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5134 int Elt = SV->getMaskElt(Index);
5137 return DAG.getUNDEF(VT.getVectorElementType());
5139 unsigned NumElems = VT.getVectorNumElements();
5140 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5141 : SV->getOperand(1);
5142 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5145 // Recurse into target specific vector shuffles to find scalars.
5146 if (isTargetShuffle(Opcode)) {
5147 MVT ShufVT = V.getSimpleValueType();
5148 unsigned NumElems = ShufVT.getVectorNumElements();
5149 SmallVector<int, 16> ShuffleMask;
5152 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5155 int Elt = ShuffleMask[Index];
5157 return DAG.getUNDEF(ShufVT.getVectorElementType());
5159 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5161 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5165 // Actual nodes that may contain scalar elements
5166 if (Opcode == ISD::BITCAST) {
5167 V = V.getOperand(0);
5168 EVT SrcVT = V.getValueType();
5169 unsigned NumElems = VT.getVectorNumElements();
5171 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5175 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5176 return (Index == 0) ? V.getOperand(0)
5177 : DAG.getUNDEF(VT.getVectorElementType());
5179 if (V.getOpcode() == ISD::BUILD_VECTOR)
5180 return V.getOperand(Index);
5185 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5186 /// shuffle operation which come from a consecutively from a zero. The
5187 /// search can start in two different directions, from left or right.
5188 /// We count undefs as zeros until PreferredNum is reached.
5189 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5190 unsigned NumElems, bool ZerosFromLeft,
5192 unsigned PreferredNum = -1U) {
5193 unsigned NumZeros = 0;
5194 for (unsigned i = 0; i != NumElems; ++i) {
5195 unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5196 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5200 if (X86::isZeroNode(Elt))
5202 else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5203 NumZeros = std::min(NumZeros + 1, PreferredNum);
5211 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5212 /// correspond consecutively to elements from one of the vector operands,
5213 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5215 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5216 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5217 unsigned NumElems, unsigned &OpNum) {
5218 bool SeenV1 = false;
5219 bool SeenV2 = false;
5221 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5222 int Idx = SVOp->getMaskElt(i);
5223 // Ignore undef indicies
5227 if (Idx < (int)NumElems)
5232 // Only accept consecutive elements from the same vector
5233 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5237 OpNum = SeenV1 ? 0 : 1;
5241 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5242 /// logical left shift of a vector.
5243 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5244 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5246 SVOp->getSimpleValueType(0).getVectorNumElements();
5247 unsigned NumZeros = getNumOfConsecutiveZeros(
5248 SVOp, NumElems, false /* check zeros from right */, DAG,
5249 SVOp->getMaskElt(0));
5255 // Considering the elements in the mask that are not consecutive zeros,
5256 // check if they consecutively come from only one of the source vectors.
5258 // V1 = {X, A, B, C} 0
5260 // vector_shuffle V1, V2 <1, 2, 3, X>
5262 if (!isShuffleMaskConsecutive(SVOp,
5263 0, // Mask Start Index
5264 NumElems-NumZeros, // Mask End Index(exclusive)
5265 NumZeros, // Where to start looking in the src vector
5266 NumElems, // Number of elements in vector
5267 OpSrc)) // Which source operand ?
5272 ShVal = SVOp->getOperand(OpSrc);
5276 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5277 /// logical left shift of a vector.
5278 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5279 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5281 SVOp->getSimpleValueType(0).getVectorNumElements();
5282 unsigned NumZeros = getNumOfConsecutiveZeros(
5283 SVOp, NumElems, true /* check zeros from left */, DAG,
5284 NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5290 // Considering the elements in the mask that are not consecutive zeros,
5291 // check if they consecutively come from only one of the source vectors.
5293 // 0 { A, B, X, X } = V2
5295 // vector_shuffle V1, V2 <X, X, 4, 5>
5297 if (!isShuffleMaskConsecutive(SVOp,
5298 NumZeros, // Mask Start Index
5299 NumElems, // Mask End Index(exclusive)
5300 0, // Where to start looking in the src vector
5301 NumElems, // Number of elements in vector
5302 OpSrc)) // Which source operand ?
5307 ShVal = SVOp->getOperand(OpSrc);
5311 /// isVectorShift - Returns true if the shuffle can be implemented as a
5312 /// logical left or right shift of a vector.
5313 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5314 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5315 // Although the logic below support any bitwidth size, there are no
5316 // shift instructions which handle more than 128-bit vectors.
5317 if (!SVOp->getSimpleValueType(0).is128BitVector())
5320 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5321 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5327 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5329 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5330 unsigned NumNonZero, unsigned NumZero,
5332 const X86Subtarget* Subtarget,
5333 const TargetLowering &TLI) {
5340 for (unsigned i = 0; i < 16; ++i) {
5341 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5342 if (ThisIsNonZero && First) {
5344 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5346 V = DAG.getUNDEF(MVT::v8i16);
5351 SDValue ThisElt, LastElt;
5352 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5353 if (LastIsNonZero) {
5354 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5355 MVT::i16, Op.getOperand(i-1));
5357 if (ThisIsNonZero) {
5358 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5359 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5360 ThisElt, DAG.getConstant(8, MVT::i8));
5362 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5366 if (ThisElt.getNode())
5367 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5368 DAG.getIntPtrConstant(i/2));
5372 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5375 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5377 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5378 unsigned NumNonZero, unsigned NumZero,
5380 const X86Subtarget* Subtarget,
5381 const TargetLowering &TLI) {
5388 for (unsigned i = 0; i < 8; ++i) {
5389 bool isNonZero = (NonZeros & (1 << i)) != 0;
5393 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5395 V = DAG.getUNDEF(MVT::v8i16);
5398 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5399 MVT::v8i16, V, Op.getOperand(i),
5400 DAG.getIntPtrConstant(i));
5407 /// getVShift - Return a vector logical shift node.
5409 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5410 unsigned NumBits, SelectionDAG &DAG,
5411 const TargetLowering &TLI, SDLoc dl) {
5412 assert(VT.is128BitVector() && "Unknown type for VShift");
5413 EVT ShVT = MVT::v2i64;
5414 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5415 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5416 return DAG.getNode(ISD::BITCAST, dl, VT,
5417 DAG.getNode(Opc, dl, ShVT, SrcOp,
5418 DAG.getConstant(NumBits,
5419 TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5423 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5425 // Check if the scalar load can be widened into a vector load. And if
5426 // the address is "base + cst" see if the cst can be "absorbed" into
5427 // the shuffle mask.
5428 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5429 SDValue Ptr = LD->getBasePtr();
5430 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5432 EVT PVT = LD->getValueType(0);
5433 if (PVT != MVT::i32 && PVT != MVT::f32)
5438 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5439 FI = FINode->getIndex();
5441 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5442 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5443 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5444 Offset = Ptr.getConstantOperandVal(1);
5445 Ptr = Ptr.getOperand(0);
5450 // FIXME: 256-bit vector instructions don't require a strict alignment,
5451 // improve this code to support it better.
5452 unsigned RequiredAlign = VT.getSizeInBits()/8;
5453 SDValue Chain = LD->getChain();
5454 // Make sure the stack object alignment is at least 16 or 32.
5455 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5456 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5457 if (MFI->isFixedObjectIndex(FI)) {
5458 // Can't change the alignment. FIXME: It's possible to compute
5459 // the exact stack offset and reference FI + adjust offset instead.
5460 // If someone *really* cares about this. That's the way to implement it.
5463 MFI->setObjectAlignment(FI, RequiredAlign);
5467 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5468 // Ptr + (Offset & ~15).
5471 if ((Offset % RequiredAlign) & 3)
5473 int64_t StartOffset = Offset & ~(RequiredAlign-1);
5475 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5476 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5478 int EltNo = (Offset - StartOffset) >> 2;
5479 unsigned NumElems = VT.getVectorNumElements();
5481 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5482 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5483 LD->getPointerInfo().getWithOffset(StartOffset),
5484 false, false, false, 0);
5486 SmallVector<int, 8> Mask;
5487 for (unsigned i = 0; i != NumElems; ++i)
5488 Mask.push_back(EltNo);
5490 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5496 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5497 /// vector of type 'VT', see if the elements can be replaced by a single large
5498 /// load which has the same value as a build_vector whose operands are 'elts'.
5500 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5502 /// FIXME: we'd also like to handle the case where the last elements are zero
5503 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5504 /// There's even a handy isZeroNode for that purpose.
5505 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5506 SDLoc &DL, SelectionDAG &DAG,
5507 bool isAfterLegalize) {
5508 EVT EltVT = VT.getVectorElementType();
5509 unsigned NumElems = Elts.size();
5511 LoadSDNode *LDBase = nullptr;
5512 unsigned LastLoadedElt = -1U;
5514 // For each element in the initializer, see if we've found a load or an undef.
5515 // If we don't find an initial load element, or later load elements are
5516 // non-consecutive, bail out.
5517 for (unsigned i = 0; i < NumElems; ++i) {
5518 SDValue Elt = Elts[i];
5520 if (!Elt.getNode() ||
5521 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5524 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5526 LDBase = cast<LoadSDNode>(Elt.getNode());
5530 if (Elt.getOpcode() == ISD::UNDEF)
5533 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5534 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5539 // If we have found an entire vector of loads and undefs, then return a large
5540 // load of the entire vector width starting at the base pointer. If we found
5541 // consecutive loads for the low half, generate a vzext_load node.
5542 if (LastLoadedElt == NumElems - 1) {
5544 if (isAfterLegalize &&
5545 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5548 SDValue NewLd = SDValue();
5550 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5551 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5552 LDBase->getPointerInfo(),
5553 LDBase->isVolatile(), LDBase->isNonTemporal(),
5554 LDBase->isInvariant(), 0);
5555 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5556 LDBase->getPointerInfo(),
5557 LDBase->isVolatile(), LDBase->isNonTemporal(),
5558 LDBase->isInvariant(), LDBase->getAlignment());
5560 if (LDBase->hasAnyUseOfValue(1)) {
5561 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5563 SDValue(NewLd.getNode(), 1));
5564 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5565 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5566 SDValue(NewLd.getNode(), 1));
5571 if (NumElems == 4 && LastLoadedElt == 1 &&
5572 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5573 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5574 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5576 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops,
5577 array_lengthof(Ops), MVT::i64,
5578 LDBase->getPointerInfo(),
5579 LDBase->getAlignment(),
5580 false/*isVolatile*/, true/*ReadMem*/,
5583 // Make sure the newly-created LOAD is in the same position as LDBase in
5584 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5585 // update uses of LDBase's output chain to use the TokenFactor.
5586 if (LDBase->hasAnyUseOfValue(1)) {
5587 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5588 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5589 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5590 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5591 SDValue(ResNode.getNode(), 1));
5594 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5599 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5600 /// to generate a splat value for the following cases:
5601 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5602 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5603 /// a scalar load, or a constant.
5604 /// The VBROADCAST node is returned when a pattern is found,
5605 /// or SDValue() otherwise.
5606 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5607 SelectionDAG &DAG) {
5608 if (!Subtarget->hasFp256())
5611 MVT VT = Op.getSimpleValueType();
5614 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5615 "Unsupported vector type for broadcast.");
5620 switch (Op.getOpcode()) {
5622 // Unknown pattern found.
5625 case ISD::BUILD_VECTOR: {
5626 // The BUILD_VECTOR node must be a splat.
5627 if (!isSplatVector(Op.getNode()))
5630 Ld = Op.getOperand(0);
5631 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5632 Ld.getOpcode() == ISD::ConstantFP);
5634 // The suspected load node has several users. Make sure that all
5635 // of its users are from the BUILD_VECTOR node.
5636 // Constants may have multiple users.
5637 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5642 case ISD::VECTOR_SHUFFLE: {
5643 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5645 // Shuffles must have a splat mask where the first element is
5647 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5650 SDValue Sc = Op.getOperand(0);
5651 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5652 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5654 if (!Subtarget->hasInt256())
5657 // Use the register form of the broadcast instruction available on AVX2.
5658 if (VT.getSizeInBits() >= 256)
5659 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5660 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5663 Ld = Sc.getOperand(0);
5664 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5665 Ld.getOpcode() == ISD::ConstantFP);
5667 // The scalar_to_vector node and the suspected
5668 // load node must have exactly one user.
5669 // Constants may have multiple users.
5671 // AVX-512 has register version of the broadcast
5672 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5673 Ld.getValueType().getSizeInBits() >= 32;
5674 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5681 bool IsGE256 = (VT.getSizeInBits() >= 256);
5683 // Handle the broadcasting a single constant scalar from the constant pool
5684 // into a vector. On Sandybridge it is still better to load a constant vector
5685 // from the constant pool and not to broadcast it from a scalar.
5686 if (ConstSplatVal && Subtarget->hasInt256()) {
5687 EVT CVT = Ld.getValueType();
5688 assert(!CVT.isVector() && "Must not broadcast a vector type");
5689 unsigned ScalarSize = CVT.getSizeInBits();
5691 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5692 const Constant *C = nullptr;
5693 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5694 C = CI->getConstantIntValue();
5695 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5696 C = CF->getConstantFPValue();
5698 assert(C && "Invalid constant type");
5700 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5701 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5702 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5703 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5704 MachinePointerInfo::getConstantPool(),
5705 false, false, false, Alignment);
5707 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5711 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5712 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5714 // Handle AVX2 in-register broadcasts.
5715 if (!IsLoad && Subtarget->hasInt256() &&
5716 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5717 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5719 // The scalar source must be a normal load.
5723 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5724 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5726 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5727 // double since there is no vbroadcastsd xmm
5728 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5729 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5730 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5733 // Unsupported broadcast.
5737 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5738 /// underlying vector and index.
5740 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5742 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5744 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5745 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5748 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5750 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5752 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5753 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5756 // In this case the vector is the extract_subvector expression and the index
5757 // is 2, as specified by the shuffle.
5758 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5759 SDValue ShuffleVec = SVOp->getOperand(0);
5760 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5761 assert(ShuffleVecVT.getVectorElementType() ==
5762 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5764 int ShuffleIdx = SVOp->getMaskElt(Idx);
5765 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5766 ExtractedFromVec = ShuffleVec;
5772 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5773 MVT VT = Op.getSimpleValueType();
5775 // Skip if insert_vec_elt is not supported.
5776 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5777 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5781 unsigned NumElems = Op.getNumOperands();
5785 SmallVector<unsigned, 4> InsertIndices;
5786 SmallVector<int, 8> Mask(NumElems, -1);
5788 for (unsigned i = 0; i != NumElems; ++i) {
5789 unsigned Opc = Op.getOperand(i).getOpcode();
5791 if (Opc == ISD::UNDEF)
5794 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5795 // Quit if more than 1 elements need inserting.
5796 if (InsertIndices.size() > 1)
5799 InsertIndices.push_back(i);
5803 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5804 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5805 // Quit if non-constant index.
5806 if (!isa<ConstantSDNode>(ExtIdx))
5808 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5810 // Quit if extracted from vector of different type.
5811 if (ExtractedFromVec.getValueType() != VT)
5814 if (!VecIn1.getNode())
5815 VecIn1 = ExtractedFromVec;
5816 else if (VecIn1 != ExtractedFromVec) {
5817 if (!VecIn2.getNode())
5818 VecIn2 = ExtractedFromVec;
5819 else if (VecIn2 != ExtractedFromVec)
5820 // Quit if more than 2 vectors to shuffle
5824 if (ExtractedFromVec == VecIn1)
5826 else if (ExtractedFromVec == VecIn2)
5827 Mask[i] = Idx + NumElems;
5830 if (!VecIn1.getNode())
5833 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5834 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5835 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5836 unsigned Idx = InsertIndices[i];
5837 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5838 DAG.getIntPtrConstant(Idx));
5844 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5846 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5848 MVT VT = Op.getSimpleValueType();
5849 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5850 "Unexpected type in LowerBUILD_VECTORvXi1!");
5853 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5854 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5855 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5856 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5857 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5858 Ops, VT.getVectorNumElements());
5861 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5862 SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5863 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5864 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5865 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5866 Ops, VT.getVectorNumElements());
5869 bool AllContants = true;
5870 uint64_t Immediate = 0;
5871 int NonConstIdx = -1;
5872 bool IsSplat = true;
5873 unsigned NumNonConsts = 0;
5874 unsigned NumConsts = 0;
5875 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5876 SDValue In = Op.getOperand(idx);
5877 if (In.getOpcode() == ISD::UNDEF)
5879 if (!isa<ConstantSDNode>(In)) {
5880 AllContants = false;
5886 if (cast<ConstantSDNode>(In)->getZExtValue())
5887 Immediate |= (1ULL << idx);
5889 if (In != Op.getOperand(0))
5894 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5895 DAG.getConstant(Immediate, MVT::i16));
5896 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5897 DAG.getIntPtrConstant(0));
5900 if (NumNonConsts == 1 && NonConstIdx != 0) {
5903 SDValue VecAsImm = DAG.getConstant(Immediate,
5904 MVT::getIntegerVT(VT.getSizeInBits()));
5905 DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
5908 DstVec = DAG.getUNDEF(VT);
5909 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5910 Op.getOperand(NonConstIdx),
5911 DAG.getIntPtrConstant(NonConstIdx));
5913 if (!IsSplat && (NonConstIdx != 0))
5914 llvm_unreachable("Unsupported BUILD_VECTOR operation");
5915 MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
5918 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5919 DAG.getConstant(-1, SelectVT),
5920 DAG.getConstant(0, SelectVT));
5922 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5923 DAG.getConstant((Immediate | 1), SelectVT),
5924 DAG.getConstant(Immediate, SelectVT));
5925 return DAG.getNode(ISD::BITCAST, dl, VT, Select);
5929 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5932 MVT VT = Op.getSimpleValueType();
5933 MVT ExtVT = VT.getVectorElementType();
5934 unsigned NumElems = Op.getNumOperands();
5936 // Generate vectors for predicate vectors.
5937 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5938 return LowerBUILD_VECTORvXi1(Op, DAG);
5940 // Vectors containing all zeros can be matched by pxor and xorps later
5941 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5942 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5943 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5944 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5947 return getZeroVector(VT, Subtarget, DAG, dl);
5950 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5951 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5952 // vpcmpeqd on 256-bit vectors.
5953 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5954 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5957 if (!VT.is512BitVector())
5958 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5961 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
5962 if (Broadcast.getNode())
5965 unsigned EVTBits = ExtVT.getSizeInBits();
5967 unsigned NumZero = 0;
5968 unsigned NumNonZero = 0;
5969 unsigned NonZeros = 0;
5970 bool IsAllConstants = true;
5971 SmallSet<SDValue, 8> Values;
5972 for (unsigned i = 0; i < NumElems; ++i) {
5973 SDValue Elt = Op.getOperand(i);
5974 if (Elt.getOpcode() == ISD::UNDEF)
5977 if (Elt.getOpcode() != ISD::Constant &&
5978 Elt.getOpcode() != ISD::ConstantFP)
5979 IsAllConstants = false;
5980 if (X86::isZeroNode(Elt))
5983 NonZeros |= (1 << i);
5988 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5989 if (NumNonZero == 0)
5990 return DAG.getUNDEF(VT);
5992 // Special case for single non-zero, non-undef, element.
5993 if (NumNonZero == 1) {
5994 unsigned Idx = countTrailingZeros(NonZeros);
5995 SDValue Item = Op.getOperand(Idx);
5997 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5998 // the value are obviously zero, truncate the value to i32 and do the
5999 // insertion that way. Only do this if the value is non-constant or if the
6000 // value is a constant being inserted into element 0. It is cheaper to do
6001 // a constant pool load than it is to do a movd + shuffle.
6002 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6003 (!IsAllConstants || Idx == 0)) {
6004 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6006 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6007 EVT VecVT = MVT::v4i32;
6008 unsigned VecElts = 4;
6010 // Truncate the value (which may itself be a constant) to i32, and
6011 // convert it to a vector with movd (S2V+shuffle to zero extend).
6012 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6013 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6014 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6016 // Now we have our 32-bit value zero extended in the low element of
6017 // a vector. If Idx != 0, swizzle it into place.
6019 SmallVector<int, 4> Mask;
6020 Mask.push_back(Idx);
6021 for (unsigned i = 1; i != VecElts; ++i)
6023 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6026 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6030 // If we have a constant or non-constant insertion into the low element of
6031 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6032 // the rest of the elements. This will be matched as movd/movq/movss/movsd
6033 // depending on what the source datatype is.
6036 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6038 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6039 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6040 if (VT.is256BitVector() || VT.is512BitVector()) {
6041 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6042 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6043 Item, DAG.getIntPtrConstant(0));
6045 assert(VT.is128BitVector() && "Expected an SSE value type!");
6046 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6047 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6048 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6051 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6052 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6053 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6054 if (VT.is256BitVector()) {
6055 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6056 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6058 assert(VT.is128BitVector() && "Expected an SSE value type!");
6059 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6061 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6065 // Is it a vector logical left shift?
6066 if (NumElems == 2 && Idx == 1 &&
6067 X86::isZeroNode(Op.getOperand(0)) &&
6068 !X86::isZeroNode(Op.getOperand(1))) {
6069 unsigned NumBits = VT.getSizeInBits();
6070 return getVShift(true, VT,
6071 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6072 VT, Op.getOperand(1)),
6073 NumBits/2, DAG, *this, dl);
6076 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6079 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6080 // is a non-constant being inserted into an element other than the low one,
6081 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6082 // movd/movss) to move this into the low element, then shuffle it into
6084 if (EVTBits == 32) {
6085 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6087 // Turn it into a shuffle of zero and zero-extended scalar to vector.
6088 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6089 SmallVector<int, 8> MaskVec;
6090 for (unsigned i = 0; i != NumElems; ++i)
6091 MaskVec.push_back(i == Idx ? 0 : 1);
6092 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6096 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6097 if (Values.size() == 1) {
6098 if (EVTBits == 32) {
6099 // Instead of a shuffle like this:
6100 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6101 // Check if it's possible to issue this instead.
6102 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6103 unsigned Idx = countTrailingZeros(NonZeros);
6104 SDValue Item = Op.getOperand(Idx);
6105 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6106 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6111 // A vector full of immediates; various special cases are already
6112 // handled, so this is best done with a single constant-pool load.
6116 // For AVX-length vectors, build the individual 128-bit pieces and use
6117 // shuffles to put them in place.
6118 if (VT.is256BitVector() || VT.is512BitVector()) {
6119 SmallVector<SDValue, 64> V;
6120 for (unsigned i = 0; i != NumElems; ++i)
6121 V.push_back(Op.getOperand(i));
6123 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6125 // Build both the lower and upper subvector.
6126 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
6127 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
6130 // Recreate the wider vector with the lower and upper part.
6131 if (VT.is256BitVector())
6132 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6133 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6136 // Let legalizer expand 2-wide build_vectors.
6137 if (EVTBits == 64) {
6138 if (NumNonZero == 1) {
6139 // One half is zero or undef.
6140 unsigned Idx = countTrailingZeros(NonZeros);
6141 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6142 Op.getOperand(Idx));
6143 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6148 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6149 if (EVTBits == 8 && NumElems == 16) {
6150 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6152 if (V.getNode()) return V;
6155 if (EVTBits == 16 && NumElems == 8) {
6156 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6158 if (V.getNode()) return V;
6161 // If element VT is == 32 bits, turn it into a number of shuffles.
6162 SmallVector<SDValue, 8> V(NumElems);
6163 if (NumElems == 4 && NumZero > 0) {
6164 for (unsigned i = 0; i < 4; ++i) {
6165 bool isZero = !(NonZeros & (1 << i));
6167 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6169 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6172 for (unsigned i = 0; i < 2; ++i) {
6173 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6176 V[i] = V[i*2]; // Must be a zero vector.
6179 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6182 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6185 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6190 bool Reverse1 = (NonZeros & 0x3) == 2;
6191 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6195 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6196 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6198 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6201 if (Values.size() > 1 && VT.is128BitVector()) {
6202 // Check for a build vector of consecutive loads.
6203 for (unsigned i = 0; i < NumElems; ++i)
6204 V[i] = Op.getOperand(i);
6206 // Check for elements which are consecutive loads.
6207 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6211 // Check for a build vector from mostly shuffle plus few inserting.
6212 SDValue Sh = buildFromShuffleMostly(Op, DAG);
6216 // For SSE 4.1, use insertps to put the high elements into the low element.
6217 if (getSubtarget()->hasSSE41()) {
6219 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6220 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6222 Result = DAG.getUNDEF(VT);
6224 for (unsigned i = 1; i < NumElems; ++i) {
6225 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6226 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6227 Op.getOperand(i), DAG.getIntPtrConstant(i));
6232 // Otherwise, expand into a number of unpckl*, start by extending each of
6233 // our (non-undef) elements to the full vector width with the element in the
6234 // bottom slot of the vector (which generates no code for SSE).
6235 for (unsigned i = 0; i < NumElems; ++i) {
6236 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6237 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6239 V[i] = DAG.getUNDEF(VT);
6242 // Next, we iteratively mix elements, e.g. for v4f32:
6243 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6244 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6245 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6246 unsigned EltStride = NumElems >> 1;
6247 while (EltStride != 0) {
6248 for (unsigned i = 0; i < EltStride; ++i) {
6249 // If V[i+EltStride] is undef and this is the first round of mixing,
6250 // then it is safe to just drop this shuffle: V[i] is already in the
6251 // right place, the one element (since it's the first round) being
6252 // inserted as undef can be dropped. This isn't safe for successive
6253 // rounds because they will permute elements within both vectors.
6254 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6255 EltStride == NumElems/2)
6258 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6267 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6268 // to create 256-bit vectors from two other 128-bit ones.
6269 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6271 MVT ResVT = Op.getSimpleValueType();
6273 assert((ResVT.is256BitVector() ||
6274 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6276 SDValue V1 = Op.getOperand(0);
6277 SDValue V2 = Op.getOperand(1);
6278 unsigned NumElems = ResVT.getVectorNumElements();
6279 if(ResVT.is256BitVector())
6280 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6282 if (Op.getNumOperands() == 4) {
6283 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6284 ResVT.getVectorNumElements()/2);
6285 SDValue V3 = Op.getOperand(2);
6286 SDValue V4 = Op.getOperand(3);
6287 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6288 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6290 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6293 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6294 MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6295 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6296 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6297 Op.getNumOperands() == 4)));
6299 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6300 // from two other 128-bit ones.
6302 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6303 return LowerAVXCONCAT_VECTORS(Op, DAG);
6306 // Try to lower a shuffle node into a simple blend instruction.
6308 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6309 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6310 SDValue V1 = SVOp->getOperand(0);
6311 SDValue V2 = SVOp->getOperand(1);
6313 MVT VT = SVOp->getSimpleValueType(0);
6314 MVT EltVT = VT.getVectorElementType();
6315 unsigned NumElems = VT.getVectorNumElements();
6317 // There is no blend with immediate in AVX-512.
6318 if (VT.is512BitVector())
6321 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
6323 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
6326 // Check the mask for BLEND and build the value.
6327 unsigned MaskValue = 0;
6328 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6329 unsigned NumLanes = (NumElems-1)/8 + 1;
6330 unsigned NumElemsInLane = NumElems / NumLanes;
6332 // Blend for v16i16 should be symetric for the both lanes.
6333 for (unsigned i = 0; i < NumElemsInLane; ++i) {
6335 int SndLaneEltIdx = (NumLanes == 2) ?
6336 SVOp->getMaskElt(i + NumElemsInLane) : -1;
6337 int EltIdx = SVOp->getMaskElt(i);
6339 if ((EltIdx < 0 || EltIdx == (int)i) &&
6340 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6343 if (((unsigned)EltIdx == (i + NumElems)) &&
6344 (SndLaneEltIdx < 0 ||
6345 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6346 MaskValue |= (1<<i);
6351 // Convert i32 vectors to floating point if it is not AVX2.
6352 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6354 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6355 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6357 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6358 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6361 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6362 DAG.getConstant(MaskValue, MVT::i32));
6363 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6366 /// In vector type \p VT, return true if the element at index \p InputIdx
6367 /// falls on a different 128-bit lane than \p OutputIdx.
6368 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
6369 unsigned OutputIdx) {
6370 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6371 return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
6374 /// Generate a PSHUFB if possible. Selects elements from \p V1 according to
6375 /// \p MaskVals. MaskVals[OutputIdx] = InputIdx specifies that we want to
6376 /// shuffle the element at InputIdx in V1 to OutputIdx in the result. If \p
6377 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
6379 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
6380 SelectionDAG &DAG) {
6381 MVT VT = V1.getSimpleValueType();
6382 assert(VT.is128BitVector() || VT.is256BitVector());
6384 MVT EltVT = VT.getVectorElementType();
6385 unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
6386 unsigned NumElts = VT.getVectorNumElements();
6388 SmallVector<SDValue, 32> PshufbMask;
6389 for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
6390 int InputIdx = MaskVals[OutputIdx];
6391 unsigned InputByteIdx;
6393 if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
6394 InputByteIdx = 0x80;
6396 // Cross lane is not allowed.
6397 if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
6399 InputByteIdx = InputIdx * EltSizeInBytes;
6400 // Index is an byte offset within the 128-bit lane.
6401 InputByteIdx &= 0xf;
6404 for (unsigned j = 0; j < EltSizeInBytes; ++j) {
6405 PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
6406 if (InputByteIdx != 0x80)
6411 MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
6413 V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
6414 return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
6415 DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT,
6416 PshufbMask.data(), PshufbMask.size()));
6419 // v8i16 shuffles - Prefer shuffles in the following order:
6420 // 1. [all] pshuflw, pshufhw, optional move
6421 // 2. [ssse3] 1 x pshufb
6422 // 3. [ssse3] 2 x pshufb + 1 x por
6423 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6425 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6426 SelectionDAG &DAG) {
6427 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6428 SDValue V1 = SVOp->getOperand(0);
6429 SDValue V2 = SVOp->getOperand(1);
6431 SmallVector<int, 8> MaskVals;
6433 // Determine if more than 1 of the words in each of the low and high quadwords
6434 // of the result come from the same quadword of one of the two inputs. Undef
6435 // mask values count as coming from any quadword, for better codegen.
6437 // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
6438 // feeds this quad. For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
6439 unsigned LoQuad[] = { 0, 0, 0, 0 };
6440 unsigned HiQuad[] = { 0, 0, 0, 0 };
6441 // Indices of quads used.
6442 std::bitset<4> InputQuads;
6443 for (unsigned i = 0; i < 8; ++i) {
6444 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6445 int EltIdx = SVOp->getMaskElt(i);
6446 MaskVals.push_back(EltIdx);
6455 InputQuads.set(EltIdx / 4);
6458 int BestLoQuad = -1;
6459 unsigned MaxQuad = 1;
6460 for (unsigned i = 0; i < 4; ++i) {
6461 if (LoQuad[i] > MaxQuad) {
6463 MaxQuad = LoQuad[i];
6467 int BestHiQuad = -1;
6469 for (unsigned i = 0; i < 4; ++i) {
6470 if (HiQuad[i] > MaxQuad) {
6472 MaxQuad = HiQuad[i];
6476 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6477 // of the two input vectors, shuffle them into one input vector so only a
6478 // single pshufb instruction is necessary. If there are more than 2 input
6479 // quads, disable the next transformation since it does not help SSSE3.
6480 bool V1Used = InputQuads[0] || InputQuads[1];
6481 bool V2Used = InputQuads[2] || InputQuads[3];
6482 if (Subtarget->hasSSSE3()) {
6483 if (InputQuads.count() == 2 && V1Used && V2Used) {
6484 BestLoQuad = InputQuads[0] ? 0 : 1;
6485 BestHiQuad = InputQuads[2] ? 2 : 3;
6487 if (InputQuads.count() > 2) {
6493 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6494 // the shuffle mask. If a quad is scored as -1, that means that it contains
6495 // words from all 4 input quadwords.
6497 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6499 BestLoQuad < 0 ? 0 : BestLoQuad,
6500 BestHiQuad < 0 ? 1 : BestHiQuad
6502 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6503 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6504 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6505 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6507 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6508 // source words for the shuffle, to aid later transformations.
6509 bool AllWordsInNewV = true;
6510 bool InOrder[2] = { true, true };
6511 for (unsigned i = 0; i != 8; ++i) {
6512 int idx = MaskVals[i];
6514 InOrder[i/4] = false;
6515 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6517 AllWordsInNewV = false;
6521 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6522 if (AllWordsInNewV) {
6523 for (int i = 0; i != 8; ++i) {
6524 int idx = MaskVals[i];
6527 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6528 if ((idx != i) && idx < 4)
6530 if ((idx != i) && idx > 3)
6539 // If we've eliminated the use of V2, and the new mask is a pshuflw or
6540 // pshufhw, that's as cheap as it gets. Return the new shuffle.
6541 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6542 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6543 unsigned TargetMask = 0;
6544 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6545 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6546 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6547 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6548 getShufflePSHUFLWImmediate(SVOp);
6549 V1 = NewV.getOperand(0);
6550 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6554 // Promote splats to a larger type which usually leads to more efficient code.
6555 // FIXME: Is this true if pshufb is available?
6556 if (SVOp->isSplat())
6557 return PromoteSplat(SVOp, DAG);
6559 // If we have SSSE3, and all words of the result are from 1 input vector,
6560 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
6561 // is present, fall back to case 4.
6562 if (Subtarget->hasSSSE3()) {
6563 SmallVector<SDValue,16> pshufbMask;
6565 // If we have elements from both input vectors, set the high bit of the
6566 // shuffle mask element to zero out elements that come from V2 in the V1
6567 // mask, and elements that come from V1 in the V2 mask, so that the two
6568 // results can be OR'd together.
6569 bool TwoInputs = V1Used && V2Used;
6570 V1 = getPSHUFB(MaskVals, V1, dl, DAG);
6572 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6574 // Calculate the shuffle mask for the second input, shuffle it, and
6575 // OR it with the first shuffled input.
6576 CommuteVectorShuffleMask(MaskVals, 8);
6577 V2 = getPSHUFB(MaskVals, V2, dl, DAG);
6578 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6579 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6582 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6583 // and update MaskVals with new element order.
6584 std::bitset<8> InOrder;
6585 if (BestLoQuad >= 0) {
6586 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6587 for (int i = 0; i != 4; ++i) {
6588 int idx = MaskVals[i];
6591 } else if ((idx / 4) == BestLoQuad) {
6596 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6599 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6600 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6601 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6603 getShufflePSHUFLWImmediate(SVOp), DAG);
6607 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6608 // and update MaskVals with the new element order.
6609 if (BestHiQuad >= 0) {
6610 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6611 for (unsigned i = 4; i != 8; ++i) {
6612 int idx = MaskVals[i];
6615 } else if ((idx / 4) == BestHiQuad) {
6616 MaskV[i] = (idx & 3) + 4;
6620 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6623 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6624 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6625 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6627 getShufflePSHUFHWImmediate(SVOp), DAG);
6631 // In case BestHi & BestLo were both -1, which means each quadword has a word
6632 // from each of the four input quadwords, calculate the InOrder bitvector now
6633 // before falling through to the insert/extract cleanup.
6634 if (BestLoQuad == -1 && BestHiQuad == -1) {
6636 for (int i = 0; i != 8; ++i)
6637 if (MaskVals[i] < 0 || MaskVals[i] == i)
6641 // The other elements are put in the right place using pextrw and pinsrw.
6642 for (unsigned i = 0; i != 8; ++i) {
6645 int EltIdx = MaskVals[i];
6648 SDValue ExtOp = (EltIdx < 8) ?
6649 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6650 DAG.getIntPtrConstant(EltIdx)) :
6651 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6652 DAG.getIntPtrConstant(EltIdx - 8));
6653 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6654 DAG.getIntPtrConstant(i));
6659 /// \brief v16i16 shuffles
6661 /// FIXME: We only support generation of a single pshufb currently. We can
6662 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
6663 /// well (e.g 2 x pshufb + 1 x por).
6665 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
6666 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6667 SDValue V1 = SVOp->getOperand(0);
6668 SDValue V2 = SVOp->getOperand(1);
6671 if (V2.getOpcode() != ISD::UNDEF)
6674 SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6675 return getPSHUFB(MaskVals, V1, dl, DAG);
6678 // v16i8 shuffles - Prefer shuffles in the following order:
6679 // 1. [ssse3] 1 x pshufb
6680 // 2. [ssse3] 2 x pshufb + 1 x por
6681 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
6682 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6683 const X86Subtarget* Subtarget,
6684 SelectionDAG &DAG) {
6685 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6686 SDValue V1 = SVOp->getOperand(0);
6687 SDValue V2 = SVOp->getOperand(1);
6689 ArrayRef<int> MaskVals = SVOp->getMask();
6691 // Promote splats to a larger type which usually leads to more efficient code.
6692 // FIXME: Is this true if pshufb is available?
6693 if (SVOp->isSplat())
6694 return PromoteSplat(SVOp, DAG);
6696 // If we have SSSE3, case 1 is generated when all result bytes come from
6697 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
6698 // present, fall back to case 3.
6700 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6701 if (Subtarget->hasSSSE3()) {
6702 SmallVector<SDValue,16> pshufbMask;
6704 // If all result elements are from one input vector, then only translate
6705 // undef mask values to 0x80 (zero out result) in the pshufb mask.
6707 // Otherwise, we have elements from both input vectors, and must zero out
6708 // elements that come from V2 in the first mask, and V1 in the second mask
6709 // so that we can OR them together.
6710 for (unsigned i = 0; i != 16; ++i) {
6711 int EltIdx = MaskVals[i];
6712 if (EltIdx < 0 || EltIdx >= 16)
6714 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6716 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6717 DAG.getNode(ISD::BUILD_VECTOR, dl,
6718 MVT::v16i8, &pshufbMask[0], 16));
6720 // As PSHUFB will zero elements with negative indices, it's safe to ignore
6721 // the 2nd operand if it's undefined or zero.
6722 if (V2.getOpcode() == ISD::UNDEF ||
6723 ISD::isBuildVectorAllZeros(V2.getNode()))
6726 // Calculate the shuffle mask for the second input, shuffle it, and
6727 // OR it with the first shuffled input.
6729 for (unsigned i = 0; i != 16; ++i) {
6730 int EltIdx = MaskVals[i];
6731 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6732 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6734 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6735 DAG.getNode(ISD::BUILD_VECTOR, dl,
6736 MVT::v16i8, &pshufbMask[0], 16));
6737 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6740 // No SSSE3 - Calculate in place words and then fix all out of place words
6741 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
6742 // the 16 different words that comprise the two doublequadword input vectors.
6743 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6744 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6746 for (int i = 0; i != 8; ++i) {
6747 int Elt0 = MaskVals[i*2];
6748 int Elt1 = MaskVals[i*2+1];
6750 // This word of the result is all undef, skip it.
6751 if (Elt0 < 0 && Elt1 < 0)
6754 // This word of the result is already in the correct place, skip it.
6755 if ((Elt0 == i*2) && (Elt1 == i*2+1))
6758 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6759 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6762 // If Elt0 and Elt1 are defined, are consecutive, and can be load
6763 // using a single extract together, load it and store it.
6764 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6765 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6766 DAG.getIntPtrConstant(Elt1 / 2));
6767 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6768 DAG.getIntPtrConstant(i));
6772 // If Elt1 is defined, extract it from the appropriate source. If the
6773 // source byte is not also odd, shift the extracted word left 8 bits
6774 // otherwise clear the bottom 8 bits if we need to do an or.
6776 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6777 DAG.getIntPtrConstant(Elt1 / 2));
6778 if ((Elt1 & 1) == 0)
6779 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6781 TLI.getShiftAmountTy(InsElt.getValueType())));
6783 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6784 DAG.getConstant(0xFF00, MVT::i16));
6786 // If Elt0 is defined, extract it from the appropriate source. If the
6787 // source byte is not also even, shift the extracted word right 8 bits. If
6788 // Elt1 was also defined, OR the extracted values together before
6789 // inserting them in the result.
6791 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6792 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6793 if ((Elt0 & 1) != 0)
6794 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6796 TLI.getShiftAmountTy(InsElt0.getValueType())));
6798 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6799 DAG.getConstant(0x00FF, MVT::i16));
6800 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6803 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6804 DAG.getIntPtrConstant(i));
6806 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6809 // v32i8 shuffles - Translate to VPSHUFB if possible.
6811 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6812 const X86Subtarget *Subtarget,
6813 SelectionDAG &DAG) {
6814 MVT VT = SVOp->getSimpleValueType(0);
6815 SDValue V1 = SVOp->getOperand(0);
6816 SDValue V2 = SVOp->getOperand(1);
6818 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6820 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6821 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6822 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6824 // VPSHUFB may be generated if
6825 // (1) one of input vector is undefined or zeroinitializer.
6826 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6827 // And (2) the mask indexes don't cross the 128-bit lane.
6828 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6829 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6832 if (V1IsAllZero && !V2IsAllZero) {
6833 CommuteVectorShuffleMask(MaskVals, 32);
6836 return getPSHUFB(MaskVals, V1, dl, DAG);
6839 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6840 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6841 /// done when every pair / quad of shuffle mask elements point to elements in
6842 /// the right sequence. e.g.
6843 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6845 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6846 SelectionDAG &DAG) {
6847 MVT VT = SVOp->getSimpleValueType(0);
6849 unsigned NumElems = VT.getVectorNumElements();
6852 switch (VT.SimpleTy) {
6853 default: llvm_unreachable("Unexpected!");
6854 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
6855 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
6856 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
6857 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
6858 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6859 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
6862 SmallVector<int, 8> MaskVec;
6863 for (unsigned i = 0; i != NumElems; i += Scale) {
6865 for (unsigned j = 0; j != Scale; ++j) {
6866 int EltIdx = SVOp->getMaskElt(i+j);
6870 StartIdx = (EltIdx / Scale);
6871 if (EltIdx != (int)(StartIdx*Scale + j))
6874 MaskVec.push_back(StartIdx);
6877 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6878 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6879 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6882 /// getVZextMovL - Return a zero-extending vector move low node.
6884 static SDValue getVZextMovL(MVT VT, MVT OpVT,
6885 SDValue SrcOp, SelectionDAG &DAG,
6886 const X86Subtarget *Subtarget, SDLoc dl) {
6887 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6888 LoadSDNode *LD = nullptr;
6889 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6890 LD = dyn_cast<LoadSDNode>(SrcOp);
6892 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6894 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6895 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6896 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6897 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6898 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6900 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6901 return DAG.getNode(ISD::BITCAST, dl, VT,
6902 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6903 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6911 return DAG.getNode(ISD::BITCAST, dl, VT,
6912 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6913 DAG.getNode(ISD::BITCAST, dl,
6917 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6918 /// which could not be matched by any known target speficic shuffle
6920 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6922 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6923 if (NewOp.getNode())
6926 MVT VT = SVOp->getSimpleValueType(0);
6928 unsigned NumElems = VT.getVectorNumElements();
6929 unsigned NumLaneElems = NumElems / 2;
6932 MVT EltVT = VT.getVectorElementType();
6933 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6936 SmallVector<int, 16> Mask;
6937 for (unsigned l = 0; l < 2; ++l) {
6938 // Build a shuffle mask for the output, discovering on the fly which
6939 // input vectors to use as shuffle operands (recorded in InputUsed).
6940 // If building a suitable shuffle vector proves too hard, then bail
6941 // out with UseBuildVector set.
6942 bool UseBuildVector = false;
6943 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6944 unsigned LaneStart = l * NumLaneElems;
6945 for (unsigned i = 0; i != NumLaneElems; ++i) {
6946 // The mask element. This indexes into the input.
6947 int Idx = SVOp->getMaskElt(i+LaneStart);
6949 // the mask element does not index into any input vector.
6954 // The input vector this mask element indexes into.
6955 int Input = Idx / NumLaneElems;
6957 // Turn the index into an offset from the start of the input vector.
6958 Idx -= Input * NumLaneElems;
6960 // Find or create a shuffle vector operand to hold this input.
6962 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6963 if (InputUsed[OpNo] == Input)
6964 // This input vector is already an operand.
6966 if (InputUsed[OpNo] < 0) {
6967 // Create a new operand for this input vector.
6968 InputUsed[OpNo] = Input;
6973 if (OpNo >= array_lengthof(InputUsed)) {
6974 // More than two input vectors used! Give up on trying to create a
6975 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
6976 UseBuildVector = true;
6980 // Add the mask index for the new shuffle vector.
6981 Mask.push_back(Idx + OpNo * NumLaneElems);
6984 if (UseBuildVector) {
6985 SmallVector<SDValue, 16> SVOps;
6986 for (unsigned i = 0; i != NumLaneElems; ++i) {
6987 // The mask element. This indexes into the input.
6988 int Idx = SVOp->getMaskElt(i+LaneStart);
6990 SVOps.push_back(DAG.getUNDEF(EltVT));
6994 // The input vector this mask element indexes into.
6995 int Input = Idx / NumElems;
6997 // Turn the index into an offset from the start of the input vector.
6998 Idx -= Input * NumElems;
7000 // Extract the vector element by hand.
7001 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
7002 SVOp->getOperand(Input),
7003 DAG.getIntPtrConstant(Idx)));
7006 // Construct the output using a BUILD_VECTOR.
7007 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
7009 } else if (InputUsed[0] < 0) {
7010 // No input vectors were used! The result is undefined.
7011 Output[l] = DAG.getUNDEF(NVT);
7013 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
7014 (InputUsed[0] % 2) * NumLaneElems,
7016 // If only one input was used, use an undefined vector for the other.
7017 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
7018 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
7019 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
7020 // At least one input vector was used. Create a new shuffle vector.
7021 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
7027 // Concatenate the result back
7028 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
7031 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
7032 /// 4 elements, and match them with several different shuffle types.
7034 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7035 SDValue V1 = SVOp->getOperand(0);
7036 SDValue V2 = SVOp->getOperand(1);
7038 MVT VT = SVOp->getSimpleValueType(0);
7040 assert(VT.is128BitVector() && "Unsupported vector size");
7042 std::pair<int, int> Locs[4];
7043 int Mask1[] = { -1, -1, -1, -1 };
7044 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
7048 for (unsigned i = 0; i != 4; ++i) {
7049 int Idx = PermMask[i];
7051 Locs[i] = std::make_pair(-1, -1);
7053 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
7055 Locs[i] = std::make_pair(0, NumLo);
7059 Locs[i] = std::make_pair(1, NumHi);
7061 Mask1[2+NumHi] = Idx;
7067 if (NumLo <= 2 && NumHi <= 2) {
7068 // If no more than two elements come from either vector. This can be
7069 // implemented with two shuffles. First shuffle gather the elements.
7070 // The second shuffle, which takes the first shuffle as both of its
7071 // vector operands, put the elements into the right order.
7072 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7074 int Mask2[] = { -1, -1, -1, -1 };
7076 for (unsigned i = 0; i != 4; ++i)
7077 if (Locs[i].first != -1) {
7078 unsigned Idx = (i < 2) ? 0 : 4;
7079 Idx += Locs[i].first * 2 + Locs[i].second;
7083 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
7086 if (NumLo == 3 || NumHi == 3) {
7087 // Otherwise, we must have three elements from one vector, call it X, and
7088 // one element from the other, call it Y. First, use a shufps to build an
7089 // intermediate vector with the one element from Y and the element from X
7090 // that will be in the same half in the final destination (the indexes don't
7091 // matter). Then, use a shufps to build the final vector, taking the half
7092 // containing the element from Y from the intermediate, and the other half
7095 // Normalize it so the 3 elements come from V1.
7096 CommuteVectorShuffleMask(PermMask, 4);
7100 // Find the element from V2.
7102 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
7103 int Val = PermMask[HiIndex];
7110 Mask1[0] = PermMask[HiIndex];
7112 Mask1[2] = PermMask[HiIndex^1];
7114 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7117 Mask1[0] = PermMask[0];
7118 Mask1[1] = PermMask[1];
7119 Mask1[2] = HiIndex & 1 ? 6 : 4;
7120 Mask1[3] = HiIndex & 1 ? 4 : 6;
7121 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7124 Mask1[0] = HiIndex & 1 ? 2 : 0;
7125 Mask1[1] = HiIndex & 1 ? 0 : 2;
7126 Mask1[2] = PermMask[2];
7127 Mask1[3] = PermMask[3];
7132 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7135 // Break it into (shuffle shuffle_hi, shuffle_lo).
7136 int LoMask[] = { -1, -1, -1, -1 };
7137 int HiMask[] = { -1, -1, -1, -1 };
7139 int *MaskPtr = LoMask;
7140 unsigned MaskIdx = 0;
7143 for (unsigned i = 0; i != 4; ++i) {
7150 int Idx = PermMask[i];
7152 Locs[i] = std::make_pair(-1, -1);
7153 } else if (Idx < 4) {
7154 Locs[i] = std::make_pair(MaskIdx, LoIdx);
7155 MaskPtr[LoIdx] = Idx;
7158 Locs[i] = std::make_pair(MaskIdx, HiIdx);
7159 MaskPtr[HiIdx] = Idx;
7164 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7165 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7166 int MaskOps[] = { -1, -1, -1, -1 };
7167 for (unsigned i = 0; i != 4; ++i)
7168 if (Locs[i].first != -1)
7169 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7170 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7173 static bool MayFoldVectorLoad(SDValue V) {
7174 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7175 V = V.getOperand(0);
7177 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7178 V = V.getOperand(0);
7179 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7180 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7181 // BUILD_VECTOR (load), undef
7182 V = V.getOperand(0);
7184 return MayFoldLoad(V);
7188 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7189 MVT VT = Op.getSimpleValueType();
7191 // Canonizalize to v2f64.
7192 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7193 return DAG.getNode(ISD::BITCAST, dl, VT,
7194 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7199 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7201 SDValue V1 = Op.getOperand(0);
7202 SDValue V2 = Op.getOperand(1);
7203 MVT VT = Op.getSimpleValueType();
7205 assert(VT != MVT::v2i64 && "unsupported shuffle type");
7207 if (HasSSE2 && VT == MVT::v2f64)
7208 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7210 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7211 return DAG.getNode(ISD::BITCAST, dl, VT,
7212 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7213 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7214 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7218 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7219 SDValue V1 = Op.getOperand(0);
7220 SDValue V2 = Op.getOperand(1);
7221 MVT VT = Op.getSimpleValueType();
7223 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7224 "unsupported shuffle type");
7226 if (V2.getOpcode() == ISD::UNDEF)
7230 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7234 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7235 SDValue V1 = Op.getOperand(0);
7236 SDValue V2 = Op.getOperand(1);
7237 MVT VT = Op.getSimpleValueType();
7238 unsigned NumElems = VT.getVectorNumElements();
7240 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7241 // operand of these instructions is only memory, so check if there's a
7242 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7244 bool CanFoldLoad = false;
7246 // Trivial case, when V2 comes from a load.
7247 if (MayFoldVectorLoad(V2))
7250 // When V1 is a load, it can be folded later into a store in isel, example:
7251 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7253 // (MOVLPSmr addr:$src1, VR128:$src2)
7254 // So, recognize this potential and also use MOVLPS or MOVLPD
7255 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7258 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7260 if (HasSSE2 && NumElems == 2)
7261 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7264 // If we don't care about the second element, proceed to use movss.
7265 if (SVOp->getMaskElt(1) != -1)
7266 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7269 // movl and movlp will both match v2i64, but v2i64 is never matched by
7270 // movl earlier because we make it strict to avoid messing with the movlp load
7271 // folding logic (see the code above getMOVLP call). Match it here then,
7272 // this is horrible, but will stay like this until we move all shuffle
7273 // matching to x86 specific nodes. Note that for the 1st condition all
7274 // types are matched with movsd.
7276 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7277 // as to remove this logic from here, as much as possible
7278 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7279 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7280 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7283 assert(VT != MVT::v4i32 && "unsupported shuffle type");
7285 // Invert the operand order and use SHUFPS to match it.
7286 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7287 getShuffleSHUFImmediate(SVOp), DAG);
7290 // It is only safe to call this function if isINSERTPSMask is true for
7291 // this shufflevector mask.
7292 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
7293 SelectionDAG &DAG) {
7294 // Generate an insertps instruction when inserting an f32 from memory onto a
7295 // v4f32 or when copying a member from one v4f32 to another.
7296 // We also use it for transferring i32 from one register to another,
7297 // since it simply copies the same bits.
7298 // If we're transfering an i32 from memory to a specific element in a
7299 // register, we output a generic DAG that will match the PINSRD
7301 // TODO: Optimize for AVX cases too (VINSERTPS)
7302 MVT VT = SVOp->getSimpleValueType(0);
7303 MVT EVT = VT.getVectorElementType();
7304 SDValue V1 = SVOp->getOperand(0);
7305 SDValue V2 = SVOp->getOperand(1);
7306 auto Mask = SVOp->getMask();
7307 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
7308 "unsupported vector type for insertps/pinsrd");
7310 int FromV1 = std::count_if(Mask.begin(), Mask.end(),
7311 [](const int &i) { return i < 4; });
7319 DestIndex = std::find_if(Mask.begin(), Mask.end(),
7320 [](const int &i) { return i < 4; }) -
7325 DestIndex = std::find_if(Mask.begin(), Mask.end(),
7326 [](const int &i) { return i >= 4; }) -
7330 if (MayFoldLoad(From)) {
7331 // Trivial case, when From comes from a load and is only used by the
7332 // shuffle. Make it use insertps from the vector that we need from that
7334 SDValue Addr = From.getOperand(1);
7336 DAG.getNode(ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
7337 DAG.getConstant(DestIndex * EVT.getStoreSize(),
7338 Addr.getSimpleValueType()));
7340 LoadSDNode *Load = cast<LoadSDNode>(From);
7342 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
7343 DAG.getMachineFunction().getMachineMemOperand(
7344 Load->getMemOperand(), 0, EVT.getStoreSize()));
7346 if (EVT == MVT::f32) {
7347 // Create this as a scalar to vector to match the instruction pattern.
7348 SDValue LoadScalarToVector =
7349 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
7350 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
7351 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
7353 } else { // EVT == MVT::i32
7354 // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
7355 // instruction, to match the PINSRD instruction, which loads an i32 to a
7356 // certain vector element.
7357 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
7358 DAG.getConstant(DestIndex, MVT::i32));
7362 // Vector-element-to-vector
7363 unsigned SrcIndex = Mask[DestIndex] % 4;
7364 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
7365 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
7368 // Reduce a vector shuffle to zext.
7369 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7370 SelectionDAG &DAG) {
7371 // PMOVZX is only available from SSE41.
7372 if (!Subtarget->hasSSE41())
7375 MVT VT = Op.getSimpleValueType();
7377 // Only AVX2 support 256-bit vector integer extending.
7378 if (!Subtarget->hasInt256() && VT.is256BitVector())
7381 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7383 SDValue V1 = Op.getOperand(0);
7384 SDValue V2 = Op.getOperand(1);
7385 unsigned NumElems = VT.getVectorNumElements();
7387 // Extending is an unary operation and the element type of the source vector
7388 // won't be equal to or larger than i64.
7389 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7390 VT.getVectorElementType() == MVT::i64)
7393 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7394 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7395 while ((1U << Shift) < NumElems) {
7396 if (SVOp->getMaskElt(1U << Shift) == 1)
7399 // The maximal ratio is 8, i.e. from i8 to i64.
7404 // Check the shuffle mask.
7405 unsigned Mask = (1U << Shift) - 1;
7406 for (unsigned i = 0; i != NumElems; ++i) {
7407 int EltIdx = SVOp->getMaskElt(i);
7408 if ((i & Mask) != 0 && EltIdx != -1)
7410 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7414 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7415 MVT NeVT = MVT::getIntegerVT(NBits);
7416 MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7418 if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7421 // Simplify the operand as it's prepared to be fed into shuffle.
7422 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7423 if (V1.getOpcode() == ISD::BITCAST &&
7424 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7425 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7426 V1.getOperand(0).getOperand(0)
7427 .getSimpleValueType().getSizeInBits() == SignificantBits) {
7428 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7429 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7430 ConstantSDNode *CIdx =
7431 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7432 // If it's foldable, i.e. normal load with single use, we will let code
7433 // selection to fold it. Otherwise, we will short the conversion sequence.
7434 if (CIdx && CIdx->getZExtValue() == 0 &&
7435 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7436 MVT FullVT = V.getSimpleValueType();
7437 MVT V1VT = V1.getSimpleValueType();
7438 if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7439 // The "ext_vec_elt" node is wider than the result node.
7440 // In this case we should extract subvector from V.
7441 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7442 unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7443 MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7444 FullVT.getVectorNumElements()/Ratio);
7445 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7446 DAG.getIntPtrConstant(0));
7448 V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7452 return DAG.getNode(ISD::BITCAST, DL, VT,
7453 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7457 NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7458 SelectionDAG &DAG) {
7459 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7460 MVT VT = Op.getSimpleValueType();
7462 SDValue V1 = Op.getOperand(0);
7463 SDValue V2 = Op.getOperand(1);
7465 if (isZeroShuffle(SVOp))
7466 return getZeroVector(VT, Subtarget, DAG, dl);
7468 // Handle splat operations
7469 if (SVOp->isSplat()) {
7470 // Use vbroadcast whenever the splat comes from a foldable load
7471 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7472 if (Broadcast.getNode())
7476 // Check integer expanding shuffles.
7477 SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7478 if (NewOp.getNode())
7481 // If the shuffle can be profitably rewritten as a narrower shuffle, then
7483 if (VT == MVT::v8i16 || VT == MVT::v16i8 ||
7484 VT == MVT::v16i16 || VT == MVT::v32i8) {
7485 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7486 if (NewOp.getNode())
7487 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7488 } else if ((VT == MVT::v4i32 ||
7489 (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
7490 // FIXME: Figure out a cleaner way to do this.
7491 // Try to make use of movq to zero out the top part.
7492 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7493 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7494 if (NewOp.getNode()) {
7495 MVT NewVT = NewOp.getSimpleValueType();
7496 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7497 NewVT, true, false))
7498 return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
7499 DAG, Subtarget, dl);
7501 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7502 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7503 if (NewOp.getNode()) {
7504 MVT NewVT = NewOp.getSimpleValueType();
7505 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7506 return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
7507 DAG, Subtarget, dl);
7515 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7516 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7517 SDValue V1 = Op.getOperand(0);
7518 SDValue V2 = Op.getOperand(1);
7519 MVT VT = Op.getSimpleValueType();
7521 unsigned NumElems = VT.getVectorNumElements();
7522 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7523 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7524 bool V1IsSplat = false;
7525 bool V2IsSplat = false;
7526 bool HasSSE2 = Subtarget->hasSSE2();
7527 bool HasFp256 = Subtarget->hasFp256();
7528 bool HasInt256 = Subtarget->hasInt256();
7529 MachineFunction &MF = DAG.getMachineFunction();
7530 bool OptForSize = MF.getFunction()->getAttributes().
7531 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7533 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7535 if (V1IsUndef && V2IsUndef)
7536 return DAG.getUNDEF(VT);
7538 // When we create a shuffle node we put the UNDEF node to second operand,
7539 // but in some cases the first operand may be transformed to UNDEF.
7540 // In this case we should just commute the node.
7542 return CommuteVectorShuffle(SVOp, DAG);
7544 // Vector shuffle lowering takes 3 steps:
7546 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7547 // narrowing and commutation of operands should be handled.
7548 // 2) Matching of shuffles with known shuffle masks to x86 target specific
7550 // 3) Rewriting of unmatched masks into new generic shuffle operations,
7551 // so the shuffle can be broken into other shuffles and the legalizer can
7552 // try the lowering again.
7554 // The general idea is that no vector_shuffle operation should be left to
7555 // be matched during isel, all of them must be converted to a target specific
7558 // Normalize the input vectors. Here splats, zeroed vectors, profitable
7559 // narrowing and commutation of operands should be handled. The actual code
7560 // doesn't include all of those, work in progress...
7561 SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7562 if (NewOp.getNode())
7565 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7567 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7568 // unpckh_undef). Only use pshufd if speed is more important than size.
7569 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7570 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7571 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7572 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7574 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7575 V2IsUndef && MayFoldVectorLoad(V1))
7576 return getMOVDDup(Op, dl, V1, DAG);
7578 if (isMOVHLPS_v_undef_Mask(M, VT))
7579 return getMOVHighToLow(Op, dl, DAG);
7581 // Use to match splats
7582 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7583 (VT == MVT::v2f64 || VT == MVT::v2i64))
7584 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7586 if (isPSHUFDMask(M, VT)) {
7587 // The actual implementation will match the mask in the if above and then
7588 // during isel it can match several different instructions, not only pshufd
7589 // as its name says, sad but true, emulate the behavior for now...
7590 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7591 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7593 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7595 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7596 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7598 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7599 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7602 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7606 if (isPALIGNRMask(M, VT, Subtarget))
7607 return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7608 getShufflePALIGNRImmediate(SVOp),
7611 // Check if this can be converted into a logical shift.
7612 bool isLeft = false;
7615 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7616 if (isShift && ShVal.hasOneUse()) {
7617 // If the shifted value has multiple uses, it may be cheaper to use
7618 // v_set0 + movlhps or movhlps, etc.
7619 MVT EltVT = VT.getVectorElementType();
7620 ShAmt *= EltVT.getSizeInBits();
7621 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7624 if (isMOVLMask(M, VT)) {
7625 if (ISD::isBuildVectorAllZeros(V1.getNode()))
7626 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7627 if (!isMOVLPMask(M, VT)) {
7628 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7629 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7631 if (VT == MVT::v4i32 || VT == MVT::v4f32)
7632 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7636 // FIXME: fold these into legal mask.
7637 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7638 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7640 if (isMOVHLPSMask(M, VT))
7641 return getMOVHighToLow(Op, dl, DAG);
7643 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7644 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7646 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7647 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7649 if (isMOVLPMask(M, VT))
7650 return getMOVLP(Op, dl, DAG, HasSSE2);
7652 if (ShouldXformToMOVHLPS(M, VT) ||
7653 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7654 return CommuteVectorShuffle(SVOp, DAG);
7657 // No better options. Use a vshldq / vsrldq.
7658 MVT EltVT = VT.getVectorElementType();
7659 ShAmt *= EltVT.getSizeInBits();
7660 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7663 bool Commuted = false;
7664 // FIXME: This should also accept a bitcast of a splat? Be careful, not
7665 // 1,1,1,1 -> v8i16 though.
7666 V1IsSplat = isSplatVector(V1.getNode());
7667 V2IsSplat = isSplatVector(V2.getNode());
7669 // Canonicalize the splat or undef, if present, to be on the RHS.
7670 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7671 CommuteVectorShuffleMask(M, NumElems);
7673 std::swap(V1IsSplat, V2IsSplat);
7677 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7678 // Shuffling low element of v1 into undef, just return v1.
7681 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7682 // the instruction selector will not match, so get a canonical MOVL with
7683 // swapped operands to undo the commute.
7684 return getMOVL(DAG, dl, VT, V2, V1);
7687 if (isUNPCKLMask(M, VT, HasInt256))
7688 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7690 if (isUNPCKHMask(M, VT, HasInt256))
7691 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7694 // Normalize mask so all entries that point to V2 points to its first
7695 // element then try to match unpck{h|l} again. If match, return a
7696 // new vector_shuffle with the corrected mask.p
7697 SmallVector<int, 8> NewMask(M.begin(), M.end());
7698 NormalizeMask(NewMask, NumElems);
7699 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7700 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7701 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7702 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7706 // Commute is back and try unpck* again.
7707 // FIXME: this seems wrong.
7708 CommuteVectorShuffleMask(M, NumElems);
7710 std::swap(V1IsSplat, V2IsSplat);
7712 if (isUNPCKLMask(M, VT, HasInt256))
7713 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7715 if (isUNPCKHMask(M, VT, HasInt256))
7716 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7719 // Normalize the node to match x86 shuffle ops if needed
7720 if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
7721 return CommuteVectorShuffle(SVOp, DAG);
7723 // The checks below are all present in isShuffleMaskLegal, but they are
7724 // inlined here right now to enable us to directly emit target specific
7725 // nodes, and remove one by one until they don't return Op anymore.
7727 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7728 SVOp->getSplatIndex() == 0 && V2IsUndef) {
7729 if (VT == MVT::v2f64 || VT == MVT::v2i64)
7730 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7733 if (isPSHUFHWMask(M, VT, HasInt256))
7734 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7735 getShufflePSHUFHWImmediate(SVOp),
7738 if (isPSHUFLWMask(M, VT, HasInt256))
7739 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7740 getShufflePSHUFLWImmediate(SVOp),
7743 if (isSHUFPMask(M, VT))
7744 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7745 getShuffleSHUFImmediate(SVOp), DAG);
7747 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7748 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7749 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7750 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7752 //===--------------------------------------------------------------------===//
7753 // Generate target specific nodes for 128 or 256-bit shuffles only
7754 // supported in the AVX instruction set.
7757 // Handle VMOVDDUPY permutations
7758 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7759 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7761 // Handle VPERMILPS/D* permutations
7762 if (isVPERMILPMask(M, VT)) {
7763 if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
7764 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7765 getShuffleSHUFImmediate(SVOp), DAG);
7766 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7767 getShuffleSHUFImmediate(SVOp), DAG);
7770 // Handle VPERM2F128/VPERM2I128 permutations
7771 if (isVPERM2X128Mask(M, VT, HasFp256))
7772 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7773 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7775 SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7776 if (BlendOp.getNode())
7779 if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
7780 return getINSERTPS(SVOp, dl, DAG);
7783 if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
7784 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
7786 if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
7787 VT.is512BitVector()) {
7788 MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
7789 MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
7790 SmallVector<SDValue, 16> permclMask;
7791 for (unsigned i = 0; i != NumElems; ++i) {
7792 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
7795 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT,
7796 &permclMask[0], NumElems);
7798 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7799 return DAG.getNode(X86ISD::VPERMV, dl, VT,
7800 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7801 return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
7802 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
7805 //===--------------------------------------------------------------------===//
7806 // Since no target specific shuffle was selected for this generic one,
7807 // lower it into other known shuffles. FIXME: this isn't true yet, but
7808 // this is the plan.
7811 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7812 if (VT == MVT::v8i16) {
7813 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7814 if (NewOp.getNode())
7818 if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
7819 SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
7820 if (NewOp.getNode())
7824 if (VT == MVT::v16i8) {
7825 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
7826 if (NewOp.getNode())
7830 if (VT == MVT::v32i8) {
7831 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7832 if (NewOp.getNode())
7836 // Handle all 128-bit wide vectors with 4 elements, and match them with
7837 // several different shuffle types.
7838 if (NumElems == 4 && VT.is128BitVector())
7839 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7841 // Handle general 256-bit shuffles
7842 if (VT.is256BitVector())
7843 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7848 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7849 MVT VT = Op.getSimpleValueType();
7852 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
7855 if (VT.getSizeInBits() == 8) {
7856 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7857 Op.getOperand(0), Op.getOperand(1));
7858 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7859 DAG.getValueType(VT));
7860 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7863 if (VT.getSizeInBits() == 16) {
7864 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7865 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7867 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7868 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7869 DAG.getNode(ISD::BITCAST, dl,
7873 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7874 Op.getOperand(0), Op.getOperand(1));
7875 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7876 DAG.getValueType(VT));
7877 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7880 if (VT == MVT::f32) {
7881 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7882 // the result back to FR32 register. It's only worth matching if the
7883 // result has a single use which is a store or a bitcast to i32. And in
7884 // the case of a store, it's not worth it if the index is a constant 0,
7885 // because a MOVSSmr can be used instead, which is smaller and faster.
7886 if (!Op.hasOneUse())
7888 SDNode *User = *Op.getNode()->use_begin();
7889 if ((User->getOpcode() != ISD::STORE ||
7890 (isa<ConstantSDNode>(Op.getOperand(1)) &&
7891 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7892 (User->getOpcode() != ISD::BITCAST ||
7893 User->getValueType(0) != MVT::i32))
7895 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7896 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7899 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7902 if (VT == MVT::i32 || VT == MVT::i64) {
7903 // ExtractPS/pextrq works with constant index.
7904 if (isa<ConstantSDNode>(Op.getOperand(1)))
7910 /// Extract one bit from mask vector, like v16i1 or v8i1.
7911 /// AVX-512 feature.
7913 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
7914 SDValue Vec = Op.getOperand(0);
7916 MVT VecVT = Vec.getSimpleValueType();
7917 SDValue Idx = Op.getOperand(1);
7918 MVT EltVT = Op.getSimpleValueType();
7920 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
7922 // variable index can't be handled in mask registers,
7923 // extend vector to VR512
7924 if (!isa<ConstantSDNode>(Idx)) {
7925 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
7926 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
7927 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
7928 ExtVT.getVectorElementType(), Ext, Idx);
7929 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
7932 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7933 const TargetRegisterClass* rc = getRegClassFor(VecVT);
7934 unsigned MaxSift = rc->getSize()*8 - 1;
7935 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
7936 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
7937 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
7938 DAG.getConstant(MaxSift, MVT::i8));
7939 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
7940 DAG.getIntPtrConstant(0));
7944 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7945 SelectionDAG &DAG) const {
7947 SDValue Vec = Op.getOperand(0);
7948 MVT VecVT = Vec.getSimpleValueType();
7949 SDValue Idx = Op.getOperand(1);
7951 if (Op.getSimpleValueType() == MVT::i1)
7952 return ExtractBitFromMaskVector(Op, DAG);
7954 if (!isa<ConstantSDNode>(Idx)) {
7955 if (VecVT.is512BitVector() ||
7956 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
7957 VecVT.getVectorElementType().getSizeInBits() == 32)) {
7960 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
7961 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
7962 MaskEltVT.getSizeInBits());
7964 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
7965 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
7966 getZeroVector(MaskVT, Subtarget, DAG, dl),
7967 Idx, DAG.getConstant(0, getPointerTy()));
7968 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
7969 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
7970 Perm, DAG.getConstant(0, getPointerTy()));
7975 // If this is a 256-bit vector result, first extract the 128-bit vector and
7976 // then extract the element from the 128-bit vector.
7977 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
7979 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7980 // Get the 128-bit vector.
7981 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7982 MVT EltVT = VecVT.getVectorElementType();
7984 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
7986 //if (IdxVal >= NumElems/2)
7987 // IdxVal -= NumElems/2;
7988 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
7989 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7990 DAG.getConstant(IdxVal, MVT::i32));
7993 assert(VecVT.is128BitVector() && "Unexpected vector length");
7995 if (Subtarget->hasSSE41()) {
7996 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
8001 MVT VT = Op.getSimpleValueType();
8002 // TODO: handle v16i8.
8003 if (VT.getSizeInBits() == 16) {
8004 SDValue Vec = Op.getOperand(0);
8005 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8007 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8008 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8009 DAG.getNode(ISD::BITCAST, dl,
8012 // Transform it so it match pextrw which produces a 32-bit result.
8013 MVT EltVT = MVT::i32;
8014 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
8015 Op.getOperand(0), Op.getOperand(1));
8016 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
8017 DAG.getValueType(VT));
8018 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8021 if (VT.getSizeInBits() == 32) {
8022 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8026 // SHUFPS the element to the lowest double word, then movss.
8027 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
8028 MVT VVT = Op.getOperand(0).getSimpleValueType();
8029 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8030 DAG.getUNDEF(VVT), Mask);
8031 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8032 DAG.getIntPtrConstant(0));
8035 if (VT.getSizeInBits() == 64) {
8036 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
8037 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
8038 // to match extract_elt for f64.
8039 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8043 // UNPCKHPD the element to the lowest double word, then movsd.
8044 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
8045 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
8046 int Mask[2] = { 1, -1 };
8047 MVT VVT = Op.getOperand(0).getSimpleValueType();
8048 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8049 DAG.getUNDEF(VVT), Mask);
8050 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8051 DAG.getIntPtrConstant(0));
8057 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8058 MVT VT = Op.getSimpleValueType();
8059 MVT EltVT = VT.getVectorElementType();
8062 SDValue N0 = Op.getOperand(0);
8063 SDValue N1 = Op.getOperand(1);
8064 SDValue N2 = Op.getOperand(2);
8066 if (!VT.is128BitVector())
8069 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
8070 isa<ConstantSDNode>(N2)) {
8072 if (VT == MVT::v8i16)
8073 Opc = X86ISD::PINSRW;
8074 else if (VT == MVT::v16i8)
8075 Opc = X86ISD::PINSRB;
8077 Opc = X86ISD::PINSRB;
8079 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
8081 if (N1.getValueType() != MVT::i32)
8082 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8083 if (N2.getValueType() != MVT::i32)
8084 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8085 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
8088 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
8089 // Bits [7:6] of the constant are the source select. This will always be
8090 // zero here. The DAG Combiner may combine an extract_elt index into these
8091 // bits. For example (insert (extract, 3), 2) could be matched by putting
8092 // the '3' into bits [7:6] of X86ISD::INSERTPS.
8093 // Bits [5:4] of the constant are the destination select. This is the
8094 // value of the incoming immediate.
8095 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
8096 // combine either bitwise AND or insert of float 0.0 to set these bits.
8097 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
8098 // Create this as a scalar to vector..
8099 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
8100 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
8103 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
8104 // PINSR* works with constant index.
8110 /// Insert one bit to mask vector, like v16i1 or v8i1.
8111 /// AVX-512 feature.
8113 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
8115 SDValue Vec = Op.getOperand(0);
8116 SDValue Elt = Op.getOperand(1);
8117 SDValue Idx = Op.getOperand(2);
8118 MVT VecVT = Vec.getSimpleValueType();
8120 if (!isa<ConstantSDNode>(Idx)) {
8121 // Non constant index. Extend source and destination,
8122 // insert element and then truncate the result.
8123 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
8124 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
8125 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
8126 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
8127 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
8128 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
8131 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8132 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
8133 if (Vec.getOpcode() == ISD::UNDEF)
8134 return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8135 DAG.getConstant(IdxVal, MVT::i8));
8136 const TargetRegisterClass* rc = getRegClassFor(VecVT);
8137 unsigned MaxSift = rc->getSize()*8 - 1;
8138 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8139 DAG.getConstant(MaxSift, MVT::i8));
8140 EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
8141 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8142 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
8145 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
8146 MVT VT = Op.getSimpleValueType();
8147 MVT EltVT = VT.getVectorElementType();
8149 if (EltVT == MVT::i1)
8150 return InsertBitToMaskVector(Op, DAG);
8153 SDValue N0 = Op.getOperand(0);
8154 SDValue N1 = Op.getOperand(1);
8155 SDValue N2 = Op.getOperand(2);
8157 // If this is a 256-bit vector result, first extract the 128-bit vector,
8158 // insert the element into the extracted half and then place it back.
8159 if (VT.is256BitVector() || VT.is512BitVector()) {
8160 if (!isa<ConstantSDNode>(N2))
8163 // Get the desired 128-bit vector half.
8164 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
8165 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
8167 // Insert the element into the desired half.
8168 unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
8169 unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
8171 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
8172 DAG.getConstant(IdxIn128, MVT::i32));
8174 // Insert the changed part back to the 256-bit vector
8175 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
8178 if (Subtarget->hasSSE41())
8179 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
8181 if (EltVT == MVT::i8)
8184 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
8185 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
8186 // as its second argument.
8187 if (N1.getValueType() != MVT::i32)
8188 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8189 if (N2.getValueType() != MVT::i32)
8190 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8191 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
8196 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
8198 MVT OpVT = Op.getSimpleValueType();
8200 // If this is a 256-bit vector result, first insert into a 128-bit
8201 // vector and then insert into the 256-bit vector.
8202 if (!OpVT.is128BitVector()) {
8203 // Insert into a 128-bit vector.
8204 unsigned SizeFactor = OpVT.getSizeInBits()/128;
8205 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
8206 OpVT.getVectorNumElements() / SizeFactor);
8208 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
8210 // Insert the 128-bit vector.
8211 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
8214 if (OpVT == MVT::v1i64 &&
8215 Op.getOperand(0).getValueType() == MVT::i64)
8216 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
8218 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
8219 assert(OpVT.is128BitVector() && "Expected an SSE type!");
8220 return DAG.getNode(ISD::BITCAST, dl, OpVT,
8221 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
8224 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
8225 // a simple subregister reference or explicit instructions to grab
8226 // upper bits of a vector.
8227 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8228 SelectionDAG &DAG) {
8230 SDValue In = Op.getOperand(0);
8231 SDValue Idx = Op.getOperand(1);
8232 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8233 MVT ResVT = Op.getSimpleValueType();
8234 MVT InVT = In.getSimpleValueType();
8236 if (Subtarget->hasFp256()) {
8237 if (ResVT.is128BitVector() &&
8238 (InVT.is256BitVector() || InVT.is512BitVector()) &&
8239 isa<ConstantSDNode>(Idx)) {
8240 return Extract128BitVector(In, IdxVal, DAG, dl);
8242 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
8243 isa<ConstantSDNode>(Idx)) {
8244 return Extract256BitVector(In, IdxVal, DAG, dl);
8250 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
8251 // simple superregister reference or explicit instructions to insert
8252 // the upper bits of a vector.
8253 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8254 SelectionDAG &DAG) {
8255 if (Subtarget->hasFp256()) {
8256 SDLoc dl(Op.getNode());
8257 SDValue Vec = Op.getNode()->getOperand(0);
8258 SDValue SubVec = Op.getNode()->getOperand(1);
8259 SDValue Idx = Op.getNode()->getOperand(2);
8261 if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8262 Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8263 SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8264 isa<ConstantSDNode>(Idx)) {
8265 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8266 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8269 if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8270 SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8271 isa<ConstantSDNode>(Idx)) {
8272 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8273 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8279 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8280 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8281 // one of the above mentioned nodes. It has to be wrapped because otherwise
8282 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8283 // be used to form addressing mode. These wrapped nodes will be selected
8286 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8287 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8289 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8291 unsigned char OpFlag = 0;
8292 unsigned WrapperKind = X86ISD::Wrapper;
8293 CodeModel::Model M = getTargetMachine().getCodeModel();
8295 if (Subtarget->isPICStyleRIPRel() &&
8296 (M == CodeModel::Small || M == CodeModel::Kernel))
8297 WrapperKind = X86ISD::WrapperRIP;
8298 else if (Subtarget->isPICStyleGOT())
8299 OpFlag = X86II::MO_GOTOFF;
8300 else if (Subtarget->isPICStyleStubPIC())
8301 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8303 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8305 CP->getOffset(), OpFlag);
8307 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8308 // With PIC, the address is actually $g + Offset.
8310 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8311 DAG.getNode(X86ISD::GlobalBaseReg,
8312 SDLoc(), getPointerTy()),
8319 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8320 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8322 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8324 unsigned char OpFlag = 0;
8325 unsigned WrapperKind = X86ISD::Wrapper;
8326 CodeModel::Model M = getTargetMachine().getCodeModel();
8328 if (Subtarget->isPICStyleRIPRel() &&
8329 (M == CodeModel::Small || M == CodeModel::Kernel))
8330 WrapperKind = X86ISD::WrapperRIP;
8331 else if (Subtarget->isPICStyleGOT())
8332 OpFlag = X86II::MO_GOTOFF;
8333 else if (Subtarget->isPICStyleStubPIC())
8334 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8336 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8339 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8341 // With PIC, the address is actually $g + Offset.
8343 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8344 DAG.getNode(X86ISD::GlobalBaseReg,
8345 SDLoc(), getPointerTy()),
8352 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8353 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8355 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8357 unsigned char OpFlag = 0;
8358 unsigned WrapperKind = X86ISD::Wrapper;
8359 CodeModel::Model M = getTargetMachine().getCodeModel();
8361 if (Subtarget->isPICStyleRIPRel() &&
8362 (M == CodeModel::Small || M == CodeModel::Kernel)) {
8363 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8364 OpFlag = X86II::MO_GOTPCREL;
8365 WrapperKind = X86ISD::WrapperRIP;
8366 } else if (Subtarget->isPICStyleGOT()) {
8367 OpFlag = X86II::MO_GOT;
8368 } else if (Subtarget->isPICStyleStubPIC()) {
8369 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8370 } else if (Subtarget->isPICStyleStubNoDynamic()) {
8371 OpFlag = X86II::MO_DARWIN_NONLAZY;
8374 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8377 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8379 // With PIC, the address is actually $g + Offset.
8380 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
8381 !Subtarget->is64Bit()) {
8382 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8383 DAG.getNode(X86ISD::GlobalBaseReg,
8384 SDLoc(), getPointerTy()),
8388 // For symbols that require a load from a stub to get the address, emit the
8390 if (isGlobalStubReference(OpFlag))
8391 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8392 MachinePointerInfo::getGOT(), false, false, false, 0);
8398 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8399 // Create the TargetBlockAddressAddress node.
8400 unsigned char OpFlags =
8401 Subtarget->ClassifyBlockAddressReference();
8402 CodeModel::Model M = getTargetMachine().getCodeModel();
8403 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8404 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8406 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8409 if (Subtarget->isPICStyleRIPRel() &&
8410 (M == CodeModel::Small || M == CodeModel::Kernel))
8411 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8413 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8415 // With PIC, the address is actually $g + Offset.
8416 if (isGlobalRelativeToPICBase(OpFlags)) {
8417 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8418 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8426 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8427 int64_t Offset, SelectionDAG &DAG) const {
8428 // Create the TargetGlobalAddress node, folding in the constant
8429 // offset if it is legal.
8430 unsigned char OpFlags =
8431 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
8432 CodeModel::Model M = getTargetMachine().getCodeModel();
8434 if (OpFlags == X86II::MO_NO_FLAG &&
8435 X86::isOffsetSuitableForCodeModel(Offset, M)) {
8436 // A direct static reference to a global.
8437 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8440 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8443 if (Subtarget->isPICStyleRIPRel() &&
8444 (M == CodeModel::Small || M == CodeModel::Kernel))
8445 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8447 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8449 // With PIC, the address is actually $g + Offset.
8450 if (isGlobalRelativeToPICBase(OpFlags)) {
8451 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8452 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8456 // For globals that require a load from a stub to get the address, emit the
8458 if (isGlobalStubReference(OpFlags))
8459 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8460 MachinePointerInfo::getGOT(), false, false, false, 0);
8462 // If there was a non-zero offset that we didn't fold, create an explicit
8465 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8466 DAG.getConstant(Offset, getPointerTy()));
8472 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8473 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8474 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8475 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8479 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8480 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8481 unsigned char OperandFlags, bool LocalDynamic = false) {
8482 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8483 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8485 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8486 GA->getValueType(0),
8490 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8494 SDValue Ops[] = { Chain, TGA, *InFlag };
8495 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8497 SDValue Ops[] = { Chain, TGA };
8498 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8501 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8502 MFI->setAdjustsStack(true);
8504 SDValue Flag = Chain.getValue(1);
8505 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8508 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8510 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8513 SDLoc dl(GA); // ? function entry point might be better
8514 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8515 DAG.getNode(X86ISD::GlobalBaseReg,
8516 SDLoc(), PtrVT), InFlag);
8517 InFlag = Chain.getValue(1);
8519 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8522 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8524 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8526 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
8527 X86::RAX, X86II::MO_TLSGD);
8530 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8536 // Get the start address of the TLS block for this module.
8537 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8538 .getInfo<X86MachineFunctionInfo>();
8539 MFI->incNumLocalDynamicTLSAccesses();
8543 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
8544 X86II::MO_TLSLD, /*LocalDynamic=*/true);
8547 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8548 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8549 InFlag = Chain.getValue(1);
8550 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8551 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8554 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8558 unsigned char OperandFlags = X86II::MO_DTPOFF;
8559 unsigned WrapperKind = X86ISD::Wrapper;
8560 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8561 GA->getValueType(0),
8562 GA->getOffset(), OperandFlags);
8563 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8565 // Add x@dtpoff with the base.
8566 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8569 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8570 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8571 const EVT PtrVT, TLSModel::Model model,
8572 bool is64Bit, bool isPIC) {
8575 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8576 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8577 is64Bit ? 257 : 256));
8579 SDValue ThreadPointer =
8580 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
8581 MachinePointerInfo(Ptr), false, false, false, 0);
8583 unsigned char OperandFlags = 0;
8584 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
8586 unsigned WrapperKind = X86ISD::Wrapper;
8587 if (model == TLSModel::LocalExec) {
8588 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8589 } else if (model == TLSModel::InitialExec) {
8591 OperandFlags = X86II::MO_GOTTPOFF;
8592 WrapperKind = X86ISD::WrapperRIP;
8594 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8597 llvm_unreachable("Unexpected model");
8600 // emit "addl x@ntpoff,%eax" (local exec)
8601 // or "addl x@indntpoff,%eax" (initial exec)
8602 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8604 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
8605 GA->getOffset(), OperandFlags);
8606 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8608 if (model == TLSModel::InitialExec) {
8609 if (isPIC && !is64Bit) {
8610 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8611 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8615 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8616 MachinePointerInfo::getGOT(), false, false, false, 0);
8619 // The address of the thread local variable is the add of the thread
8620 // pointer with the offset of the variable.
8621 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8625 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8627 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8628 const GlobalValue *GV = GA->getGlobal();
8630 if (Subtarget->isTargetELF()) {
8631 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8634 case TLSModel::GeneralDynamic:
8635 if (Subtarget->is64Bit())
8636 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8637 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8638 case TLSModel::LocalDynamic:
8639 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8640 Subtarget->is64Bit());
8641 case TLSModel::InitialExec:
8642 case TLSModel::LocalExec:
8643 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8644 Subtarget->is64Bit(),
8645 getTargetMachine().getRelocationModel() == Reloc::PIC_);
8647 llvm_unreachable("Unknown TLS model.");
8650 if (Subtarget->isTargetDarwin()) {
8651 // Darwin only has one model of TLS. Lower to that.
8652 unsigned char OpFlag = 0;
8653 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8654 X86ISD::WrapperRIP : X86ISD::Wrapper;
8656 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8658 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8659 !Subtarget->is64Bit();
8661 OpFlag = X86II::MO_TLVP_PIC_BASE;
8663 OpFlag = X86II::MO_TLVP;
8665 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8666 GA->getValueType(0),
8667 GA->getOffset(), OpFlag);
8668 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8670 // With PIC32, the address is actually $g + Offset.
8672 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8673 DAG.getNode(X86ISD::GlobalBaseReg,
8674 SDLoc(), getPointerTy()),
8677 // Lowering the machine isd will make sure everything is in the right
8679 SDValue Chain = DAG.getEntryNode();
8680 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8681 SDValue Args[] = { Chain, Offset };
8682 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
8684 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8685 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8686 MFI->setAdjustsStack(true);
8688 // And our return value (tls address) is in the standard call return value
8690 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8691 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8695 if (Subtarget->isTargetKnownWindowsMSVC() ||
8696 Subtarget->isTargetWindowsGNU()) {
8697 // Just use the implicit TLS architecture
8698 // Need to generate someting similar to:
8699 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8701 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
8702 // mov rcx, qword [rdx+rcx*8]
8703 // mov eax, .tls$:tlsvar
8704 // [rax+rcx] contains the address
8705 // Windows 64bit: gs:0x58
8706 // Windows 32bit: fs:__tls_array
8708 // If GV is an alias then use the aliasee for determining
8709 // thread-localness.
8710 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
8711 GV = GA->getAliasedGlobal();
8713 SDValue Chain = DAG.getEntryNode();
8715 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8716 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8717 // use its literal value of 0x2C.
8718 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8719 ? Type::getInt8PtrTy(*DAG.getContext(),
8721 : Type::getInt32PtrTy(*DAG.getContext(),
8725 Subtarget->is64Bit()
8726 ? DAG.getIntPtrConstant(0x58)
8727 : (Subtarget->isTargetWindowsGNU()
8728 ? DAG.getIntPtrConstant(0x2C)
8729 : DAG.getExternalSymbol("_tls_array", getPointerTy()));
8731 SDValue ThreadPointer =
8732 DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8733 MachinePointerInfo(Ptr), false, false, false, 0);
8735 // Load the _tls_index variable
8736 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8737 if (Subtarget->is64Bit())
8738 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8739 IDX, MachinePointerInfo(), MVT::i32,
8742 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
8743 false, false, false, 0);
8745 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
8747 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
8749 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
8750 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
8751 false, false, false, 0);
8753 // Get the offset of start of .tls section
8754 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8755 GA->getValueType(0),
8756 GA->getOffset(), X86II::MO_SECREL);
8757 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
8759 // The address of the thread local variable is the add of the thread
8760 // pointer with the offset of the variable.
8761 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
8764 llvm_unreachable("TLS not implemented for this target.");
8767 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
8768 /// and take a 2 x i32 value to shift plus a shift amount.
8769 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
8770 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
8771 MVT VT = Op.getSimpleValueType();
8772 unsigned VTBits = VT.getSizeInBits();
8774 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
8775 SDValue ShOpLo = Op.getOperand(0);
8776 SDValue ShOpHi = Op.getOperand(1);
8777 SDValue ShAmt = Op.getOperand(2);
8778 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
8779 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
8781 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8782 DAG.getConstant(VTBits - 1, MVT::i8));
8783 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
8784 DAG.getConstant(VTBits - 1, MVT::i8))
8785 : DAG.getConstant(0, VT);
8788 if (Op.getOpcode() == ISD::SHL_PARTS) {
8789 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
8790 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
8792 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
8793 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
8796 // If the shift amount is larger or equal than the width of a part we can't
8797 // rely on the results of shld/shrd. Insert a test and select the appropriate
8798 // values for large shift amounts.
8799 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8800 DAG.getConstant(VTBits, MVT::i8));
8801 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8802 AndNode, DAG.getConstant(0, MVT::i8));
8805 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8806 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
8807 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
8809 if (Op.getOpcode() == ISD::SHL_PARTS) {
8810 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8811 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8813 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8814 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8817 SDValue Ops[2] = { Lo, Hi };
8818 return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
8821 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
8822 SelectionDAG &DAG) const {
8823 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
8825 if (SrcVT.isVector())
8828 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
8829 "Unknown SINT_TO_FP to lower!");
8831 // These are really Legal; return the operand so the caller accepts it as
8833 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
8835 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
8836 Subtarget->is64Bit()) {
8841 unsigned Size = SrcVT.getSizeInBits()/8;
8842 MachineFunction &MF = DAG.getMachineFunction();
8843 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8844 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8845 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8847 MachinePointerInfo::getFixedStack(SSFI),
8849 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8852 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8854 SelectionDAG &DAG) const {
8858 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8860 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8862 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8864 unsigned ByteSize = SrcVT.getSizeInBits()/8;
8866 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8867 MachineMemOperand *MMO;
8869 int SSFI = FI->getIndex();
8871 DAG.getMachineFunction()
8872 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8873 MachineMemOperand::MOLoad, ByteSize, ByteSize);
8875 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8876 StackSlot = StackSlot.getOperand(1);
8878 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8879 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8881 Tys, Ops, array_lengthof(Ops),
8885 Chain = Result.getValue(1);
8886 SDValue InFlag = Result.getValue(2);
8888 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8889 // shouldn't be necessary except that RFP cannot be live across
8890 // multiple blocks. When stackifier is fixed, they can be uncoupled.
8891 MachineFunction &MF = DAG.getMachineFunction();
8892 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8893 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8894 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8895 Tys = DAG.getVTList(MVT::Other);
8897 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8899 MachineMemOperand *MMO =
8900 DAG.getMachineFunction()
8901 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8902 MachineMemOperand::MOStore, SSFISize, SSFISize);
8904 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8905 Ops, array_lengthof(Ops),
8906 Op.getValueType(), MMO);
8907 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8908 MachinePointerInfo::getFixedStack(SSFI),
8909 false, false, false, 0);
8915 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8916 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8917 SelectionDAG &DAG) const {
8918 // This algorithm is not obvious. Here it is what we're trying to output:
8921 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8922 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8926 pshufd $0x4e, %xmm0, %xmm1
8932 LLVMContext *Context = DAG.getContext();
8934 // Build some magic constants.
8935 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8936 Constant *C0 = ConstantDataVector::get(*Context, CV0);
8937 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8939 SmallVector<Constant*,2> CV1;
8941 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8942 APInt(64, 0x4330000000000000ULL))));
8944 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8945 APInt(64, 0x4530000000000000ULL))));
8946 Constant *C1 = ConstantVector::get(CV1);
8947 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8949 // Load the 64-bit value into an XMM register.
8950 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8952 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8953 MachinePointerInfo::getConstantPool(),
8954 false, false, false, 16);
8955 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8956 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8959 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8960 MachinePointerInfo::getConstantPool(),
8961 false, false, false, 16);
8962 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8963 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8966 if (Subtarget->hasSSE3()) {
8967 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8968 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8970 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8971 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8973 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8974 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8978 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8979 DAG.getIntPtrConstant(0));
8982 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8983 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8984 SelectionDAG &DAG) const {
8986 // FP constant to bias correct the final result.
8987 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8990 // Load the 32-bit value into an XMM register.
8991 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8994 // Zero out the upper parts of the register.
8995 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8997 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8998 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8999 DAG.getIntPtrConstant(0));
9001 // Or the load with the bias.
9002 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
9003 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9004 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9006 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9007 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9008 MVT::v2f64, Bias)));
9009 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9010 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
9011 DAG.getIntPtrConstant(0));
9013 // Subtract the bias.
9014 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
9016 // Handle final rounding.
9017 EVT DestVT = Op.getValueType();
9019 if (DestVT.bitsLT(MVT::f64))
9020 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
9021 DAG.getIntPtrConstant(0));
9022 if (DestVT.bitsGT(MVT::f64))
9023 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
9025 // Handle final rounding.
9029 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
9030 SelectionDAG &DAG) const {
9031 SDValue N0 = Op.getOperand(0);
9032 MVT SVT = N0.getSimpleValueType();
9035 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
9036 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
9037 "Custom UINT_TO_FP is not supported!");
9039 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
9040 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
9041 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
9044 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
9045 SelectionDAG &DAG) const {
9046 SDValue N0 = Op.getOperand(0);
9049 if (Op.getValueType().isVector())
9050 return lowerUINT_TO_FP_vec(Op, DAG);
9052 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
9053 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
9054 // the optimization here.
9055 if (DAG.SignBitIsZero(N0))
9056 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
9058 MVT SrcVT = N0.getSimpleValueType();
9059 MVT DstVT = Op.getSimpleValueType();
9060 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
9061 return LowerUINT_TO_FP_i64(Op, DAG);
9062 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
9063 return LowerUINT_TO_FP_i32(Op, DAG);
9064 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
9067 // Make a 64-bit buffer, and use it to build an FILD.
9068 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
9069 if (SrcVT == MVT::i32) {
9070 SDValue WordOff = DAG.getConstant(4, getPointerTy());
9071 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
9072 getPointerTy(), StackSlot, WordOff);
9073 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9074 StackSlot, MachinePointerInfo(),
9076 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
9077 OffsetSlot, MachinePointerInfo(),
9079 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
9083 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
9084 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9085 StackSlot, MachinePointerInfo(),
9087 // For i64 source, we need to add the appropriate power of 2 if the input
9088 // was negative. This is the same as the optimization in
9089 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
9090 // we must be careful to do the computation in x87 extended precision, not
9091 // in SSE. (The generic code can't know it's OK to do this, or how to.)
9092 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
9093 MachineMemOperand *MMO =
9094 DAG.getMachineFunction()
9095 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9096 MachineMemOperand::MOLoad, 8, 8);
9098 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
9099 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
9100 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
9101 array_lengthof(Ops), MVT::i64, MMO);
9103 APInt FF(32, 0x5F800000ULL);
9105 // Check whether the sign bit is set.
9106 SDValue SignSet = DAG.getSetCC(dl,
9107 getSetCCResultType(*DAG.getContext(), MVT::i64),
9108 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
9111 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
9112 SDValue FudgePtr = DAG.getConstantPool(
9113 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
9116 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
9117 SDValue Zero = DAG.getIntPtrConstant(0);
9118 SDValue Four = DAG.getIntPtrConstant(4);
9119 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
9121 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
9123 // Load the value out, extending it from f32 to f80.
9124 // FIXME: Avoid the extend by constructing the right constant pool?
9125 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
9126 FudgePtr, MachinePointerInfo::getConstantPool(),
9127 MVT::f32, false, false, 4);
9128 // Extend everything to 80 bits to force it to be done on x87.
9129 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
9130 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
9133 std::pair<SDValue,SDValue>
9134 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
9135 bool IsSigned, bool IsReplace) const {
9138 EVT DstTy = Op.getValueType();
9140 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
9141 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
9145 assert(DstTy.getSimpleVT() <= MVT::i64 &&
9146 DstTy.getSimpleVT() >= MVT::i16 &&
9147 "Unknown FP_TO_INT to lower!");
9149 // These are really Legal.
9150 if (DstTy == MVT::i32 &&
9151 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9152 return std::make_pair(SDValue(), SDValue());
9153 if (Subtarget->is64Bit() &&
9154 DstTy == MVT::i64 &&
9155 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9156 return std::make_pair(SDValue(), SDValue());
9158 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
9159 // stack slot, or into the FTOL runtime function.
9160 MachineFunction &MF = DAG.getMachineFunction();
9161 unsigned MemSize = DstTy.getSizeInBits()/8;
9162 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9163 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9166 if (!IsSigned && isIntegerTypeFTOL(DstTy))
9167 Opc = X86ISD::WIN_FTOL;
9169 switch (DstTy.getSimpleVT().SimpleTy) {
9170 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
9171 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
9172 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
9173 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
9176 SDValue Chain = DAG.getEntryNode();
9177 SDValue Value = Op.getOperand(0);
9178 EVT TheVT = Op.getOperand(0).getValueType();
9179 // FIXME This causes a redundant load/store if the SSE-class value is already
9180 // in memory, such as if it is on the callstack.
9181 if (isScalarFPTypeInSSEReg(TheVT)) {
9182 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
9183 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
9184 MachinePointerInfo::getFixedStack(SSFI),
9186 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
9188 Chain, StackSlot, DAG.getValueType(TheVT)
9191 MachineMemOperand *MMO =
9192 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9193 MachineMemOperand::MOLoad, MemSize, MemSize);
9194 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops,
9195 array_lengthof(Ops), DstTy, MMO);
9196 Chain = Value.getValue(1);
9197 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9198 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9201 MachineMemOperand *MMO =
9202 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9203 MachineMemOperand::MOStore, MemSize, MemSize);
9205 if (Opc != X86ISD::WIN_FTOL) {
9206 // Build the FP_TO_INT*_IN_MEM
9207 SDValue Ops[] = { Chain, Value, StackSlot };
9208 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
9209 Ops, array_lengthof(Ops), DstTy,
9211 return std::make_pair(FIST, StackSlot);
9213 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
9214 DAG.getVTList(MVT::Other, MVT::Glue),
9216 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
9217 MVT::i32, ftol.getValue(1));
9218 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
9219 MVT::i32, eax.getValue(2));
9220 SDValue Ops[] = { eax, edx };
9221 SDValue pair = IsReplace
9222 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, array_lengthof(Ops))
9223 : DAG.getMergeValues(Ops, array_lengthof(Ops), DL);
9224 return std::make_pair(pair, SDValue());
9228 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
9229 const X86Subtarget *Subtarget) {
9230 MVT VT = Op->getSimpleValueType(0);
9231 SDValue In = Op->getOperand(0);
9232 MVT InVT = In.getSimpleValueType();
9235 // Optimize vectors in AVX mode:
9238 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
9239 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
9240 // Concat upper and lower parts.
9243 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
9244 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
9245 // Concat upper and lower parts.
9248 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
9249 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
9250 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
9253 if (Subtarget->hasInt256())
9254 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
9256 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
9257 SDValue Undef = DAG.getUNDEF(InVT);
9258 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9259 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9260 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9262 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9263 VT.getVectorNumElements()/2);
9265 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9266 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9268 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9271 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9272 SelectionDAG &DAG) {
9273 MVT VT = Op->getSimpleValueType(0);
9274 SDValue In = Op->getOperand(0);
9275 MVT InVT = In.getSimpleValueType();
9277 unsigned int NumElts = VT.getVectorNumElements();
9278 if (NumElts != 8 && NumElts != 16)
9281 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9282 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9284 EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9285 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9286 // Now we have only mask extension
9287 assert(InVT.getVectorElementType() == MVT::i1);
9288 SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9289 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9290 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9291 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9292 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9293 MachinePointerInfo::getConstantPool(),
9294 false, false, false, Alignment);
9296 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9297 if (VT.is512BitVector())
9299 return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9302 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9303 SelectionDAG &DAG) {
9304 if (Subtarget->hasFp256()) {
9305 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9313 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9314 SelectionDAG &DAG) {
9316 MVT VT = Op.getSimpleValueType();
9317 SDValue In = Op.getOperand(0);
9318 MVT SVT = In.getSimpleValueType();
9320 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9321 return LowerZERO_EXTEND_AVX512(Op, DAG);
9323 if (Subtarget->hasFp256()) {
9324 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9329 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9330 VT.getVectorNumElements() != SVT.getVectorNumElements());
9334 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9336 MVT VT = Op.getSimpleValueType();
9337 SDValue In = Op.getOperand(0);
9338 MVT InVT = In.getSimpleValueType();
9340 if (VT == MVT::i1) {
9341 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9342 "Invalid scalar TRUNCATE operation");
9343 if (InVT == MVT::i32)
9345 if (InVT.getSizeInBits() == 64)
9346 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9347 else if (InVT.getSizeInBits() < 32)
9348 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9349 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
9351 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9352 "Invalid TRUNCATE operation");
9354 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9355 if (VT.getVectorElementType().getSizeInBits() >=8)
9356 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9358 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9359 unsigned NumElts = InVT.getVectorNumElements();
9360 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9361 if (InVT.getSizeInBits() < 512) {
9362 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9363 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9367 SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9368 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9369 SDValue CP = DAG.getConstantPool(C, getPointerTy());
9370 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9371 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9372 MachinePointerInfo::getConstantPool(),
9373 false, false, false, Alignment);
9374 SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9375 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9376 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9379 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9380 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9381 if (Subtarget->hasInt256()) {
9382 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9383 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9384 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9386 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9387 DAG.getIntPtrConstant(0));
9390 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9391 DAG.getIntPtrConstant(0));
9392 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9393 DAG.getIntPtrConstant(2));
9394 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9395 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9396 static const int ShufMask[] = {0, 2, 4, 6};
9397 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
9400 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9401 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9402 if (Subtarget->hasInt256()) {
9403 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9405 SmallVector<SDValue,32> pshufbMask;
9406 for (unsigned i = 0; i < 2; ++i) {
9407 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9408 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9409 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9410 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9411 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9412 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9413 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9414 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9415 for (unsigned j = 0; j < 8; ++j)
9416 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9418 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
9419 &pshufbMask[0], 32);
9420 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9421 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9423 static const int ShufMask[] = {0, 2, -1, -1};
9424 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
9426 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9427 DAG.getIntPtrConstant(0));
9428 return DAG.getNode(ISD::BITCAST, DL, VT, In);
9431 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9432 DAG.getIntPtrConstant(0));
9434 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9435 DAG.getIntPtrConstant(4));
9437 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9438 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9441 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
9442 -1, -1, -1, -1, -1, -1, -1, -1};
9444 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9445 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9446 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9448 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9449 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9451 // The MOVLHPS Mask:
9452 static const int ShufMask2[] = {0, 1, 4, 5};
9453 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9454 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9457 // Handle truncation of V256 to V128 using shuffles.
9458 if (!VT.is128BitVector() || !InVT.is256BitVector())
9461 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9463 unsigned NumElems = VT.getVectorNumElements();
9464 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
9466 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9467 // Prepare truncation shuffle mask
9468 for (unsigned i = 0; i != NumElems; ++i)
9470 SDValue V = DAG.getVectorShuffle(NVT, DL,
9471 DAG.getNode(ISD::BITCAST, DL, NVT, In),
9472 DAG.getUNDEF(NVT), &MaskVec[0]);
9473 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9474 DAG.getIntPtrConstant(0));
9477 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9478 SelectionDAG &DAG) const {
9479 assert(!Op.getSimpleValueType().isVector());
9481 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9482 /*IsSigned=*/ true, /*IsReplace=*/ false);
9483 SDValue FIST = Vals.first, StackSlot = Vals.second;
9484 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9485 if (!FIST.getNode()) return Op;
9487 if (StackSlot.getNode())
9489 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9490 FIST, StackSlot, MachinePointerInfo(),
9491 false, false, false, 0);
9493 // The node is the result.
9497 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9498 SelectionDAG &DAG) const {
9499 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9500 /*IsSigned=*/ false, /*IsReplace=*/ false);
9501 SDValue FIST = Vals.first, StackSlot = Vals.second;
9502 assert(FIST.getNode() && "Unexpected failure");
9504 if (StackSlot.getNode())
9506 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9507 FIST, StackSlot, MachinePointerInfo(),
9508 false, false, false, 0);
9510 // The node is the result.
9514 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9516 MVT VT = Op.getSimpleValueType();
9517 SDValue In = Op.getOperand(0);
9518 MVT SVT = In.getSimpleValueType();
9520 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9522 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9523 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9524 In, DAG.getUNDEF(SVT)));
9527 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
9528 LLVMContext *Context = DAG.getContext();
9530 MVT VT = Op.getSimpleValueType();
9532 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9533 if (VT.isVector()) {
9534 EltVT = VT.getVectorElementType();
9535 NumElts = VT.getVectorNumElements();
9538 if (EltVT == MVT::f64)
9539 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9540 APInt(64, ~(1ULL << 63))));
9542 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9543 APInt(32, ~(1U << 31))));
9544 C = ConstantVector::getSplat(NumElts, C);
9545 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9546 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9547 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9548 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9549 MachinePointerInfo::getConstantPool(),
9550 false, false, false, Alignment);
9551 if (VT.isVector()) {
9552 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9553 return DAG.getNode(ISD::BITCAST, dl, VT,
9554 DAG.getNode(ISD::AND, dl, ANDVT,
9555 DAG.getNode(ISD::BITCAST, dl, ANDVT,
9557 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9559 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9562 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
9563 LLVMContext *Context = DAG.getContext();
9565 MVT VT = Op.getSimpleValueType();
9567 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9568 if (VT.isVector()) {
9569 EltVT = VT.getVectorElementType();
9570 NumElts = VT.getVectorNumElements();
9573 if (EltVT == MVT::f64)
9574 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9575 APInt(64, 1ULL << 63)));
9577 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9578 APInt(32, 1U << 31)));
9579 C = ConstantVector::getSplat(NumElts, C);
9580 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9581 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9582 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9583 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9584 MachinePointerInfo::getConstantPool(),
9585 false, false, false, Alignment);
9586 if (VT.isVector()) {
9587 MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
9588 return DAG.getNode(ISD::BITCAST, dl, VT,
9589 DAG.getNode(ISD::XOR, dl, XORVT,
9590 DAG.getNode(ISD::BITCAST, dl, XORVT,
9592 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9595 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9598 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
9599 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9600 LLVMContext *Context = DAG.getContext();
9601 SDValue Op0 = Op.getOperand(0);
9602 SDValue Op1 = Op.getOperand(1);
9604 MVT VT = Op.getSimpleValueType();
9605 MVT SrcVT = Op1.getSimpleValueType();
9607 // If second operand is smaller, extend it first.
9608 if (SrcVT.bitsLT(VT)) {
9609 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9612 // And if it is bigger, shrink it first.
9613 if (SrcVT.bitsGT(VT)) {
9614 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9618 // At this point the operands and the result should have the same
9619 // type, and that won't be f80 since that is not custom lowered.
9621 // First get the sign bit of second operand.
9622 SmallVector<Constant*,4> CV;
9623 if (SrcVT == MVT::f64) {
9624 const fltSemantics &Sem = APFloat::IEEEdouble;
9625 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9626 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9628 const fltSemantics &Sem = APFloat::IEEEsingle;
9629 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9630 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9631 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9632 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9634 Constant *C = ConstantVector::get(CV);
9635 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9636 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9637 MachinePointerInfo::getConstantPool(),
9638 false, false, false, 16);
9639 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9641 // Shift sign bit right or left if the two operands have different types.
9642 if (SrcVT.bitsGT(VT)) {
9643 // Op0 is MVT::f32, Op1 is MVT::f64.
9644 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9645 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9646 DAG.getConstant(32, MVT::i32));
9647 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9648 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9649 DAG.getIntPtrConstant(0));
9652 // Clear first operand sign bit.
9654 if (VT == MVT::f64) {
9655 const fltSemantics &Sem = APFloat::IEEEdouble;
9656 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9657 APInt(64, ~(1ULL << 63)))));
9658 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9660 const fltSemantics &Sem = APFloat::IEEEsingle;
9661 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9662 APInt(32, ~(1U << 31)))));
9663 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9664 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9665 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9667 C = ConstantVector::get(CV);
9668 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9669 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9670 MachinePointerInfo::getConstantPool(),
9671 false, false, false, 16);
9672 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9674 // Or the value with the sign bit.
9675 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9678 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9679 SDValue N0 = Op.getOperand(0);
9681 MVT VT = Op.getSimpleValueType();
9683 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9684 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9685 DAG.getConstant(1, VT));
9686 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9689 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9691 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
9692 SelectionDAG &DAG) {
9693 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9695 if (!Subtarget->hasSSE41())
9698 if (!Op->hasOneUse())
9701 SDNode *N = Op.getNode();
9704 SmallVector<SDValue, 8> Opnds;
9705 DenseMap<SDValue, unsigned> VecInMap;
9706 SmallVector<SDValue, 8> VecIns;
9707 EVT VT = MVT::Other;
9709 // Recognize a special case where a vector is casted into wide integer to
9711 Opnds.push_back(N->getOperand(0));
9712 Opnds.push_back(N->getOperand(1));
9714 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9715 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9716 // BFS traverse all OR'd operands.
9717 if (I->getOpcode() == ISD::OR) {
9718 Opnds.push_back(I->getOperand(0));
9719 Opnds.push_back(I->getOperand(1));
9720 // Re-evaluate the number of nodes to be traversed.
9721 e += 2; // 2 more nodes (LHS and RHS) are pushed.
9725 // Quit if a non-EXTRACT_VECTOR_ELT
9726 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9729 // Quit if without a constant index.
9730 SDValue Idx = I->getOperand(1);
9731 if (!isa<ConstantSDNode>(Idx))
9734 SDValue ExtractedFromVec = I->getOperand(0);
9735 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9736 if (M == VecInMap.end()) {
9737 VT = ExtractedFromVec.getValueType();
9738 // Quit if not 128/256-bit vector.
9739 if (!VT.is128BitVector() && !VT.is256BitVector())
9741 // Quit if not the same type.
9742 if (VecInMap.begin() != VecInMap.end() &&
9743 VT != VecInMap.begin()->first.getValueType())
9745 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9746 VecIns.push_back(ExtractedFromVec);
9748 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9751 assert((VT.is128BitVector() || VT.is256BitVector()) &&
9752 "Not extracted from 128-/256-bit vector.");
9754 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
9756 for (DenseMap<SDValue, unsigned>::const_iterator
9757 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
9758 // Quit if not all elements are used.
9759 if (I->second != FullMask)
9763 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9765 // Cast all vectors into TestVT for PTEST.
9766 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
9767 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
9769 // If more than one full vectors are evaluated, OR them first before PTEST.
9770 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
9771 // Each iteration will OR 2 nodes and append the result until there is only
9772 // 1 node left, i.e. the final OR'd value of all vectors.
9773 SDValue LHS = VecIns[Slot];
9774 SDValue RHS = VecIns[Slot + 1];
9775 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
9778 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
9779 VecIns.back(), VecIns.back());
9782 /// \brief return true if \c Op has a use that doesn't just read flags.
9783 static bool hasNonFlagsUse(SDValue Op) {
9784 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
9787 unsigned UOpNo = UI.getOperandNo();
9788 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9789 // Look pass truncate.
9790 UOpNo = User->use_begin().getOperandNo();
9791 User = *User->use_begin();
9794 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
9795 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
9801 /// Emit nodes that will be selected as "test Op0,Op0", or something
9803 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
9804 SelectionDAG &DAG) const {
9805 if (Op.getValueType() == MVT::i1)
9806 // KORTEST instruction should be selected
9807 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9808 DAG.getConstant(0, Op.getValueType()));
9810 // CF and OF aren't always set the way we want. Determine which
9811 // of these we need.
9812 bool NeedCF = false;
9813 bool NeedOF = false;
9816 case X86::COND_A: case X86::COND_AE:
9817 case X86::COND_B: case X86::COND_BE:
9820 case X86::COND_G: case X86::COND_GE:
9821 case X86::COND_L: case X86::COND_LE:
9822 case X86::COND_O: case X86::COND_NO:
9826 // See if we can use the EFLAGS value from the operand instead of
9827 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
9828 // we prove that the arithmetic won't overflow, we can't use OF or CF.
9829 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
9830 // Emit a CMP with 0, which is the TEST pattern.
9831 //if (Op.getValueType() == MVT::i1)
9832 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
9833 // DAG.getConstant(0, MVT::i1));
9834 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9835 DAG.getConstant(0, Op.getValueType()));
9837 unsigned Opcode = 0;
9838 unsigned NumOperands = 0;
9840 // Truncate operations may prevent the merge of the SETCC instruction
9841 // and the arithmetic instruction before it. Attempt to truncate the operands
9842 // of the arithmetic instruction and use a reduced bit-width instruction.
9843 bool NeedTruncation = false;
9844 SDValue ArithOp = Op;
9845 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
9846 SDValue Arith = Op->getOperand(0);
9847 // Both the trunc and the arithmetic op need to have one user each.
9848 if (Arith->hasOneUse())
9849 switch (Arith.getOpcode()) {
9856 NeedTruncation = true;
9862 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
9863 // which may be the result of a CAST. We use the variable 'Op', which is the
9864 // non-casted variable when we check for possible users.
9865 switch (ArithOp.getOpcode()) {
9867 // Due to an isel shortcoming, be conservative if this add is likely to be
9868 // selected as part of a load-modify-store instruction. When the root node
9869 // in a match is a store, isel doesn't know how to remap non-chain non-flag
9870 // uses of other nodes in the match, such as the ADD in this case. This
9871 // leads to the ADD being left around and reselected, with the result being
9872 // two adds in the output. Alas, even if none our users are stores, that
9873 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
9874 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
9875 // climbing the DAG back to the root, and it doesn't seem to be worth the
9877 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9878 UE = Op.getNode()->use_end(); UI != UE; ++UI)
9879 if (UI->getOpcode() != ISD::CopyToReg &&
9880 UI->getOpcode() != ISD::SETCC &&
9881 UI->getOpcode() != ISD::STORE)
9884 if (ConstantSDNode *C =
9885 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
9886 // An add of one will be selected as an INC.
9887 if (C->getAPIntValue() == 1) {
9888 Opcode = X86ISD::INC;
9893 // An add of negative one (subtract of one) will be selected as a DEC.
9894 if (C->getAPIntValue().isAllOnesValue()) {
9895 Opcode = X86ISD::DEC;
9901 // Otherwise use a regular EFLAGS-setting add.
9902 Opcode = X86ISD::ADD;
9907 // If we have a constant logical shift that's only used in a comparison
9908 // against zero turn it into an equivalent AND. This allows turning it into
9909 // a TEST instruction later.
9910 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) &&
9911 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
9912 EVT VT = Op.getValueType();
9913 unsigned BitWidth = VT.getSizeInBits();
9914 unsigned ShAmt = Op->getConstantOperandVal(1);
9915 if (ShAmt >= BitWidth) // Avoid undefined shifts.
9917 APInt Mask = ArithOp.getOpcode() == ISD::SRL
9918 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
9919 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
9920 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
9922 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
9923 DAG.getConstant(Mask, VT));
9924 DAG.ReplaceAllUsesWith(Op, New);
9930 // If the primary and result isn't used, don't bother using X86ISD::AND,
9931 // because a TEST instruction will be better.
9932 if (!hasNonFlagsUse(Op))
9938 // Due to the ISEL shortcoming noted above, be conservative if this op is
9939 // likely to be selected as part of a load-modify-store instruction.
9940 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9941 UE = Op.getNode()->use_end(); UI != UE; ++UI)
9942 if (UI->getOpcode() == ISD::STORE)
9945 // Otherwise use a regular EFLAGS-setting instruction.
9946 switch (ArithOp.getOpcode()) {
9947 default: llvm_unreachable("unexpected operator!");
9948 case ISD::SUB: Opcode = X86ISD::SUB; break;
9949 case ISD::XOR: Opcode = X86ISD::XOR; break;
9950 case ISD::AND: Opcode = X86ISD::AND; break;
9952 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9953 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
9954 if (EFLAGS.getNode())
9957 Opcode = X86ISD::OR;
9971 return SDValue(Op.getNode(), 1);
9977 // If we found that truncation is beneficial, perform the truncation and
9979 if (NeedTruncation) {
9980 EVT VT = Op.getValueType();
9981 SDValue WideVal = Op->getOperand(0);
9982 EVT WideVT = WideVal.getValueType();
9983 unsigned ConvertedOp = 0;
9984 // Use a target machine opcode to prevent further DAGCombine
9985 // optimizations that may separate the arithmetic operations
9986 // from the setcc node.
9987 switch (WideVal.getOpcode()) {
9989 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9990 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9991 case ISD::AND: ConvertedOp = X86ISD::AND; break;
9992 case ISD::OR: ConvertedOp = X86ISD::OR; break;
9993 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9997 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9998 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9999 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
10000 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
10001 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
10007 // Emit a CMP with 0, which is the TEST pattern.
10008 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10009 DAG.getConstant(0, Op.getValueType()));
10011 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10012 SmallVector<SDValue, 4> Ops;
10013 for (unsigned i = 0; i != NumOperands; ++i)
10014 Ops.push_back(Op.getOperand(i));
10016 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
10017 DAG.ReplaceAllUsesWith(Op, New);
10018 return SDValue(New.getNode(), 1);
10021 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
10023 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
10024 SDLoc dl, SelectionDAG &DAG) const {
10025 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
10026 if (C->getAPIntValue() == 0)
10027 return EmitTest(Op0, X86CC, dl, DAG);
10029 if (Op0.getValueType() == MVT::i1)
10030 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
10033 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
10034 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
10035 // Do the comparison at i32 if it's smaller, besides the Atom case.
10036 // This avoids subregister aliasing issues. Keep the smaller reference
10037 // if we're optimizing for size, however, as that'll allow better folding
10038 // of memory operations.
10039 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
10040 !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
10041 AttributeSet::FunctionIndex, Attribute::MinSize) &&
10042 !Subtarget->isAtom()) {
10043 unsigned ExtendOp =
10044 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
10045 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
10046 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
10048 // Use SUB instead of CMP to enable CSE between SUB and CMP.
10049 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
10050 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
10052 return SDValue(Sub.getNode(), 1);
10054 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
10057 /// Convert a comparison if required by the subtarget.
10058 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
10059 SelectionDAG &DAG) const {
10060 // If the subtarget does not support the FUCOMI instruction, floating-point
10061 // comparisons have to be converted.
10062 if (Subtarget->hasCMov() ||
10063 Cmp.getOpcode() != X86ISD::CMP ||
10064 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
10065 !Cmp.getOperand(1).getValueType().isFloatingPoint())
10068 // The instruction selector will select an FUCOM instruction instead of
10069 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
10070 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
10071 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
10073 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
10074 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
10075 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
10076 DAG.getConstant(8, MVT::i8));
10077 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
10078 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
10081 static bool isAllOnes(SDValue V) {
10082 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10083 return C && C->isAllOnesValue();
10086 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
10087 /// if it's possible.
10088 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
10089 SDLoc dl, SelectionDAG &DAG) const {
10090 SDValue Op0 = And.getOperand(0);
10091 SDValue Op1 = And.getOperand(1);
10092 if (Op0.getOpcode() == ISD::TRUNCATE)
10093 Op0 = Op0.getOperand(0);
10094 if (Op1.getOpcode() == ISD::TRUNCATE)
10095 Op1 = Op1.getOperand(0);
10098 if (Op1.getOpcode() == ISD::SHL)
10099 std::swap(Op0, Op1);
10100 if (Op0.getOpcode() == ISD::SHL) {
10101 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
10102 if (And00C->getZExtValue() == 1) {
10103 // If we looked past a truncate, check that it's only truncating away
10105 unsigned BitWidth = Op0.getValueSizeInBits();
10106 unsigned AndBitWidth = And.getValueSizeInBits();
10107 if (BitWidth > AndBitWidth) {
10109 DAG.ComputeMaskedBits(Op0, Zeros, Ones);
10110 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
10114 RHS = Op0.getOperand(1);
10116 } else if (Op1.getOpcode() == ISD::Constant) {
10117 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
10118 uint64_t AndRHSVal = AndRHS->getZExtValue();
10119 SDValue AndLHS = Op0;
10121 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
10122 LHS = AndLHS.getOperand(0);
10123 RHS = AndLHS.getOperand(1);
10126 // Use BT if the immediate can't be encoded in a TEST instruction.
10127 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
10129 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
10133 if (LHS.getNode()) {
10134 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
10135 // instruction. Since the shift amount is in-range-or-undefined, we know
10136 // that doing a bittest on the i32 value is ok. We extend to i32 because
10137 // the encoding for the i16 version is larger than the i32 version.
10138 // Also promote i16 to i32 for performance / code size reason.
10139 if (LHS.getValueType() == MVT::i8 ||
10140 LHS.getValueType() == MVT::i16)
10141 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
10143 // If the operand types disagree, extend the shift amount to match. Since
10144 // BT ignores high bits (like shifts) we can use anyextend.
10145 if (LHS.getValueType() != RHS.getValueType())
10146 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
10148 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
10149 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
10150 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10151 DAG.getConstant(Cond, MVT::i8), BT);
10157 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
10159 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
10164 // SSE Condition code mapping:
10173 switch (SetCCOpcode) {
10174 default: llvm_unreachable("Unexpected SETCC condition");
10176 case ISD::SETEQ: SSECC = 0; break;
10178 case ISD::SETGT: Swap = true; // Fallthrough
10180 case ISD::SETOLT: SSECC = 1; break;
10182 case ISD::SETGE: Swap = true; // Fallthrough
10184 case ISD::SETOLE: SSECC = 2; break;
10185 case ISD::SETUO: SSECC = 3; break;
10187 case ISD::SETNE: SSECC = 4; break;
10188 case ISD::SETULE: Swap = true; // Fallthrough
10189 case ISD::SETUGE: SSECC = 5; break;
10190 case ISD::SETULT: Swap = true; // Fallthrough
10191 case ISD::SETUGT: SSECC = 6; break;
10192 case ISD::SETO: SSECC = 7; break;
10194 case ISD::SETONE: SSECC = 8; break;
10197 std::swap(Op0, Op1);
10202 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
10203 // ones, and then concatenate the result back.
10204 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
10205 MVT VT = Op.getSimpleValueType();
10207 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
10208 "Unsupported value type for operation");
10210 unsigned NumElems = VT.getVectorNumElements();
10212 SDValue CC = Op.getOperand(2);
10214 // Extract the LHS vectors
10215 SDValue LHS = Op.getOperand(0);
10216 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10217 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10219 // Extract the RHS vectors
10220 SDValue RHS = Op.getOperand(1);
10221 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10222 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10224 // Issue the operation on the smaller types and concatenate the result back
10225 MVT EltVT = VT.getVectorElementType();
10226 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10227 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10228 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
10229 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
10232 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
10233 const X86Subtarget *Subtarget) {
10234 SDValue Op0 = Op.getOperand(0);
10235 SDValue Op1 = Op.getOperand(1);
10236 SDValue CC = Op.getOperand(2);
10237 MVT VT = Op.getSimpleValueType();
10240 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
10241 Op.getValueType().getScalarType() == MVT::i1 &&
10242 "Cannot set masked compare for this operation");
10244 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10246 bool Unsigned = false;
10249 switch (SetCCOpcode) {
10250 default: llvm_unreachable("Unexpected SETCC condition");
10251 case ISD::SETNE: SSECC = 4; break;
10252 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
10253 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
10254 case ISD::SETLT: Swap = true; //fall-through
10255 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
10256 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
10257 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
10258 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
10259 case ISD::SETULE: Unsigned = true; //fall-through
10260 case ISD::SETLE: SSECC = 2; break;
10264 std::swap(Op0, Op1);
10266 return DAG.getNode(Opc, dl, VT, Op0, Op1);
10267 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
10268 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10269 DAG.getConstant(SSECC, MVT::i8));
10272 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
10273 /// operand \p Op1. If non-trivial (for example because it's not constant)
10274 /// return an empty value.
10275 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
10277 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
10281 MVT VT = Op1.getSimpleValueType();
10282 MVT EVT = VT.getVectorElementType();
10283 unsigned n = VT.getVectorNumElements();
10284 SmallVector<SDValue, 8> ULTOp1;
10286 for (unsigned i = 0; i < n; ++i) {
10287 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
10288 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
10291 // Avoid underflow.
10292 APInt Val = Elt->getAPIntValue();
10296 ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
10299 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1.data(), ULTOp1.size());
10302 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
10303 SelectionDAG &DAG) {
10304 SDValue Op0 = Op.getOperand(0);
10305 SDValue Op1 = Op.getOperand(1);
10306 SDValue CC = Op.getOperand(2);
10307 MVT VT = Op.getSimpleValueType();
10308 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10309 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10314 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10315 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10318 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10319 unsigned Opc = X86ISD::CMPP;
10320 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10321 assert(VT.getVectorNumElements() <= 16);
10322 Opc = X86ISD::CMPM;
10324 // In the two special cases we can't handle, emit two comparisons.
10327 unsigned CombineOpc;
10328 if (SetCCOpcode == ISD::SETUEQ) {
10329 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10331 assert(SetCCOpcode == ISD::SETONE);
10332 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10335 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10336 DAG.getConstant(CC0, MVT::i8));
10337 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10338 DAG.getConstant(CC1, MVT::i8));
10339 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10341 // Handle all other FP comparisons here.
10342 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10343 DAG.getConstant(SSECC, MVT::i8));
10346 // Break 256-bit integer vector compare into smaller ones.
10347 if (VT.is256BitVector() && !Subtarget->hasInt256())
10348 return Lower256IntVSETCC(Op, DAG);
10350 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10351 EVT OpVT = Op1.getValueType();
10352 if (Subtarget->hasAVX512()) {
10353 if (Op1.getValueType().is512BitVector() ||
10354 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10355 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
10357 // In AVX-512 architecture setcc returns mask with i1 elements,
10358 // But there is no compare instruction for i8 and i16 elements.
10359 // We are not talking about 512-bit operands in this case, these
10360 // types are illegal.
10362 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10363 OpVT.getVectorElementType().getSizeInBits() >= 8))
10364 return DAG.getNode(ISD::TRUNCATE, dl, VT,
10365 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10368 // We are handling one of the integer comparisons here. Since SSE only has
10369 // GT and EQ comparisons for integer, swapping operands and multiple
10370 // operations may be required for some comparisons.
10372 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10373 bool Subus = false;
10375 switch (SetCCOpcode) {
10376 default: llvm_unreachable("Unexpected SETCC condition");
10377 case ISD::SETNE: Invert = true;
10378 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
10379 case ISD::SETLT: Swap = true;
10380 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
10381 case ISD::SETGE: Swap = true;
10382 case ISD::SETLE: Opc = X86ISD::PCMPGT;
10383 Invert = true; break;
10384 case ISD::SETULT: Swap = true;
10385 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
10386 FlipSigns = true; break;
10387 case ISD::SETUGE: Swap = true;
10388 case ISD::SETULE: Opc = X86ISD::PCMPGT;
10389 FlipSigns = true; Invert = true; break;
10392 // Special case: Use min/max operations for SETULE/SETUGE
10393 MVT VET = VT.getVectorElementType();
10395 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10396 || (Subtarget->hasSSE2() && (VET == MVT::i8));
10399 switch (SetCCOpcode) {
10401 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10402 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10405 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10408 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
10409 if (!MinMax && hasSubus) {
10410 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
10412 // t = psubus Op0, Op1
10413 // pcmpeq t, <0..0>
10414 switch (SetCCOpcode) {
10416 case ISD::SETULT: {
10417 // If the comparison is against a constant we can turn this into a
10418 // setule. With psubus, setule does not require a swap. This is
10419 // beneficial because the constant in the register is no longer
10420 // destructed as the destination so it can be hoisted out of a loop.
10421 // Only do this pre-AVX since vpcmp* is no longer destructive.
10422 if (Subtarget->hasAVX())
10424 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
10425 if (ULEOp1.getNode()) {
10427 Subus = true; Invert = false; Swap = false;
10431 // Psubus is better than flip-sign because it requires no inversion.
10432 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
10433 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
10437 Opc = X86ISD::SUBUS;
10443 std::swap(Op0, Op1);
10445 // Check that the operation in question is available (most are plain SSE2,
10446 // but PCMPGTQ and PCMPEQQ have different requirements).
10447 if (VT == MVT::v2i64) {
10448 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10449 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10451 // First cast everything to the right type.
10452 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10453 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10455 // Since SSE has no unsigned integer comparisons, we need to flip the sign
10456 // bits of the inputs before performing those operations. The lower
10457 // compare is always unsigned.
10460 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10462 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10463 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10464 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10465 Sign, Zero, Sign, Zero);
10467 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10468 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10470 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10471 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10472 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10474 // Create masks for only the low parts/high parts of the 64 bit integers.
10475 static const int MaskHi[] = { 1, 1, 3, 3 };
10476 static const int MaskLo[] = { 0, 0, 2, 2 };
10477 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10478 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10479 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10481 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10482 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10485 Result = DAG.getNOT(dl, Result, MVT::v4i32);
10487 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10490 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10491 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10492 // pcmpeqd + pshufd + pand.
10493 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10495 // First cast everything to the right type.
10496 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10497 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10500 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
10502 // Make sure the lower and upper halves are both all-ones.
10503 static const int Mask[] = { 1, 0, 3, 2 };
10504 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
10505 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
10508 Result = DAG.getNOT(dl, Result, MVT::v4i32);
10510 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10514 // Since SSE has no unsigned integer comparisons, we need to flip the sign
10515 // bits of the inputs before performing those operations.
10517 EVT EltVT = VT.getVectorElementType();
10518 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
10519 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
10520 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
10523 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
10525 // If the logical-not of the result is required, perform that now.
10527 Result = DAG.getNOT(dl, Result, VT);
10530 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
10533 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
10534 getZeroVector(VT, Subtarget, DAG, dl));
10539 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
10541 MVT VT = Op.getSimpleValueType();
10543 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
10545 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
10546 && "SetCC type must be 8-bit or 1-bit integer");
10547 SDValue Op0 = Op.getOperand(0);
10548 SDValue Op1 = Op.getOperand(1);
10550 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10552 // Optimize to BT if possible.
10553 // Lower (X & (1 << N)) == 0 to BT(X, N).
10554 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
10555 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
10556 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
10557 Op1.getOpcode() == ISD::Constant &&
10558 cast<ConstantSDNode>(Op1)->isNullValue() &&
10559 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10560 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
10561 if (NewSetCC.getNode())
10565 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
10567 if (Op1.getOpcode() == ISD::Constant &&
10568 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
10569 cast<ConstantSDNode>(Op1)->isNullValue()) &&
10570 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10572 // If the input is a setcc, then reuse the input setcc or use a new one with
10573 // the inverted condition.
10574 if (Op0.getOpcode() == X86ISD::SETCC) {
10575 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
10576 bool Invert = (CC == ISD::SETNE) ^
10577 cast<ConstantSDNode>(Op1)->isNullValue();
10581 CCode = X86::GetOppositeBranchCondition(CCode);
10582 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10583 DAG.getConstant(CCode, MVT::i8),
10584 Op0.getOperand(1));
10586 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10590 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
10591 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
10592 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10594 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
10595 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
10598 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
10599 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
10600 if (X86CC == X86::COND_INVALID)
10603 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
10604 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
10605 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10606 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
10608 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10612 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10613 static bool isX86LogicalCmp(SDValue Op) {
10614 unsigned Opc = Op.getNode()->getOpcode();
10615 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10616 Opc == X86ISD::SAHF)
10618 if (Op.getResNo() == 1 &&
10619 (Opc == X86ISD::ADD ||
10620 Opc == X86ISD::SUB ||
10621 Opc == X86ISD::ADC ||
10622 Opc == X86ISD::SBB ||
10623 Opc == X86ISD::SMUL ||
10624 Opc == X86ISD::UMUL ||
10625 Opc == X86ISD::INC ||
10626 Opc == X86ISD::DEC ||
10627 Opc == X86ISD::OR ||
10628 Opc == X86ISD::XOR ||
10629 Opc == X86ISD::AND))
10632 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
10638 static bool isZero(SDValue V) {
10639 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10640 return C && C->isNullValue();
10643 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
10644 if (V.getOpcode() != ISD::TRUNCATE)
10647 SDValue VOp0 = V.getOperand(0);
10648 unsigned InBits = VOp0.getValueSizeInBits();
10649 unsigned Bits = V.getValueSizeInBits();
10650 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
10653 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
10654 bool addTest = true;
10655 SDValue Cond = Op.getOperand(0);
10656 SDValue Op1 = Op.getOperand(1);
10657 SDValue Op2 = Op.getOperand(2);
10659 EVT VT = Op1.getValueType();
10662 // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
10663 // are available. Otherwise fp cmovs get lowered into a less efficient branch
10664 // sequence later on.
10665 if (Cond.getOpcode() == ISD::SETCC &&
10666 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
10667 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
10668 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
10669 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
10670 int SSECC = translateX86FSETCC(
10671 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
10674 if (Subtarget->hasAVX512()) {
10675 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
10676 DAG.getConstant(SSECC, MVT::i8));
10677 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
10679 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
10680 DAG.getConstant(SSECC, MVT::i8));
10681 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
10682 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
10683 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
10687 if (Cond.getOpcode() == ISD::SETCC) {
10688 SDValue NewCond = LowerSETCC(Cond, DAG);
10689 if (NewCond.getNode())
10693 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
10694 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
10695 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
10696 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
10697 if (Cond.getOpcode() == X86ISD::SETCC &&
10698 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
10699 isZero(Cond.getOperand(1).getOperand(1))) {
10700 SDValue Cmp = Cond.getOperand(1);
10702 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
10704 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
10705 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
10706 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
10708 SDValue CmpOp0 = Cmp.getOperand(0);
10709 // Apply further optimizations for special cases
10710 // (select (x != 0), -1, 0) -> neg & sbb
10711 // (select (x == 0), 0, -1) -> neg & sbb
10712 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
10713 if (YC->isNullValue() &&
10714 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
10715 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
10716 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
10717 DAG.getConstant(0, CmpOp0.getValueType()),
10719 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10720 DAG.getConstant(X86::COND_B, MVT::i8),
10721 SDValue(Neg.getNode(), 1));
10725 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10726 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10727 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10729 SDValue Res = // Res = 0 or -1.
10730 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10731 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
10733 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
10734 Res = DAG.getNOT(DL, Res, Res.getValueType());
10736 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
10737 if (!N2C || !N2C->isNullValue())
10738 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
10743 // Look past (and (setcc_carry (cmp ...)), 1).
10744 if (Cond.getOpcode() == ISD::AND &&
10745 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10746 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10747 if (C && C->getAPIntValue() == 1)
10748 Cond = Cond.getOperand(0);
10751 // If condition flag is set by a X86ISD::CMP, then use it as the condition
10752 // setting operand in place of the X86ISD::SETCC.
10753 unsigned CondOpcode = Cond.getOpcode();
10754 if (CondOpcode == X86ISD::SETCC ||
10755 CondOpcode == X86ISD::SETCC_CARRY) {
10756 CC = Cond.getOperand(0);
10758 SDValue Cmp = Cond.getOperand(1);
10759 unsigned Opc = Cmp.getOpcode();
10760 MVT VT = Op.getSimpleValueType();
10762 bool IllegalFPCMov = false;
10763 if (VT.isFloatingPoint() && !VT.isVector() &&
10764 !isScalarFPTypeInSSEReg(VT)) // FPStack?
10765 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
10767 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
10768 Opc == X86ISD::BT) { // FIXME
10772 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10773 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10774 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10775 Cond.getOperand(0).getValueType() != MVT::i8)) {
10776 SDValue LHS = Cond.getOperand(0);
10777 SDValue RHS = Cond.getOperand(1);
10778 unsigned X86Opcode;
10781 switch (CondOpcode) {
10782 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10783 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10784 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10785 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10786 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10787 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10788 default: llvm_unreachable("unexpected overflowing operator");
10790 if (CondOpcode == ISD::UMULO)
10791 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10794 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10796 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
10798 if (CondOpcode == ISD::UMULO)
10799 Cond = X86Op.getValue(2);
10801 Cond = X86Op.getValue(1);
10803 CC = DAG.getConstant(X86Cond, MVT::i8);
10808 // Look pass the truncate if the high bits are known zero.
10809 if (isTruncWithZeroHighBitsInput(Cond, DAG))
10810 Cond = Cond.getOperand(0);
10812 // We know the result of AND is compared against zero. Try to match
10814 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10815 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
10816 if (NewSetCC.getNode()) {
10817 CC = NewSetCC.getOperand(0);
10818 Cond = NewSetCC.getOperand(1);
10825 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10826 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
10829 // a < b ? -1 : 0 -> RES = ~setcc_carry
10830 // a < b ? 0 : -1 -> RES = setcc_carry
10831 // a >= b ? -1 : 0 -> RES = setcc_carry
10832 // a >= b ? 0 : -1 -> RES = ~setcc_carry
10833 if (Cond.getOpcode() == X86ISD::SUB) {
10834 Cond = ConvertCmpIfNecessary(Cond, DAG);
10835 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
10837 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
10838 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
10839 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10840 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
10841 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
10842 return DAG.getNOT(DL, Res, Res.getValueType());
10847 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
10848 // widen the cmov and push the truncate through. This avoids introducing a new
10849 // branch during isel and doesn't add any extensions.
10850 if (Op.getValueType() == MVT::i8 &&
10851 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
10852 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
10853 if (T1.getValueType() == T2.getValueType() &&
10854 // Blacklist CopyFromReg to avoid partial register stalls.
10855 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
10856 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
10857 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
10858 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
10862 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
10863 // condition is true.
10864 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
10865 SDValue Ops[] = { Op2, Op1, CC, Cond };
10866 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
10869 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
10870 MVT VT = Op->getSimpleValueType(0);
10871 SDValue In = Op->getOperand(0);
10872 MVT InVT = In.getSimpleValueType();
10875 unsigned int NumElts = VT.getVectorNumElements();
10876 if (NumElts != 8 && NumElts != 16)
10879 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
10880 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10882 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10883 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
10885 MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
10886 Constant *C = ConstantInt::get(*DAG.getContext(),
10887 APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
10889 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
10890 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
10891 SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
10892 MachinePointerInfo::getConstantPool(),
10893 false, false, false, Alignment);
10894 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
10895 if (VT.is512BitVector())
10897 return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
10900 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
10901 SelectionDAG &DAG) {
10902 MVT VT = Op->getSimpleValueType(0);
10903 SDValue In = Op->getOperand(0);
10904 MVT InVT = In.getSimpleValueType();
10907 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
10908 return LowerSIGN_EXTEND_AVX512(Op, DAG);
10910 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
10911 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
10912 (VT != MVT::v16i16 || InVT != MVT::v16i8))
10915 if (Subtarget->hasInt256())
10916 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10918 // Optimize vectors in AVX mode
10919 // Sign extend v8i16 to v8i32 and
10922 // Divide input vector into two parts
10923 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
10924 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
10925 // concat the vectors to original VT
10927 unsigned NumElems = InVT.getVectorNumElements();
10928 SDValue Undef = DAG.getUNDEF(InVT);
10930 SmallVector<int,8> ShufMask1(NumElems, -1);
10931 for (unsigned i = 0; i != NumElems/2; ++i)
10934 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
10936 SmallVector<int,8> ShufMask2(NumElems, -1);
10937 for (unsigned i = 0; i != NumElems/2; ++i)
10938 ShufMask2[i] = i + NumElems/2;
10940 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
10942 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
10943 VT.getVectorNumElements()/2);
10945 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
10946 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
10948 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
10951 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
10952 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
10953 // from the AND / OR.
10954 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
10955 Opc = Op.getOpcode();
10956 if (Opc != ISD::OR && Opc != ISD::AND)
10958 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10959 Op.getOperand(0).hasOneUse() &&
10960 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
10961 Op.getOperand(1).hasOneUse());
10964 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
10965 // 1 and that the SETCC node has a single use.
10966 static bool isXor1OfSetCC(SDValue Op) {
10967 if (Op.getOpcode() != ISD::XOR)
10969 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10970 if (N1C && N1C->getAPIntValue() == 1) {
10971 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10972 Op.getOperand(0).hasOneUse();
10977 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
10978 bool addTest = true;
10979 SDValue Chain = Op.getOperand(0);
10980 SDValue Cond = Op.getOperand(1);
10981 SDValue Dest = Op.getOperand(2);
10984 bool Inverted = false;
10986 if (Cond.getOpcode() == ISD::SETCC) {
10987 // Check for setcc([su]{add,sub,mul}o == 0).
10988 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
10989 isa<ConstantSDNode>(Cond.getOperand(1)) &&
10990 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
10991 Cond.getOperand(0).getResNo() == 1 &&
10992 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
10993 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
10994 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
10995 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
10996 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
10997 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
10999 Cond = Cond.getOperand(0);
11001 SDValue NewCond = LowerSETCC(Cond, DAG);
11002 if (NewCond.getNode())
11007 // FIXME: LowerXALUO doesn't handle these!!
11008 else if (Cond.getOpcode() == X86ISD::ADD ||
11009 Cond.getOpcode() == X86ISD::SUB ||
11010 Cond.getOpcode() == X86ISD::SMUL ||
11011 Cond.getOpcode() == X86ISD::UMUL)
11012 Cond = LowerXALUO(Cond, DAG);
11015 // Look pass (and (setcc_carry (cmp ...)), 1).
11016 if (Cond.getOpcode() == ISD::AND &&
11017 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
11018 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11019 if (C && C->getAPIntValue() == 1)
11020 Cond = Cond.getOperand(0);
11023 // If condition flag is set by a X86ISD::CMP, then use it as the condition
11024 // setting operand in place of the X86ISD::SETCC.
11025 unsigned CondOpcode = Cond.getOpcode();
11026 if (CondOpcode == X86ISD::SETCC ||
11027 CondOpcode == X86ISD::SETCC_CARRY) {
11028 CC = Cond.getOperand(0);
11030 SDValue Cmp = Cond.getOperand(1);
11031 unsigned Opc = Cmp.getOpcode();
11032 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
11033 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
11037 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
11041 // These can only come from an arithmetic instruction with overflow,
11042 // e.g. SADDO, UADDO.
11043 Cond = Cond.getNode()->getOperand(1);
11049 CondOpcode = Cond.getOpcode();
11050 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11051 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11052 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11053 Cond.getOperand(0).getValueType() != MVT::i8)) {
11054 SDValue LHS = Cond.getOperand(0);
11055 SDValue RHS = Cond.getOperand(1);
11056 unsigned X86Opcode;
11059 // Keep this in sync with LowerXALUO, otherwise we might create redundant
11060 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
11062 switch (CondOpcode) {
11063 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11065 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11067 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
11070 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11071 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11073 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11075 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
11078 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11079 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11080 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11081 default: llvm_unreachable("unexpected overflowing operator");
11084 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
11085 if (CondOpcode == ISD::UMULO)
11086 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11089 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11091 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
11093 if (CondOpcode == ISD::UMULO)
11094 Cond = X86Op.getValue(2);
11096 Cond = X86Op.getValue(1);
11098 CC = DAG.getConstant(X86Cond, MVT::i8);
11102 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
11103 SDValue Cmp = Cond.getOperand(0).getOperand(1);
11104 if (CondOpc == ISD::OR) {
11105 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
11106 // two branches instead of an explicit OR instruction with a
11108 if (Cmp == Cond.getOperand(1).getOperand(1) &&
11109 isX86LogicalCmp(Cmp)) {
11110 CC = Cond.getOperand(0).getOperand(0);
11111 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11112 Chain, Dest, CC, Cmp);
11113 CC = Cond.getOperand(1).getOperand(0);
11117 } else { // ISD::AND
11118 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
11119 // two branches instead of an explicit AND instruction with a
11120 // separate test. However, we only do this if this block doesn't
11121 // have a fall-through edge, because this requires an explicit
11122 // jmp when the condition is false.
11123 if (Cmp == Cond.getOperand(1).getOperand(1) &&
11124 isX86LogicalCmp(Cmp) &&
11125 Op.getNode()->hasOneUse()) {
11126 X86::CondCode CCode =
11127 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11128 CCode = X86::GetOppositeBranchCondition(CCode);
11129 CC = DAG.getConstant(CCode, MVT::i8);
11130 SDNode *User = *Op.getNode()->use_begin();
11131 // Look for an unconditional branch following this conditional branch.
11132 // We need this because we need to reverse the successors in order
11133 // to implement FCMP_OEQ.
11134 if (User->getOpcode() == ISD::BR) {
11135 SDValue FalseBB = User->getOperand(1);
11137 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11138 assert(NewBR == User);
11142 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11143 Chain, Dest, CC, Cmp);
11144 X86::CondCode CCode =
11145 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
11146 CCode = X86::GetOppositeBranchCondition(CCode);
11147 CC = DAG.getConstant(CCode, MVT::i8);
11153 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
11154 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
11155 // It should be transformed during dag combiner except when the condition
11156 // is set by a arithmetics with overflow node.
11157 X86::CondCode CCode =
11158 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11159 CCode = X86::GetOppositeBranchCondition(CCode);
11160 CC = DAG.getConstant(CCode, MVT::i8);
11161 Cond = Cond.getOperand(0).getOperand(1);
11163 } else if (Cond.getOpcode() == ISD::SETCC &&
11164 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
11165 // For FCMP_OEQ, we can emit
11166 // two branches instead of an explicit AND instruction with a
11167 // separate test. However, we only do this if this block doesn't
11168 // have a fall-through edge, because this requires an explicit
11169 // jmp when the condition is false.
11170 if (Op.getNode()->hasOneUse()) {
11171 SDNode *User = *Op.getNode()->use_begin();
11172 // Look for an unconditional branch following this conditional branch.
11173 // We need this because we need to reverse the successors in order
11174 // to implement FCMP_OEQ.
11175 if (User->getOpcode() == ISD::BR) {
11176 SDValue FalseBB = User->getOperand(1);
11178 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11179 assert(NewBR == User);
11183 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11184 Cond.getOperand(0), Cond.getOperand(1));
11185 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11186 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11187 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11188 Chain, Dest, CC, Cmp);
11189 CC = DAG.getConstant(X86::COND_P, MVT::i8);
11194 } else if (Cond.getOpcode() == ISD::SETCC &&
11195 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
11196 // For FCMP_UNE, we can emit
11197 // two branches instead of an explicit AND instruction with a
11198 // separate test. However, we only do this if this block doesn't
11199 // have a fall-through edge, because this requires an explicit
11200 // jmp when the condition is false.
11201 if (Op.getNode()->hasOneUse()) {
11202 SDNode *User = *Op.getNode()->use_begin();
11203 // Look for an unconditional branch following this conditional branch.
11204 // We need this because we need to reverse the successors in order
11205 // to implement FCMP_UNE.
11206 if (User->getOpcode() == ISD::BR) {
11207 SDValue FalseBB = User->getOperand(1);
11209 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11210 assert(NewBR == User);
11213 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11214 Cond.getOperand(0), Cond.getOperand(1));
11215 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11216 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11217 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11218 Chain, Dest, CC, Cmp);
11219 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
11229 // Look pass the truncate if the high bits are known zero.
11230 if (isTruncWithZeroHighBitsInput(Cond, DAG))
11231 Cond = Cond.getOperand(0);
11233 // We know the result of AND is compared against zero. Try to match
11235 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11236 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
11237 if (NewSetCC.getNode()) {
11238 CC = NewSetCC.getOperand(0);
11239 Cond = NewSetCC.getOperand(1);
11246 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11247 Cond = EmitTest(Cond, X86::COND_NE, dl, DAG);
11249 Cond = ConvertCmpIfNecessary(Cond, DAG);
11250 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11251 Chain, Dest, CC, Cond);
11254 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
11255 // Calls to _alloca is needed to probe the stack when allocating more than 4k
11256 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
11257 // that the guard pages used by the OS virtual memory manager are allocated in
11258 // correct sequence.
11260 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
11261 SelectionDAG &DAG) const {
11262 MachineFunction &MF = DAG.getMachineFunction();
11263 bool SplitStack = MF.shouldSplitStack();
11264 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
11269 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11270 SDNode* Node = Op.getNode();
11272 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
11273 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
11274 " not tell us which reg is the stack pointer!");
11275 EVT VT = Node->getValueType(0);
11276 SDValue Tmp1 = SDValue(Node, 0);
11277 SDValue Tmp2 = SDValue(Node, 1);
11278 SDValue Tmp3 = Node->getOperand(2);
11279 SDValue Chain = Tmp1.getOperand(0);
11281 // Chain the dynamic stack allocation so that it doesn't modify the stack
11282 // pointer when other instructions are using the stack.
11283 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
11286 SDValue Size = Tmp2.getOperand(1);
11287 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
11288 Chain = SP.getValue(1);
11289 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
11290 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
11291 unsigned StackAlign = TFI.getStackAlignment();
11292 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
11293 if (Align > StackAlign)
11294 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
11295 DAG.getConstant(-(uint64_t)Align, VT));
11296 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
11298 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
11299 DAG.getIntPtrConstant(0, true), SDValue(),
11302 SDValue Ops[2] = { Tmp1, Tmp2 };
11303 return DAG.getMergeValues(Ops, 2, dl);
11307 SDValue Chain = Op.getOperand(0);
11308 SDValue Size = Op.getOperand(1);
11309 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11310 EVT VT = Op.getNode()->getValueType(0);
11312 bool Is64Bit = Subtarget->is64Bit();
11313 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
11316 MachineRegisterInfo &MRI = MF.getRegInfo();
11319 // The 64 bit implementation of segmented stacks needs to clobber both r10
11320 // r11. This makes it impossible to use it along with nested parameters.
11321 const Function *F = MF.getFunction();
11323 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
11325 if (I->hasNestAttr())
11326 report_fatal_error("Cannot use segmented stacks with functions that "
11327 "have nested arguments.");
11330 const TargetRegisterClass *AddrRegClass =
11331 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
11332 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
11333 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
11334 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
11335 DAG.getRegister(Vreg, SPTy));
11336 SDValue Ops1[2] = { Value, Chain };
11337 return DAG.getMergeValues(Ops1, 2, dl);
11340 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
11342 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
11343 Flag = Chain.getValue(1);
11344 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11346 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
11348 const X86RegisterInfo *RegInfo =
11349 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11350 unsigned SPReg = RegInfo->getStackRegister();
11351 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
11352 Chain = SP.getValue(1);
11355 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11356 DAG.getConstant(-(uint64_t)Align, VT));
11357 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
11360 SDValue Ops1[2] = { SP, Chain };
11361 return DAG.getMergeValues(Ops1, 2, dl);
11365 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
11366 MachineFunction &MF = DAG.getMachineFunction();
11367 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
11369 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11372 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
11373 // vastart just stores the address of the VarArgsFrameIndex slot into the
11374 // memory location argument.
11375 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11377 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
11378 MachinePointerInfo(SV), false, false, 0);
11382 // gp_offset (0 - 6 * 8)
11383 // fp_offset (48 - 48 + 8 * 16)
11384 // overflow_arg_area (point to parameters coming in memory).
11386 SmallVector<SDValue, 8> MemOps;
11387 SDValue FIN = Op.getOperand(1);
11389 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
11390 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
11392 FIN, MachinePointerInfo(SV), false, false, 0);
11393 MemOps.push_back(Store);
11396 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11397 FIN, DAG.getIntPtrConstant(4));
11398 Store = DAG.getStore(Op.getOperand(0), DL,
11399 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
11401 FIN, MachinePointerInfo(SV, 4), false, false, 0);
11402 MemOps.push_back(Store);
11404 // Store ptr to overflow_arg_area
11405 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11406 FIN, DAG.getIntPtrConstant(4));
11407 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11409 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11410 MachinePointerInfo(SV, 8),
11412 MemOps.push_back(Store);
11414 // Store ptr to reg_save_area.
11415 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11416 FIN, DAG.getIntPtrConstant(8));
11417 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11419 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11420 MachinePointerInfo(SV, 16), false, false, 0);
11421 MemOps.push_back(Store);
11422 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11423 &MemOps[0], MemOps.size());
11426 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11427 assert(Subtarget->is64Bit() &&
11428 "LowerVAARG only handles 64-bit va_arg!");
11429 assert((Subtarget->isTargetLinux() ||
11430 Subtarget->isTargetDarwin()) &&
11431 "Unhandled target in LowerVAARG");
11432 assert(Op.getNode()->getNumOperands() == 4);
11433 SDValue Chain = Op.getOperand(0);
11434 SDValue SrcPtr = Op.getOperand(1);
11435 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11436 unsigned Align = Op.getConstantOperandVal(3);
11439 EVT ArgVT = Op.getNode()->getValueType(0);
11440 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11441 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11444 // Decide which area this value should be read from.
11445 // TODO: Implement the AMD64 ABI in its entirety. This simple
11446 // selection mechanism works only for the basic types.
11447 if (ArgVT == MVT::f80) {
11448 llvm_unreachable("va_arg for f80 not yet implemented");
11449 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11450 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
11451 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11452 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
11454 llvm_unreachable("Unhandled argument type in LowerVAARG");
11457 if (ArgMode == 2) {
11458 // Sanity Check: Make sure using fp_offset makes sense.
11459 assert(!getTargetMachine().Options.UseSoftFloat &&
11460 !(DAG.getMachineFunction()
11461 .getFunction()->getAttributes()
11462 .hasAttribute(AttributeSet::FunctionIndex,
11463 Attribute::NoImplicitFloat)) &&
11464 Subtarget->hasSSE1());
11467 // Insert VAARG_64 node into the DAG
11468 // VAARG_64 returns two values: Variable Argument Address, Chain
11469 SmallVector<SDValue, 11> InstOps;
11470 InstOps.push_back(Chain);
11471 InstOps.push_back(SrcPtr);
11472 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11473 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11474 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11475 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11476 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11477 VTs, &InstOps[0], InstOps.size(),
11479 MachinePointerInfo(SV),
11481 /*Volatile=*/false,
11483 /*WriteMem=*/true);
11484 Chain = VAARG.getValue(1);
11486 // Load the next argument and return it
11487 return DAG.getLoad(ArgVT, dl,
11490 MachinePointerInfo(),
11491 false, false, false, 0);
11494 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11495 SelectionDAG &DAG) {
11496 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
11497 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
11498 SDValue Chain = Op.getOperand(0);
11499 SDValue DstPtr = Op.getOperand(1);
11500 SDValue SrcPtr = Op.getOperand(2);
11501 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
11502 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11505 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
11506 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
11508 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
11511 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
11512 // amount is a constant. Takes immediate version of shift as input.
11513 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
11514 SDValue SrcOp, uint64_t ShiftAmt,
11515 SelectionDAG &DAG) {
11516 MVT ElementType = VT.getVectorElementType();
11518 // Check for ShiftAmt >= element width
11519 if (ShiftAmt >= ElementType.getSizeInBits()) {
11520 if (Opc == X86ISD::VSRAI)
11521 ShiftAmt = ElementType.getSizeInBits() - 1;
11523 return DAG.getConstant(0, VT);
11526 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
11527 && "Unknown target vector shift-by-constant node");
11529 // Fold this packed vector shift into a build vector if SrcOp is a
11530 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
11531 if (VT == SrcOp.getSimpleValueType() &&
11532 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
11533 SmallVector<SDValue, 8> Elts;
11534 unsigned NumElts = SrcOp->getNumOperands();
11535 ConstantSDNode *ND;
11538 default: llvm_unreachable(0);
11539 case X86ISD::VSHLI:
11540 for (unsigned i=0; i!=NumElts; ++i) {
11541 SDValue CurrentOp = SrcOp->getOperand(i);
11542 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11543 Elts.push_back(CurrentOp);
11546 ND = cast<ConstantSDNode>(CurrentOp);
11547 const APInt &C = ND->getAPIntValue();
11548 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
11551 case X86ISD::VSRLI:
11552 for (unsigned i=0; i!=NumElts; ++i) {
11553 SDValue CurrentOp = SrcOp->getOperand(i);
11554 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11555 Elts.push_back(CurrentOp);
11558 ND = cast<ConstantSDNode>(CurrentOp);
11559 const APInt &C = ND->getAPIntValue();
11560 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
11563 case X86ISD::VSRAI:
11564 for (unsigned i=0; i!=NumElts; ++i) {
11565 SDValue CurrentOp = SrcOp->getOperand(i);
11566 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11567 Elts.push_back(CurrentOp);
11570 ND = cast<ConstantSDNode>(CurrentOp);
11571 const APInt &C = ND->getAPIntValue();
11572 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
11577 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Elts[0], NumElts);
11580 return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
11583 // getTargetVShiftNode - Handle vector element shifts where the shift amount
11584 // may or may not be a constant. Takes immediate version of shift as input.
11585 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
11586 SDValue SrcOp, SDValue ShAmt,
11587 SelectionDAG &DAG) {
11588 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
11590 // Catch shift-by-constant.
11591 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
11592 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
11593 CShAmt->getZExtValue(), DAG);
11595 // Change opcode to non-immediate version
11597 default: llvm_unreachable("Unknown target vector shift node");
11598 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
11599 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
11600 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
11603 // Need to build a vector containing shift amount
11604 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
11607 ShOps[1] = DAG.getConstant(0, MVT::i32);
11608 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
11609 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
11611 // The return type has to be a 128-bit type with the same element
11612 // type as the input type.
11613 MVT EltVT = VT.getVectorElementType();
11614 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
11616 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
11617 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
11620 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
11622 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11624 default: return SDValue(); // Don't custom lower most intrinsics.
11625 // Comparison intrinsics.
11626 case Intrinsic::x86_sse_comieq_ss:
11627 case Intrinsic::x86_sse_comilt_ss:
11628 case Intrinsic::x86_sse_comile_ss:
11629 case Intrinsic::x86_sse_comigt_ss:
11630 case Intrinsic::x86_sse_comige_ss:
11631 case Intrinsic::x86_sse_comineq_ss:
11632 case Intrinsic::x86_sse_ucomieq_ss:
11633 case Intrinsic::x86_sse_ucomilt_ss:
11634 case Intrinsic::x86_sse_ucomile_ss:
11635 case Intrinsic::x86_sse_ucomigt_ss:
11636 case Intrinsic::x86_sse_ucomige_ss:
11637 case Intrinsic::x86_sse_ucomineq_ss:
11638 case Intrinsic::x86_sse2_comieq_sd:
11639 case Intrinsic::x86_sse2_comilt_sd:
11640 case Intrinsic::x86_sse2_comile_sd:
11641 case Intrinsic::x86_sse2_comigt_sd:
11642 case Intrinsic::x86_sse2_comige_sd:
11643 case Intrinsic::x86_sse2_comineq_sd:
11644 case Intrinsic::x86_sse2_ucomieq_sd:
11645 case Intrinsic::x86_sse2_ucomilt_sd:
11646 case Intrinsic::x86_sse2_ucomile_sd:
11647 case Intrinsic::x86_sse2_ucomigt_sd:
11648 case Intrinsic::x86_sse2_ucomige_sd:
11649 case Intrinsic::x86_sse2_ucomineq_sd: {
11653 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11654 case Intrinsic::x86_sse_comieq_ss:
11655 case Intrinsic::x86_sse2_comieq_sd:
11656 Opc = X86ISD::COMI;
11659 case Intrinsic::x86_sse_comilt_ss:
11660 case Intrinsic::x86_sse2_comilt_sd:
11661 Opc = X86ISD::COMI;
11664 case Intrinsic::x86_sse_comile_ss:
11665 case Intrinsic::x86_sse2_comile_sd:
11666 Opc = X86ISD::COMI;
11669 case Intrinsic::x86_sse_comigt_ss:
11670 case Intrinsic::x86_sse2_comigt_sd:
11671 Opc = X86ISD::COMI;
11674 case Intrinsic::x86_sse_comige_ss:
11675 case Intrinsic::x86_sse2_comige_sd:
11676 Opc = X86ISD::COMI;
11679 case Intrinsic::x86_sse_comineq_ss:
11680 case Intrinsic::x86_sse2_comineq_sd:
11681 Opc = X86ISD::COMI;
11684 case Intrinsic::x86_sse_ucomieq_ss:
11685 case Intrinsic::x86_sse2_ucomieq_sd:
11686 Opc = X86ISD::UCOMI;
11689 case Intrinsic::x86_sse_ucomilt_ss:
11690 case Intrinsic::x86_sse2_ucomilt_sd:
11691 Opc = X86ISD::UCOMI;
11694 case Intrinsic::x86_sse_ucomile_ss:
11695 case Intrinsic::x86_sse2_ucomile_sd:
11696 Opc = X86ISD::UCOMI;
11699 case Intrinsic::x86_sse_ucomigt_ss:
11700 case Intrinsic::x86_sse2_ucomigt_sd:
11701 Opc = X86ISD::UCOMI;
11704 case Intrinsic::x86_sse_ucomige_ss:
11705 case Intrinsic::x86_sse2_ucomige_sd:
11706 Opc = X86ISD::UCOMI;
11709 case Intrinsic::x86_sse_ucomineq_ss:
11710 case Intrinsic::x86_sse2_ucomineq_sd:
11711 Opc = X86ISD::UCOMI;
11716 SDValue LHS = Op.getOperand(1);
11717 SDValue RHS = Op.getOperand(2);
11718 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
11719 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
11720 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
11721 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11722 DAG.getConstant(X86CC, MVT::i8), Cond);
11723 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11726 // Arithmetic intrinsics.
11727 case Intrinsic::x86_sse2_pmulu_dq:
11728 case Intrinsic::x86_avx2_pmulu_dq:
11729 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
11730 Op.getOperand(1), Op.getOperand(2));
11732 case Intrinsic::x86_sse2_pmulhu_w:
11733 case Intrinsic::x86_avx2_pmulhu_w:
11734 return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
11735 Op.getOperand(1), Op.getOperand(2));
11737 case Intrinsic::x86_sse2_pmulh_w:
11738 case Intrinsic::x86_avx2_pmulh_w:
11739 return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
11740 Op.getOperand(1), Op.getOperand(2));
11742 // SSE2/AVX2 sub with unsigned saturation intrinsics
11743 case Intrinsic::x86_sse2_psubus_b:
11744 case Intrinsic::x86_sse2_psubus_w:
11745 case Intrinsic::x86_avx2_psubus_b:
11746 case Intrinsic::x86_avx2_psubus_w:
11747 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
11748 Op.getOperand(1), Op.getOperand(2));
11750 // SSE3/AVX horizontal add/sub intrinsics
11751 case Intrinsic::x86_sse3_hadd_ps:
11752 case Intrinsic::x86_sse3_hadd_pd:
11753 case Intrinsic::x86_avx_hadd_ps_256:
11754 case Intrinsic::x86_avx_hadd_pd_256:
11755 case Intrinsic::x86_sse3_hsub_ps:
11756 case Intrinsic::x86_sse3_hsub_pd:
11757 case Intrinsic::x86_avx_hsub_ps_256:
11758 case Intrinsic::x86_avx_hsub_pd_256:
11759 case Intrinsic::x86_ssse3_phadd_w_128:
11760 case Intrinsic::x86_ssse3_phadd_d_128:
11761 case Intrinsic::x86_avx2_phadd_w:
11762 case Intrinsic::x86_avx2_phadd_d:
11763 case Intrinsic::x86_ssse3_phsub_w_128:
11764 case Intrinsic::x86_ssse3_phsub_d_128:
11765 case Intrinsic::x86_avx2_phsub_w:
11766 case Intrinsic::x86_avx2_phsub_d: {
11769 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11770 case Intrinsic::x86_sse3_hadd_ps:
11771 case Intrinsic::x86_sse3_hadd_pd:
11772 case Intrinsic::x86_avx_hadd_ps_256:
11773 case Intrinsic::x86_avx_hadd_pd_256:
11774 Opcode = X86ISD::FHADD;
11776 case Intrinsic::x86_sse3_hsub_ps:
11777 case Intrinsic::x86_sse3_hsub_pd:
11778 case Intrinsic::x86_avx_hsub_ps_256:
11779 case Intrinsic::x86_avx_hsub_pd_256:
11780 Opcode = X86ISD::FHSUB;
11782 case Intrinsic::x86_ssse3_phadd_w_128:
11783 case Intrinsic::x86_ssse3_phadd_d_128:
11784 case Intrinsic::x86_avx2_phadd_w:
11785 case Intrinsic::x86_avx2_phadd_d:
11786 Opcode = X86ISD::HADD;
11788 case Intrinsic::x86_ssse3_phsub_w_128:
11789 case Intrinsic::x86_ssse3_phsub_d_128:
11790 case Intrinsic::x86_avx2_phsub_w:
11791 case Intrinsic::x86_avx2_phsub_d:
11792 Opcode = X86ISD::HSUB;
11795 return DAG.getNode(Opcode, dl, Op.getValueType(),
11796 Op.getOperand(1), Op.getOperand(2));
11799 // SSE2/SSE41/AVX2 integer max/min intrinsics.
11800 case Intrinsic::x86_sse2_pmaxu_b:
11801 case Intrinsic::x86_sse41_pmaxuw:
11802 case Intrinsic::x86_sse41_pmaxud:
11803 case Intrinsic::x86_avx2_pmaxu_b:
11804 case Intrinsic::x86_avx2_pmaxu_w:
11805 case Intrinsic::x86_avx2_pmaxu_d:
11806 case Intrinsic::x86_sse2_pminu_b:
11807 case Intrinsic::x86_sse41_pminuw:
11808 case Intrinsic::x86_sse41_pminud:
11809 case Intrinsic::x86_avx2_pminu_b:
11810 case Intrinsic::x86_avx2_pminu_w:
11811 case Intrinsic::x86_avx2_pminu_d:
11812 case Intrinsic::x86_sse41_pmaxsb:
11813 case Intrinsic::x86_sse2_pmaxs_w:
11814 case Intrinsic::x86_sse41_pmaxsd:
11815 case Intrinsic::x86_avx2_pmaxs_b:
11816 case Intrinsic::x86_avx2_pmaxs_w:
11817 case Intrinsic::x86_avx2_pmaxs_d:
11818 case Intrinsic::x86_sse41_pminsb:
11819 case Intrinsic::x86_sse2_pmins_w:
11820 case Intrinsic::x86_sse41_pminsd:
11821 case Intrinsic::x86_avx2_pmins_b:
11822 case Intrinsic::x86_avx2_pmins_w:
11823 case Intrinsic::x86_avx2_pmins_d: {
11826 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11827 case Intrinsic::x86_sse2_pmaxu_b:
11828 case Intrinsic::x86_sse41_pmaxuw:
11829 case Intrinsic::x86_sse41_pmaxud:
11830 case Intrinsic::x86_avx2_pmaxu_b:
11831 case Intrinsic::x86_avx2_pmaxu_w:
11832 case Intrinsic::x86_avx2_pmaxu_d:
11833 Opcode = X86ISD::UMAX;
11835 case Intrinsic::x86_sse2_pminu_b:
11836 case Intrinsic::x86_sse41_pminuw:
11837 case Intrinsic::x86_sse41_pminud:
11838 case Intrinsic::x86_avx2_pminu_b:
11839 case Intrinsic::x86_avx2_pminu_w:
11840 case Intrinsic::x86_avx2_pminu_d:
11841 Opcode = X86ISD::UMIN;
11843 case Intrinsic::x86_sse41_pmaxsb:
11844 case Intrinsic::x86_sse2_pmaxs_w:
11845 case Intrinsic::x86_sse41_pmaxsd:
11846 case Intrinsic::x86_avx2_pmaxs_b:
11847 case Intrinsic::x86_avx2_pmaxs_w:
11848 case Intrinsic::x86_avx2_pmaxs_d:
11849 Opcode = X86ISD::SMAX;
11851 case Intrinsic::x86_sse41_pminsb:
11852 case Intrinsic::x86_sse2_pmins_w:
11853 case Intrinsic::x86_sse41_pminsd:
11854 case Intrinsic::x86_avx2_pmins_b:
11855 case Intrinsic::x86_avx2_pmins_w:
11856 case Intrinsic::x86_avx2_pmins_d:
11857 Opcode = X86ISD::SMIN;
11860 return DAG.getNode(Opcode, dl, Op.getValueType(),
11861 Op.getOperand(1), Op.getOperand(2));
11864 // SSE/SSE2/AVX floating point max/min intrinsics.
11865 case Intrinsic::x86_sse_max_ps:
11866 case Intrinsic::x86_sse2_max_pd:
11867 case Intrinsic::x86_avx_max_ps_256:
11868 case Intrinsic::x86_avx_max_pd_256:
11869 case Intrinsic::x86_sse_min_ps:
11870 case Intrinsic::x86_sse2_min_pd:
11871 case Intrinsic::x86_avx_min_ps_256:
11872 case Intrinsic::x86_avx_min_pd_256: {
11875 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11876 case Intrinsic::x86_sse_max_ps:
11877 case Intrinsic::x86_sse2_max_pd:
11878 case Intrinsic::x86_avx_max_ps_256:
11879 case Intrinsic::x86_avx_max_pd_256:
11880 Opcode = X86ISD::FMAX;
11882 case Intrinsic::x86_sse_min_ps:
11883 case Intrinsic::x86_sse2_min_pd:
11884 case Intrinsic::x86_avx_min_ps_256:
11885 case Intrinsic::x86_avx_min_pd_256:
11886 Opcode = X86ISD::FMIN;
11889 return DAG.getNode(Opcode, dl, Op.getValueType(),
11890 Op.getOperand(1), Op.getOperand(2));
11893 // AVX2 variable shift intrinsics
11894 case Intrinsic::x86_avx2_psllv_d:
11895 case Intrinsic::x86_avx2_psllv_q:
11896 case Intrinsic::x86_avx2_psllv_d_256:
11897 case Intrinsic::x86_avx2_psllv_q_256:
11898 case Intrinsic::x86_avx2_psrlv_d:
11899 case Intrinsic::x86_avx2_psrlv_q:
11900 case Intrinsic::x86_avx2_psrlv_d_256:
11901 case Intrinsic::x86_avx2_psrlv_q_256:
11902 case Intrinsic::x86_avx2_psrav_d:
11903 case Intrinsic::x86_avx2_psrav_d_256: {
11906 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11907 case Intrinsic::x86_avx2_psllv_d:
11908 case Intrinsic::x86_avx2_psllv_q:
11909 case Intrinsic::x86_avx2_psllv_d_256:
11910 case Intrinsic::x86_avx2_psllv_q_256:
11913 case Intrinsic::x86_avx2_psrlv_d:
11914 case Intrinsic::x86_avx2_psrlv_q:
11915 case Intrinsic::x86_avx2_psrlv_d_256:
11916 case Intrinsic::x86_avx2_psrlv_q_256:
11919 case Intrinsic::x86_avx2_psrav_d:
11920 case Intrinsic::x86_avx2_psrav_d_256:
11924 return DAG.getNode(Opcode, dl, Op.getValueType(),
11925 Op.getOperand(1), Op.getOperand(2));
11928 case Intrinsic::x86_ssse3_pshuf_b_128:
11929 case Intrinsic::x86_avx2_pshuf_b:
11930 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
11931 Op.getOperand(1), Op.getOperand(2));
11933 case Intrinsic::x86_ssse3_psign_b_128:
11934 case Intrinsic::x86_ssse3_psign_w_128:
11935 case Intrinsic::x86_ssse3_psign_d_128:
11936 case Intrinsic::x86_avx2_psign_b:
11937 case Intrinsic::x86_avx2_psign_w:
11938 case Intrinsic::x86_avx2_psign_d:
11939 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
11940 Op.getOperand(1), Op.getOperand(2));
11942 case Intrinsic::x86_sse41_insertps:
11943 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
11944 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11946 case Intrinsic::x86_avx_vperm2f128_ps_256:
11947 case Intrinsic::x86_avx_vperm2f128_pd_256:
11948 case Intrinsic::x86_avx_vperm2f128_si_256:
11949 case Intrinsic::x86_avx2_vperm2i128:
11950 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
11951 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11953 case Intrinsic::x86_avx2_permd:
11954 case Intrinsic::x86_avx2_permps:
11955 // Operands intentionally swapped. Mask is last operand to intrinsic,
11956 // but second operand for node/instruction.
11957 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
11958 Op.getOperand(2), Op.getOperand(1));
11960 case Intrinsic::x86_sse_sqrt_ps:
11961 case Intrinsic::x86_sse2_sqrt_pd:
11962 case Intrinsic::x86_avx_sqrt_ps_256:
11963 case Intrinsic::x86_avx_sqrt_pd_256:
11964 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
11966 // ptest and testp intrinsics. The intrinsic these come from are designed to
11967 // return an integer value, not just an instruction so lower it to the ptest
11968 // or testp pattern and a setcc for the result.
11969 case Intrinsic::x86_sse41_ptestz:
11970 case Intrinsic::x86_sse41_ptestc:
11971 case Intrinsic::x86_sse41_ptestnzc:
11972 case Intrinsic::x86_avx_ptestz_256:
11973 case Intrinsic::x86_avx_ptestc_256:
11974 case Intrinsic::x86_avx_ptestnzc_256:
11975 case Intrinsic::x86_avx_vtestz_ps:
11976 case Intrinsic::x86_avx_vtestc_ps:
11977 case Intrinsic::x86_avx_vtestnzc_ps:
11978 case Intrinsic::x86_avx_vtestz_pd:
11979 case Intrinsic::x86_avx_vtestc_pd:
11980 case Intrinsic::x86_avx_vtestnzc_pd:
11981 case Intrinsic::x86_avx_vtestz_ps_256:
11982 case Intrinsic::x86_avx_vtestc_ps_256:
11983 case Intrinsic::x86_avx_vtestnzc_ps_256:
11984 case Intrinsic::x86_avx_vtestz_pd_256:
11985 case Intrinsic::x86_avx_vtestc_pd_256:
11986 case Intrinsic::x86_avx_vtestnzc_pd_256: {
11987 bool IsTestPacked = false;
11990 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
11991 case Intrinsic::x86_avx_vtestz_ps:
11992 case Intrinsic::x86_avx_vtestz_pd:
11993 case Intrinsic::x86_avx_vtestz_ps_256:
11994 case Intrinsic::x86_avx_vtestz_pd_256:
11995 IsTestPacked = true; // Fallthrough
11996 case Intrinsic::x86_sse41_ptestz:
11997 case Intrinsic::x86_avx_ptestz_256:
11999 X86CC = X86::COND_E;
12001 case Intrinsic::x86_avx_vtestc_ps:
12002 case Intrinsic::x86_avx_vtestc_pd:
12003 case Intrinsic::x86_avx_vtestc_ps_256:
12004 case Intrinsic::x86_avx_vtestc_pd_256:
12005 IsTestPacked = true; // Fallthrough
12006 case Intrinsic::x86_sse41_ptestc:
12007 case Intrinsic::x86_avx_ptestc_256:
12009 X86CC = X86::COND_B;
12011 case Intrinsic::x86_avx_vtestnzc_ps:
12012 case Intrinsic::x86_avx_vtestnzc_pd:
12013 case Intrinsic::x86_avx_vtestnzc_ps_256:
12014 case Intrinsic::x86_avx_vtestnzc_pd_256:
12015 IsTestPacked = true; // Fallthrough
12016 case Intrinsic::x86_sse41_ptestnzc:
12017 case Intrinsic::x86_avx_ptestnzc_256:
12019 X86CC = X86::COND_A;
12023 SDValue LHS = Op.getOperand(1);
12024 SDValue RHS = Op.getOperand(2);
12025 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
12026 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
12027 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12028 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
12029 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12031 case Intrinsic::x86_avx512_kortestz_w:
12032 case Intrinsic::x86_avx512_kortestc_w: {
12033 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
12034 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
12035 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
12036 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12037 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
12038 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
12039 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12042 // SSE/AVX shift intrinsics
12043 case Intrinsic::x86_sse2_psll_w:
12044 case Intrinsic::x86_sse2_psll_d:
12045 case Intrinsic::x86_sse2_psll_q:
12046 case Intrinsic::x86_avx2_psll_w:
12047 case Intrinsic::x86_avx2_psll_d:
12048 case Intrinsic::x86_avx2_psll_q:
12049 case Intrinsic::x86_sse2_psrl_w:
12050 case Intrinsic::x86_sse2_psrl_d:
12051 case Intrinsic::x86_sse2_psrl_q:
12052 case Intrinsic::x86_avx2_psrl_w:
12053 case Intrinsic::x86_avx2_psrl_d:
12054 case Intrinsic::x86_avx2_psrl_q:
12055 case Intrinsic::x86_sse2_psra_w:
12056 case Intrinsic::x86_sse2_psra_d:
12057 case Intrinsic::x86_avx2_psra_w:
12058 case Intrinsic::x86_avx2_psra_d: {
12061 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12062 case Intrinsic::x86_sse2_psll_w:
12063 case Intrinsic::x86_sse2_psll_d:
12064 case Intrinsic::x86_sse2_psll_q:
12065 case Intrinsic::x86_avx2_psll_w:
12066 case Intrinsic::x86_avx2_psll_d:
12067 case Intrinsic::x86_avx2_psll_q:
12068 Opcode = X86ISD::VSHL;
12070 case Intrinsic::x86_sse2_psrl_w:
12071 case Intrinsic::x86_sse2_psrl_d:
12072 case Intrinsic::x86_sse2_psrl_q:
12073 case Intrinsic::x86_avx2_psrl_w:
12074 case Intrinsic::x86_avx2_psrl_d:
12075 case Intrinsic::x86_avx2_psrl_q:
12076 Opcode = X86ISD::VSRL;
12078 case Intrinsic::x86_sse2_psra_w:
12079 case Intrinsic::x86_sse2_psra_d:
12080 case Intrinsic::x86_avx2_psra_w:
12081 case Intrinsic::x86_avx2_psra_d:
12082 Opcode = X86ISD::VSRA;
12085 return DAG.getNode(Opcode, dl, Op.getValueType(),
12086 Op.getOperand(1), Op.getOperand(2));
12089 // SSE/AVX immediate shift intrinsics
12090 case Intrinsic::x86_sse2_pslli_w:
12091 case Intrinsic::x86_sse2_pslli_d:
12092 case Intrinsic::x86_sse2_pslli_q:
12093 case Intrinsic::x86_avx2_pslli_w:
12094 case Intrinsic::x86_avx2_pslli_d:
12095 case Intrinsic::x86_avx2_pslli_q:
12096 case Intrinsic::x86_sse2_psrli_w:
12097 case Intrinsic::x86_sse2_psrli_d:
12098 case Intrinsic::x86_sse2_psrli_q:
12099 case Intrinsic::x86_avx2_psrli_w:
12100 case Intrinsic::x86_avx2_psrli_d:
12101 case Intrinsic::x86_avx2_psrli_q:
12102 case Intrinsic::x86_sse2_psrai_w:
12103 case Intrinsic::x86_sse2_psrai_d:
12104 case Intrinsic::x86_avx2_psrai_w:
12105 case Intrinsic::x86_avx2_psrai_d: {
12108 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12109 case Intrinsic::x86_sse2_pslli_w:
12110 case Intrinsic::x86_sse2_pslli_d:
12111 case Intrinsic::x86_sse2_pslli_q:
12112 case Intrinsic::x86_avx2_pslli_w:
12113 case Intrinsic::x86_avx2_pslli_d:
12114 case Intrinsic::x86_avx2_pslli_q:
12115 Opcode = X86ISD::VSHLI;
12117 case Intrinsic::x86_sse2_psrli_w:
12118 case Intrinsic::x86_sse2_psrli_d:
12119 case Intrinsic::x86_sse2_psrli_q:
12120 case Intrinsic::x86_avx2_psrli_w:
12121 case Intrinsic::x86_avx2_psrli_d:
12122 case Intrinsic::x86_avx2_psrli_q:
12123 Opcode = X86ISD::VSRLI;
12125 case Intrinsic::x86_sse2_psrai_w:
12126 case Intrinsic::x86_sse2_psrai_d:
12127 case Intrinsic::x86_avx2_psrai_w:
12128 case Intrinsic::x86_avx2_psrai_d:
12129 Opcode = X86ISD::VSRAI;
12132 return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
12133 Op.getOperand(1), Op.getOperand(2), DAG);
12136 case Intrinsic::x86_sse42_pcmpistria128:
12137 case Intrinsic::x86_sse42_pcmpestria128:
12138 case Intrinsic::x86_sse42_pcmpistric128:
12139 case Intrinsic::x86_sse42_pcmpestric128:
12140 case Intrinsic::x86_sse42_pcmpistrio128:
12141 case Intrinsic::x86_sse42_pcmpestrio128:
12142 case Intrinsic::x86_sse42_pcmpistris128:
12143 case Intrinsic::x86_sse42_pcmpestris128:
12144 case Intrinsic::x86_sse42_pcmpistriz128:
12145 case Intrinsic::x86_sse42_pcmpestriz128: {
12149 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12150 case Intrinsic::x86_sse42_pcmpistria128:
12151 Opcode = X86ISD::PCMPISTRI;
12152 X86CC = X86::COND_A;
12154 case Intrinsic::x86_sse42_pcmpestria128:
12155 Opcode = X86ISD::PCMPESTRI;
12156 X86CC = X86::COND_A;
12158 case Intrinsic::x86_sse42_pcmpistric128:
12159 Opcode = X86ISD::PCMPISTRI;
12160 X86CC = X86::COND_B;
12162 case Intrinsic::x86_sse42_pcmpestric128:
12163 Opcode = X86ISD::PCMPESTRI;
12164 X86CC = X86::COND_B;
12166 case Intrinsic::x86_sse42_pcmpistrio128:
12167 Opcode = X86ISD::PCMPISTRI;
12168 X86CC = X86::COND_O;
12170 case Intrinsic::x86_sse42_pcmpestrio128:
12171 Opcode = X86ISD::PCMPESTRI;
12172 X86CC = X86::COND_O;
12174 case Intrinsic::x86_sse42_pcmpistris128:
12175 Opcode = X86ISD::PCMPISTRI;
12176 X86CC = X86::COND_S;
12178 case Intrinsic::x86_sse42_pcmpestris128:
12179 Opcode = X86ISD::PCMPESTRI;
12180 X86CC = X86::COND_S;
12182 case Intrinsic::x86_sse42_pcmpistriz128:
12183 Opcode = X86ISD::PCMPISTRI;
12184 X86CC = X86::COND_E;
12186 case Intrinsic::x86_sse42_pcmpestriz128:
12187 Opcode = X86ISD::PCMPESTRI;
12188 X86CC = X86::COND_E;
12191 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12192 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12193 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
12194 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12195 DAG.getConstant(X86CC, MVT::i8),
12196 SDValue(PCMP.getNode(), 1));
12197 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12200 case Intrinsic::x86_sse42_pcmpistri128:
12201 case Intrinsic::x86_sse42_pcmpestri128: {
12203 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
12204 Opcode = X86ISD::PCMPISTRI;
12206 Opcode = X86ISD::PCMPESTRI;
12208 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12209 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12210 return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
12212 case Intrinsic::x86_fma_vfmadd_ps:
12213 case Intrinsic::x86_fma_vfmadd_pd:
12214 case Intrinsic::x86_fma_vfmsub_ps:
12215 case Intrinsic::x86_fma_vfmsub_pd:
12216 case Intrinsic::x86_fma_vfnmadd_ps:
12217 case Intrinsic::x86_fma_vfnmadd_pd:
12218 case Intrinsic::x86_fma_vfnmsub_ps:
12219 case Intrinsic::x86_fma_vfnmsub_pd:
12220 case Intrinsic::x86_fma_vfmaddsub_ps:
12221 case Intrinsic::x86_fma_vfmaddsub_pd:
12222 case Intrinsic::x86_fma_vfmsubadd_ps:
12223 case Intrinsic::x86_fma_vfmsubadd_pd:
12224 case Intrinsic::x86_fma_vfmadd_ps_256:
12225 case Intrinsic::x86_fma_vfmadd_pd_256:
12226 case Intrinsic::x86_fma_vfmsub_ps_256:
12227 case Intrinsic::x86_fma_vfmsub_pd_256:
12228 case Intrinsic::x86_fma_vfnmadd_ps_256:
12229 case Intrinsic::x86_fma_vfnmadd_pd_256:
12230 case Intrinsic::x86_fma_vfnmsub_ps_256:
12231 case Intrinsic::x86_fma_vfnmsub_pd_256:
12232 case Intrinsic::x86_fma_vfmaddsub_ps_256:
12233 case Intrinsic::x86_fma_vfmaddsub_pd_256:
12234 case Intrinsic::x86_fma_vfmsubadd_ps_256:
12235 case Intrinsic::x86_fma_vfmsubadd_pd_256:
12236 case Intrinsic::x86_fma_vfmadd_ps_512:
12237 case Intrinsic::x86_fma_vfmadd_pd_512:
12238 case Intrinsic::x86_fma_vfmsub_ps_512:
12239 case Intrinsic::x86_fma_vfmsub_pd_512:
12240 case Intrinsic::x86_fma_vfnmadd_ps_512:
12241 case Intrinsic::x86_fma_vfnmadd_pd_512:
12242 case Intrinsic::x86_fma_vfnmsub_ps_512:
12243 case Intrinsic::x86_fma_vfnmsub_pd_512:
12244 case Intrinsic::x86_fma_vfmaddsub_ps_512:
12245 case Intrinsic::x86_fma_vfmaddsub_pd_512:
12246 case Intrinsic::x86_fma_vfmsubadd_ps_512:
12247 case Intrinsic::x86_fma_vfmsubadd_pd_512: {
12250 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12251 case Intrinsic::x86_fma_vfmadd_ps:
12252 case Intrinsic::x86_fma_vfmadd_pd:
12253 case Intrinsic::x86_fma_vfmadd_ps_256:
12254 case Intrinsic::x86_fma_vfmadd_pd_256:
12255 case Intrinsic::x86_fma_vfmadd_ps_512:
12256 case Intrinsic::x86_fma_vfmadd_pd_512:
12257 Opc = X86ISD::FMADD;
12259 case Intrinsic::x86_fma_vfmsub_ps:
12260 case Intrinsic::x86_fma_vfmsub_pd:
12261 case Intrinsic::x86_fma_vfmsub_ps_256:
12262 case Intrinsic::x86_fma_vfmsub_pd_256:
12263 case Intrinsic::x86_fma_vfmsub_ps_512:
12264 case Intrinsic::x86_fma_vfmsub_pd_512:
12265 Opc = X86ISD::FMSUB;
12267 case Intrinsic::x86_fma_vfnmadd_ps:
12268 case Intrinsic::x86_fma_vfnmadd_pd:
12269 case Intrinsic::x86_fma_vfnmadd_ps_256:
12270 case Intrinsic::x86_fma_vfnmadd_pd_256:
12271 case Intrinsic::x86_fma_vfnmadd_ps_512:
12272 case Intrinsic::x86_fma_vfnmadd_pd_512:
12273 Opc = X86ISD::FNMADD;
12275 case Intrinsic::x86_fma_vfnmsub_ps:
12276 case Intrinsic::x86_fma_vfnmsub_pd:
12277 case Intrinsic::x86_fma_vfnmsub_ps_256:
12278 case Intrinsic::x86_fma_vfnmsub_pd_256:
12279 case Intrinsic::x86_fma_vfnmsub_ps_512:
12280 case Intrinsic::x86_fma_vfnmsub_pd_512:
12281 Opc = X86ISD::FNMSUB;
12283 case Intrinsic::x86_fma_vfmaddsub_ps:
12284 case Intrinsic::x86_fma_vfmaddsub_pd:
12285 case Intrinsic::x86_fma_vfmaddsub_ps_256:
12286 case Intrinsic::x86_fma_vfmaddsub_pd_256:
12287 case Intrinsic::x86_fma_vfmaddsub_ps_512:
12288 case Intrinsic::x86_fma_vfmaddsub_pd_512:
12289 Opc = X86ISD::FMADDSUB;
12291 case Intrinsic::x86_fma_vfmsubadd_ps:
12292 case Intrinsic::x86_fma_vfmsubadd_pd:
12293 case Intrinsic::x86_fma_vfmsubadd_ps_256:
12294 case Intrinsic::x86_fma_vfmsubadd_pd_256:
12295 case Intrinsic::x86_fma_vfmsubadd_ps_512:
12296 case Intrinsic::x86_fma_vfmsubadd_pd_512:
12297 Opc = X86ISD::FMSUBADD;
12301 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
12302 Op.getOperand(2), Op.getOperand(3));
12307 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12308 SDValue Base, SDValue Index,
12309 SDValue ScaleOp, SDValue Chain,
12310 const X86Subtarget * Subtarget) {
12312 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12313 assert(C && "Invalid scale type");
12314 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12315 SDValue Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12316 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12317 Index.getSimpleValueType().getVectorNumElements());
12318 SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12319 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12320 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12321 SDValue Segment = DAG.getRegister(0, MVT::i32);
12322 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12323 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12324 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12325 return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
12328 static SDValue getMGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12329 SDValue Src, SDValue Mask, SDValue Base,
12330 SDValue Index, SDValue ScaleOp, SDValue Chain,
12331 const X86Subtarget * Subtarget) {
12333 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12334 assert(C && "Invalid scale type");
12335 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12336 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12337 Index.getSimpleValueType().getVectorNumElements());
12338 SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12339 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12340 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12341 SDValue Segment = DAG.getRegister(0, MVT::i32);
12342 if (Src.getOpcode() == ISD::UNDEF)
12343 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12344 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12345 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12346 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12347 return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
12350 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12351 SDValue Src, SDValue Base, SDValue Index,
12352 SDValue ScaleOp, SDValue Chain) {
12354 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12355 assert(C && "Invalid scale type");
12356 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12357 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12358 SDValue Segment = DAG.getRegister(0, MVT::i32);
12359 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12360 Index.getSimpleValueType().getVectorNumElements());
12361 SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12362 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12363 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12364 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12365 return SDValue(Res, 1);
12368 static SDValue getMScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12369 SDValue Src, SDValue Mask, SDValue Base,
12370 SDValue Index, SDValue ScaleOp, SDValue Chain) {
12372 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12373 assert(C && "Invalid scale type");
12374 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12375 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12376 SDValue Segment = DAG.getRegister(0, MVT::i32);
12377 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12378 Index.getSimpleValueType().getVectorNumElements());
12379 SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12380 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12381 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12382 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12383 return SDValue(Res, 1);
12386 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
12387 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
12388 // also used to custom lower READCYCLECOUNTER nodes.
12389 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
12390 SelectionDAG &DAG, const X86Subtarget *Subtarget,
12391 SmallVectorImpl<SDValue> &Results) {
12392 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12393 SDValue TheChain = N->getOperand(0);
12394 SDValue rd = DAG.getNode(Opcode, DL, Tys, &TheChain, 1);
12397 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
12398 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
12399 // and the EAX register is loaded with the low-order 32 bits.
12400 if (Subtarget->is64Bit()) {
12401 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
12402 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
12405 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
12406 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
12409 SDValue Chain = HI.getValue(1);
12411 if (Opcode == X86ISD::RDTSCP_DAG) {
12412 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
12414 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
12415 // the ECX register. Add 'ecx' explicitly to the chain.
12416 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
12418 // Explicitly store the content of ECX at the location passed in input
12419 // to the 'rdtscp' intrinsic.
12420 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
12421 MachinePointerInfo(), false, false, 0);
12424 if (Subtarget->is64Bit()) {
12425 // The EDX register is loaded with the high-order 32 bits of the MSR, and
12426 // the EAX register is loaded with the low-order 32 bits.
12427 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
12428 DAG.getConstant(32, MVT::i8));
12429 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
12430 Results.push_back(Chain);
12434 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12435 SDValue Ops[] = { LO, HI };
12436 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops,
12437 array_lengthof(Ops));
12438 Results.push_back(Pair);
12439 Results.push_back(Chain);
12442 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12443 SelectionDAG &DAG) {
12444 SmallVector<SDValue, 2> Results;
12446 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
12448 return DAG.getMergeValues(&Results[0], Results.size(), DL);
12451 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
12452 SelectionDAG &DAG) {
12454 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12456 default: return SDValue(); // Don't custom lower most intrinsics.
12458 // RDRAND/RDSEED intrinsics.
12459 case Intrinsic::x86_rdrand_16:
12460 case Intrinsic::x86_rdrand_32:
12461 case Intrinsic::x86_rdrand_64:
12462 case Intrinsic::x86_rdseed_16:
12463 case Intrinsic::x86_rdseed_32:
12464 case Intrinsic::x86_rdseed_64: {
12465 unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
12466 IntNo == Intrinsic::x86_rdseed_32 ||
12467 IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
12469 // Emit the node with the right value type.
12470 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
12471 SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
12473 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
12474 // Otherwise return the value from Rand, which is always 0, casted to i32.
12475 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
12476 DAG.getConstant(1, Op->getValueType(1)),
12477 DAG.getConstant(X86::COND_B, MVT::i32),
12478 SDValue(Result.getNode(), 1) };
12479 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
12480 DAG.getVTList(Op->getValueType(1), MVT::Glue),
12481 Ops, array_lengthof(Ops));
12483 // Return { result, isValid, chain }.
12484 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
12485 SDValue(Result.getNode(), 2));
12487 //int_gather(index, base, scale);
12488 case Intrinsic::x86_avx512_gather_qpd_512:
12489 case Intrinsic::x86_avx512_gather_qps_512:
12490 case Intrinsic::x86_avx512_gather_dpd_512:
12491 case Intrinsic::x86_avx512_gather_qpi_512:
12492 case Intrinsic::x86_avx512_gather_qpq_512:
12493 case Intrinsic::x86_avx512_gather_dpq_512:
12494 case Intrinsic::x86_avx512_gather_dps_512:
12495 case Intrinsic::x86_avx512_gather_dpi_512: {
12498 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12499 case Intrinsic::x86_avx512_gather_qps_512: Opc = X86::VGATHERQPSZrm; break;
12500 case Intrinsic::x86_avx512_gather_qpd_512: Opc = X86::VGATHERQPDZrm; break;
12501 case Intrinsic::x86_avx512_gather_dpd_512: Opc = X86::VGATHERDPDZrm; break;
12502 case Intrinsic::x86_avx512_gather_dps_512: Opc = X86::VGATHERDPSZrm; break;
12503 case Intrinsic::x86_avx512_gather_qpi_512: Opc = X86::VPGATHERQDZrm; break;
12504 case Intrinsic::x86_avx512_gather_qpq_512: Opc = X86::VPGATHERQQZrm; break;
12505 case Intrinsic::x86_avx512_gather_dpi_512: Opc = X86::VPGATHERDDZrm; break;
12506 case Intrinsic::x86_avx512_gather_dpq_512: Opc = X86::VPGATHERDQZrm; break;
12508 SDValue Chain = Op.getOperand(0);
12509 SDValue Index = Op.getOperand(2);
12510 SDValue Base = Op.getOperand(3);
12511 SDValue Scale = Op.getOperand(4);
12512 return getGatherNode(Opc, Op, DAG, Base, Index, Scale, Chain, Subtarget);
12514 //int_gather_mask(v1, mask, index, base, scale);
12515 case Intrinsic::x86_avx512_gather_qps_mask_512:
12516 case Intrinsic::x86_avx512_gather_qpd_mask_512:
12517 case Intrinsic::x86_avx512_gather_dpd_mask_512:
12518 case Intrinsic::x86_avx512_gather_dps_mask_512:
12519 case Intrinsic::x86_avx512_gather_qpi_mask_512:
12520 case Intrinsic::x86_avx512_gather_qpq_mask_512:
12521 case Intrinsic::x86_avx512_gather_dpi_mask_512:
12522 case Intrinsic::x86_avx512_gather_dpq_mask_512: {
12525 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12526 case Intrinsic::x86_avx512_gather_qps_mask_512:
12527 Opc = X86::VGATHERQPSZrm; break;
12528 case Intrinsic::x86_avx512_gather_qpd_mask_512:
12529 Opc = X86::VGATHERQPDZrm; break;
12530 case Intrinsic::x86_avx512_gather_dpd_mask_512:
12531 Opc = X86::VGATHERDPDZrm; break;
12532 case Intrinsic::x86_avx512_gather_dps_mask_512:
12533 Opc = X86::VGATHERDPSZrm; break;
12534 case Intrinsic::x86_avx512_gather_qpi_mask_512:
12535 Opc = X86::VPGATHERQDZrm; break;
12536 case Intrinsic::x86_avx512_gather_qpq_mask_512:
12537 Opc = X86::VPGATHERQQZrm; break;
12538 case Intrinsic::x86_avx512_gather_dpi_mask_512:
12539 Opc = X86::VPGATHERDDZrm; break;
12540 case Intrinsic::x86_avx512_gather_dpq_mask_512:
12541 Opc = X86::VPGATHERDQZrm; break;
12543 SDValue Chain = Op.getOperand(0);
12544 SDValue Src = Op.getOperand(2);
12545 SDValue Mask = Op.getOperand(3);
12546 SDValue Index = Op.getOperand(4);
12547 SDValue Base = Op.getOperand(5);
12548 SDValue Scale = Op.getOperand(6);
12549 return getMGatherNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
12552 //int_scatter(base, index, v1, scale);
12553 case Intrinsic::x86_avx512_scatter_qpd_512:
12554 case Intrinsic::x86_avx512_scatter_qps_512:
12555 case Intrinsic::x86_avx512_scatter_dpd_512:
12556 case Intrinsic::x86_avx512_scatter_qpi_512:
12557 case Intrinsic::x86_avx512_scatter_qpq_512:
12558 case Intrinsic::x86_avx512_scatter_dpq_512:
12559 case Intrinsic::x86_avx512_scatter_dps_512:
12560 case Intrinsic::x86_avx512_scatter_dpi_512: {
12563 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12564 case Intrinsic::x86_avx512_scatter_qpd_512:
12565 Opc = X86::VSCATTERQPDZmr; break;
12566 case Intrinsic::x86_avx512_scatter_qps_512:
12567 Opc = X86::VSCATTERQPSZmr; break;
12568 case Intrinsic::x86_avx512_scatter_dpd_512:
12569 Opc = X86::VSCATTERDPDZmr; break;
12570 case Intrinsic::x86_avx512_scatter_dps_512:
12571 Opc = X86::VSCATTERDPSZmr; break;
12572 case Intrinsic::x86_avx512_scatter_qpi_512:
12573 Opc = X86::VPSCATTERQDZmr; break;
12574 case Intrinsic::x86_avx512_scatter_qpq_512:
12575 Opc = X86::VPSCATTERQQZmr; break;
12576 case Intrinsic::x86_avx512_scatter_dpq_512:
12577 Opc = X86::VPSCATTERDQZmr; break;
12578 case Intrinsic::x86_avx512_scatter_dpi_512:
12579 Opc = X86::VPSCATTERDDZmr; break;
12581 SDValue Chain = Op.getOperand(0);
12582 SDValue Base = Op.getOperand(2);
12583 SDValue Index = Op.getOperand(3);
12584 SDValue Src = Op.getOperand(4);
12585 SDValue Scale = Op.getOperand(5);
12586 return getScatterNode(Opc, Op, DAG, Src, Base, Index, Scale, Chain);
12588 //int_scatter_mask(base, mask, index, v1, scale);
12589 case Intrinsic::x86_avx512_scatter_qps_mask_512:
12590 case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12591 case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12592 case Intrinsic::x86_avx512_scatter_dps_mask_512:
12593 case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12594 case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12595 case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12596 case Intrinsic::x86_avx512_scatter_dpq_mask_512: {
12599 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12600 case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12601 Opc = X86::VSCATTERQPDZmr; break;
12602 case Intrinsic::x86_avx512_scatter_qps_mask_512:
12603 Opc = X86::VSCATTERQPSZmr; break;
12604 case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12605 Opc = X86::VSCATTERDPDZmr; break;
12606 case Intrinsic::x86_avx512_scatter_dps_mask_512:
12607 Opc = X86::VSCATTERDPSZmr; break;
12608 case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12609 Opc = X86::VPSCATTERQDZmr; break;
12610 case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12611 Opc = X86::VPSCATTERQQZmr; break;
12612 case Intrinsic::x86_avx512_scatter_dpq_mask_512:
12613 Opc = X86::VPSCATTERDQZmr; break;
12614 case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12615 Opc = X86::VPSCATTERDDZmr; break;
12617 SDValue Chain = Op.getOperand(0);
12618 SDValue Base = Op.getOperand(2);
12619 SDValue Mask = Op.getOperand(3);
12620 SDValue Index = Op.getOperand(4);
12621 SDValue Src = Op.getOperand(5);
12622 SDValue Scale = Op.getOperand(6);
12623 return getMScatterNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
12625 // Read Time Stamp Counter (RDTSC).
12626 case Intrinsic::x86_rdtsc:
12627 // Read Time Stamp Counter and Processor ID (RDTSCP).
12628 case Intrinsic::x86_rdtscp: {
12631 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12632 case Intrinsic::x86_rdtsc:
12633 Opc = X86ISD::RDTSC_DAG; break;
12634 case Intrinsic::x86_rdtscp:
12635 Opc = X86ISD::RDTSCP_DAG; break;
12637 SmallVector<SDValue, 2> Results;
12638 getReadTimeStampCounter(Op.getNode(), dl, Opc, DAG, Subtarget, Results);
12639 return DAG.getMergeValues(&Results[0], Results.size(), dl);
12641 // XTEST intrinsics.
12642 case Intrinsic::x86_xtest: {
12643 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
12644 SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
12645 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12646 DAG.getConstant(X86::COND_NE, MVT::i8),
12648 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
12649 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
12650 Ret, SDValue(InTrans.getNode(), 1));
12655 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
12656 SelectionDAG &DAG) const {
12657 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12658 MFI->setReturnAddressIsTaken(true);
12660 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
12663 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12665 EVT PtrVT = getPointerTy();
12668 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12669 const X86RegisterInfo *RegInfo =
12670 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12671 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
12672 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12673 DAG.getNode(ISD::ADD, dl, PtrVT,
12674 FrameAddr, Offset),
12675 MachinePointerInfo(), false, false, false, 0);
12678 // Just load the return address.
12679 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
12680 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12681 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
12684 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
12685 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12686 MFI->setFrameAddressIsTaken(true);
12688 EVT VT = Op.getValueType();
12689 SDLoc dl(Op); // FIXME probably not meaningful
12690 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12691 const X86RegisterInfo *RegInfo =
12692 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12693 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12694 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
12695 (FrameReg == X86::EBP && VT == MVT::i32)) &&
12696 "Invalid Frame Register!");
12697 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
12699 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
12700 MachinePointerInfo(),
12701 false, false, false, 0);
12705 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
12706 SelectionDAG &DAG) const {
12707 const X86RegisterInfo *RegInfo =
12708 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12709 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
12712 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
12713 SDValue Chain = Op.getOperand(0);
12714 SDValue Offset = Op.getOperand(1);
12715 SDValue Handler = Op.getOperand(2);
12718 EVT PtrVT = getPointerTy();
12719 const X86RegisterInfo *RegInfo =
12720 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12721 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12722 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
12723 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
12724 "Invalid Frame Register!");
12725 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
12726 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
12728 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
12729 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
12730 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
12731 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
12733 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
12735 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
12736 DAG.getRegister(StoreAddrReg, PtrVT));
12739 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
12740 SelectionDAG &DAG) const {
12742 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
12743 DAG.getVTList(MVT::i32, MVT::Other),
12744 Op.getOperand(0), Op.getOperand(1));
12747 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
12748 SelectionDAG &DAG) const {
12750 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
12751 Op.getOperand(0), Op.getOperand(1));
12754 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
12755 return Op.getOperand(0);
12758 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
12759 SelectionDAG &DAG) const {
12760 SDValue Root = Op.getOperand(0);
12761 SDValue Trmp = Op.getOperand(1); // trampoline
12762 SDValue FPtr = Op.getOperand(2); // nested function
12763 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
12766 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
12767 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12769 if (Subtarget->is64Bit()) {
12770 SDValue OutChains[6];
12772 // Large code-model.
12773 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
12774 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
12776 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
12777 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
12779 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
12781 // Load the pointer to the nested function into R11.
12782 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
12783 SDValue Addr = Trmp;
12784 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12785 Addr, MachinePointerInfo(TrmpAddr),
12788 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12789 DAG.getConstant(2, MVT::i64));
12790 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
12791 MachinePointerInfo(TrmpAddr, 2),
12794 // Load the 'nest' parameter value into R10.
12795 // R10 is specified in X86CallingConv.td
12796 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
12797 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12798 DAG.getConstant(10, MVT::i64));
12799 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12800 Addr, MachinePointerInfo(TrmpAddr, 10),
12803 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12804 DAG.getConstant(12, MVT::i64));
12805 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
12806 MachinePointerInfo(TrmpAddr, 12),
12809 // Jump to the nested function.
12810 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
12811 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12812 DAG.getConstant(20, MVT::i64));
12813 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12814 Addr, MachinePointerInfo(TrmpAddr, 20),
12817 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
12818 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12819 DAG.getConstant(22, MVT::i64));
12820 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
12821 MachinePointerInfo(TrmpAddr, 22),
12824 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
12826 const Function *Func =
12827 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
12828 CallingConv::ID CC = Func->getCallingConv();
12833 llvm_unreachable("Unsupported calling convention");
12834 case CallingConv::C:
12835 case CallingConv::X86_StdCall: {
12836 // Pass 'nest' parameter in ECX.
12837 // Must be kept in sync with X86CallingConv.td
12838 NestReg = X86::ECX;
12840 // Check that ECX wasn't needed by an 'inreg' parameter.
12841 FunctionType *FTy = Func->getFunctionType();
12842 const AttributeSet &Attrs = Func->getAttributes();
12844 if (!Attrs.isEmpty() && !Func->isVarArg()) {
12845 unsigned InRegCount = 0;
12848 for (FunctionType::param_iterator I = FTy->param_begin(),
12849 E = FTy->param_end(); I != E; ++I, ++Idx)
12850 if (Attrs.hasAttribute(Idx, Attribute::InReg))
12851 // FIXME: should only count parameters that are lowered to integers.
12852 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
12854 if (InRegCount > 2) {
12855 report_fatal_error("Nest register in use - reduce number of inreg"
12861 case CallingConv::X86_FastCall:
12862 case CallingConv::X86_ThisCall:
12863 case CallingConv::Fast:
12864 // Pass 'nest' parameter in EAX.
12865 // Must be kept in sync with X86CallingConv.td
12866 NestReg = X86::EAX;
12870 SDValue OutChains[4];
12871 SDValue Addr, Disp;
12873 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12874 DAG.getConstant(10, MVT::i32));
12875 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
12877 // This is storing the opcode for MOV32ri.
12878 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
12879 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
12880 OutChains[0] = DAG.getStore(Root, dl,
12881 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
12882 Trmp, MachinePointerInfo(TrmpAddr),
12885 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12886 DAG.getConstant(1, MVT::i32));
12887 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
12888 MachinePointerInfo(TrmpAddr, 1),
12891 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
12892 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12893 DAG.getConstant(5, MVT::i32));
12894 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
12895 MachinePointerInfo(TrmpAddr, 5),
12898 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12899 DAG.getConstant(6, MVT::i32));
12900 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
12901 MachinePointerInfo(TrmpAddr, 6),
12904 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
12908 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
12909 SelectionDAG &DAG) const {
12911 The rounding mode is in bits 11:10 of FPSR, and has the following
12913 00 Round to nearest
12918 FLT_ROUNDS, on the other hand, expects the following:
12925 To perform the conversion, we do:
12926 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
12929 MachineFunction &MF = DAG.getMachineFunction();
12930 const TargetMachine &TM = MF.getTarget();
12931 const TargetFrameLowering &TFI = *TM.getFrameLowering();
12932 unsigned StackAlignment = TFI.getStackAlignment();
12933 MVT VT = Op.getSimpleValueType();
12936 // Save FP Control Word to stack slot
12937 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
12938 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12940 MachineMemOperand *MMO =
12941 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12942 MachineMemOperand::MOStore, 2, 2);
12944 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
12945 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
12946 DAG.getVTList(MVT::Other),
12947 Ops, array_lengthof(Ops), MVT::i16,
12950 // Load FP Control Word from stack slot
12951 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
12952 MachinePointerInfo(), false, false, false, 0);
12954 // Transform as necessary
12956 DAG.getNode(ISD::SRL, DL, MVT::i16,
12957 DAG.getNode(ISD::AND, DL, MVT::i16,
12958 CWD, DAG.getConstant(0x800, MVT::i16)),
12959 DAG.getConstant(11, MVT::i8));
12961 DAG.getNode(ISD::SRL, DL, MVT::i16,
12962 DAG.getNode(ISD::AND, DL, MVT::i16,
12963 CWD, DAG.getConstant(0x400, MVT::i16)),
12964 DAG.getConstant(9, MVT::i8));
12967 DAG.getNode(ISD::AND, DL, MVT::i16,
12968 DAG.getNode(ISD::ADD, DL, MVT::i16,
12969 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
12970 DAG.getConstant(1, MVT::i16)),
12971 DAG.getConstant(3, MVT::i16));
12973 return DAG.getNode((VT.getSizeInBits() < 16 ?
12974 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
12977 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
12978 MVT VT = Op.getSimpleValueType();
12980 unsigned NumBits = VT.getSizeInBits();
12983 Op = Op.getOperand(0);
12984 if (VT == MVT::i8) {
12985 // Zero extend to i32 since there is not an i8 bsr.
12987 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
12990 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
12991 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12992 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
12994 // If src is zero (i.e. bsr sets ZF), returns NumBits.
12997 DAG.getConstant(NumBits+NumBits-1, OpVT),
12998 DAG.getConstant(X86::COND_E, MVT::i8),
13001 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
13003 // Finally xor with NumBits-1.
13004 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13007 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13011 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
13012 MVT VT = Op.getSimpleValueType();
13014 unsigned NumBits = VT.getSizeInBits();
13017 Op = Op.getOperand(0);
13018 if (VT == MVT::i8) {
13019 // Zero extend to i32 since there is not an i8 bsr.
13021 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13024 // Issue a bsr (scan bits in reverse).
13025 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13026 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13028 // And xor with NumBits-1.
13029 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13032 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13036 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
13037 MVT VT = Op.getSimpleValueType();
13038 unsigned NumBits = VT.getSizeInBits();
13040 Op = Op.getOperand(0);
13042 // Issue a bsf (scan bits forward) which also sets EFLAGS.
13043 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13044 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
13046 // If src is zero (i.e. bsf sets ZF), returns NumBits.
13049 DAG.getConstant(NumBits, VT),
13050 DAG.getConstant(X86::COND_E, MVT::i8),
13053 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
13056 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
13057 // ones, and then concatenate the result back.
13058 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
13059 MVT VT = Op.getSimpleValueType();
13061 assert(VT.is256BitVector() && VT.isInteger() &&
13062 "Unsupported value type for operation");
13064 unsigned NumElems = VT.getVectorNumElements();
13067 // Extract the LHS vectors
13068 SDValue LHS = Op.getOperand(0);
13069 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13070 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13072 // Extract the RHS vectors
13073 SDValue RHS = Op.getOperand(1);
13074 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13075 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13077 MVT EltVT = VT.getVectorElementType();
13078 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13080 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13081 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
13082 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
13085 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
13086 assert(Op.getSimpleValueType().is256BitVector() &&
13087 Op.getSimpleValueType().isInteger() &&
13088 "Only handle AVX 256-bit vector integer operation");
13089 return Lower256IntArith(Op, DAG);
13092 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
13093 assert(Op.getSimpleValueType().is256BitVector() &&
13094 Op.getSimpleValueType().isInteger() &&
13095 "Only handle AVX 256-bit vector integer operation");
13096 return Lower256IntArith(Op, DAG);
13099 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
13100 SelectionDAG &DAG) {
13102 MVT VT = Op.getSimpleValueType();
13104 // Decompose 256-bit ops into smaller 128-bit ops.
13105 if (VT.is256BitVector() && !Subtarget->hasInt256())
13106 return Lower256IntArith(Op, DAG);
13108 SDValue A = Op.getOperand(0);
13109 SDValue B = Op.getOperand(1);
13111 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
13112 if (VT == MVT::v4i32) {
13113 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
13114 "Should not custom lower when pmuldq is available!");
13116 // Extract the odd parts.
13117 static const int UnpackMask[] = { 1, -1, 3, -1 };
13118 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
13119 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
13121 // Multiply the even parts.
13122 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
13123 // Now multiply odd parts.
13124 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
13126 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
13127 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
13129 // Merge the two vectors back together with a shuffle. This expands into 2
13131 static const int ShufMask[] = { 0, 4, 2, 6 };
13132 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
13135 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
13136 "Only know how to lower V2I64/V4I64/V8I64 multiply");
13138 // Ahi = psrlqi(a, 32);
13139 // Bhi = psrlqi(b, 32);
13141 // AloBlo = pmuludq(a, b);
13142 // AloBhi = pmuludq(a, Bhi);
13143 // AhiBlo = pmuludq(Ahi, b);
13145 // AloBhi = psllqi(AloBhi, 32);
13146 // AhiBlo = psllqi(AhiBlo, 32);
13147 // return AloBlo + AloBhi + AhiBlo;
13149 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
13150 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
13152 // Bit cast to 32-bit vectors for MULUDQ
13153 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
13154 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
13155 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
13156 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
13157 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
13158 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
13160 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
13161 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
13162 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
13164 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
13165 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
13167 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
13168 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
13171 static SDValue LowerUMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
13172 SelectionDAG &DAG) {
13173 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
13174 EVT VT = Op0.getValueType();
13177 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
13178 (VT == MVT::v8i32 && Subtarget->hasInt256()));
13180 // Get the high parts.
13181 const int Mask[] = {1, 2, 3, 4, 5, 6, 7, 8};
13182 SDValue Hi0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
13183 SDValue Hi1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
13185 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
13187 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
13188 SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
13189 DAG.getNode(X86ISD::PMULUDQ, dl, MulVT, Op0, Op1));
13190 SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
13191 DAG.getNode(X86ISD::PMULUDQ, dl, MulVT, Hi0, Hi1));
13193 // Shuffle it back into the right order.
13194 const int HighMask[] = {1, 3, 5, 7, 9, 11, 13, 15};
13195 SDValue Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
13196 const int LowMask[] = {0, 2, 4, 6, 8, 10, 12, 14};
13197 SDValue Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
13199 return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Highs, Lows);
13202 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
13203 const X86Subtarget *Subtarget) {
13204 MVT VT = Op.getSimpleValueType();
13206 SDValue R = Op.getOperand(0);
13207 SDValue Amt = Op.getOperand(1);
13209 // Optimize shl/srl/sra with constant shift amount.
13210 if (isSplatVector(Amt.getNode())) {
13211 SDValue SclrAmt = Amt->getOperand(0);
13212 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
13213 uint64_t ShiftAmt = C->getZExtValue();
13215 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
13216 (Subtarget->hasInt256() &&
13217 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13218 (Subtarget->hasAVX512() &&
13219 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13220 if (Op.getOpcode() == ISD::SHL)
13221 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13223 if (Op.getOpcode() == ISD::SRL)
13224 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13226 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
13227 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13231 if (VT == MVT::v16i8) {
13232 if (Op.getOpcode() == ISD::SHL) {
13233 // Make a large shift.
13234 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13235 MVT::v8i16, R, ShiftAmt,
13237 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13238 // Zero out the rightmost bits.
13239 SmallVector<SDValue, 16> V(16,
13240 DAG.getConstant(uint8_t(-1U << ShiftAmt),
13242 return DAG.getNode(ISD::AND, dl, VT, SHL,
13243 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
13245 if (Op.getOpcode() == ISD::SRL) {
13246 // Make a large shift.
13247 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13248 MVT::v8i16, R, ShiftAmt,
13250 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13251 // Zero out the leftmost bits.
13252 SmallVector<SDValue, 16> V(16,
13253 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13255 return DAG.getNode(ISD::AND, dl, VT, SRL,
13256 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
13258 if (Op.getOpcode() == ISD::SRA) {
13259 if (ShiftAmt == 7) {
13260 // R s>> 7 === R s< 0
13261 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13262 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13265 // R s>> a === ((R u>> a) ^ m) - m
13266 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13267 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
13269 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
13270 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13271 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13274 llvm_unreachable("Unknown shift opcode.");
13277 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
13278 if (Op.getOpcode() == ISD::SHL) {
13279 // Make a large shift.
13280 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13281 MVT::v16i16, R, ShiftAmt,
13283 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13284 // Zero out the rightmost bits.
13285 SmallVector<SDValue, 32> V(32,
13286 DAG.getConstant(uint8_t(-1U << ShiftAmt),
13288 return DAG.getNode(ISD::AND, dl, VT, SHL,
13289 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
13291 if (Op.getOpcode() == ISD::SRL) {
13292 // Make a large shift.
13293 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13294 MVT::v16i16, R, ShiftAmt,
13296 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13297 // Zero out the leftmost bits.
13298 SmallVector<SDValue, 32> V(32,
13299 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13301 return DAG.getNode(ISD::AND, dl, VT, SRL,
13302 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
13304 if (Op.getOpcode() == ISD::SRA) {
13305 if (ShiftAmt == 7) {
13306 // R s>> 7 === R s< 0
13307 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13308 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13311 // R s>> a === ((R u>> a) ^ m) - m
13312 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13313 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
13315 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
13316 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13317 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13320 llvm_unreachable("Unknown shift opcode.");
13325 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13326 if (!Subtarget->is64Bit() &&
13327 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
13328 Amt.getOpcode() == ISD::BITCAST &&
13329 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13330 Amt = Amt.getOperand(0);
13331 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13332 VT.getVectorNumElements();
13333 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
13334 uint64_t ShiftAmt = 0;
13335 for (unsigned i = 0; i != Ratio; ++i) {
13336 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
13340 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
13342 // Check remaining shift amounts.
13343 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13344 uint64_t ShAmt = 0;
13345 for (unsigned j = 0; j != Ratio; ++j) {
13346 ConstantSDNode *C =
13347 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
13351 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
13353 if (ShAmt != ShiftAmt)
13356 switch (Op.getOpcode()) {
13358 llvm_unreachable("Unknown shift opcode!");
13360 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13363 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13366 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13374 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
13375 const X86Subtarget* Subtarget) {
13376 MVT VT = Op.getSimpleValueType();
13378 SDValue R = Op.getOperand(0);
13379 SDValue Amt = Op.getOperand(1);
13381 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
13382 VT == MVT::v4i32 || VT == MVT::v8i16 ||
13383 (Subtarget->hasInt256() &&
13384 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
13385 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13386 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13388 EVT EltVT = VT.getVectorElementType();
13390 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13391 unsigned NumElts = VT.getVectorNumElements();
13393 for (i = 0; i != NumElts; ++i) {
13394 if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
13398 for (j = i; j != NumElts; ++j) {
13399 SDValue Arg = Amt.getOperand(j);
13400 if (Arg.getOpcode() == ISD::UNDEF) continue;
13401 if (Arg != Amt.getOperand(i))
13404 if (i != NumElts && j == NumElts)
13405 BaseShAmt = Amt.getOperand(i);
13407 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13408 Amt = Amt.getOperand(0);
13409 if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
13410 cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
13411 SDValue InVec = Amt.getOperand(0);
13412 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13413 unsigned NumElts = InVec.getValueType().getVectorNumElements();
13415 for (; i != NumElts; ++i) {
13416 SDValue Arg = InVec.getOperand(i);
13417 if (Arg.getOpcode() == ISD::UNDEF) continue;
13421 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13422 if (ConstantSDNode *C =
13423 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13424 unsigned SplatIdx =
13425 cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
13426 if (C->getZExtValue() == SplatIdx)
13427 BaseShAmt = InVec.getOperand(1);
13430 if (!BaseShAmt.getNode())
13431 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
13432 DAG.getIntPtrConstant(0));
13436 if (BaseShAmt.getNode()) {
13437 if (EltVT.bitsGT(MVT::i32))
13438 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
13439 else if (EltVT.bitsLT(MVT::i32))
13440 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
13442 switch (Op.getOpcode()) {
13444 llvm_unreachable("Unknown shift opcode!");
13446 switch (VT.SimpleTy) {
13447 default: return SDValue();
13456 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
13459 switch (VT.SimpleTy) {
13460 default: return SDValue();
13467 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
13470 switch (VT.SimpleTy) {
13471 default: return SDValue();
13480 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
13486 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13487 if (!Subtarget->is64Bit() &&
13488 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
13489 (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
13490 Amt.getOpcode() == ISD::BITCAST &&
13491 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13492 Amt = Amt.getOperand(0);
13493 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13494 VT.getVectorNumElements();
13495 std::vector<SDValue> Vals(Ratio);
13496 for (unsigned i = 0; i != Ratio; ++i)
13497 Vals[i] = Amt.getOperand(i);
13498 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13499 for (unsigned j = 0; j != Ratio; ++j)
13500 if (Vals[j] != Amt.getOperand(i + j))
13503 switch (Op.getOpcode()) {
13505 llvm_unreachable("Unknown shift opcode!");
13507 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
13509 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
13511 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
13518 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
13519 SelectionDAG &DAG) {
13521 MVT VT = Op.getSimpleValueType();
13523 SDValue R = Op.getOperand(0);
13524 SDValue Amt = Op.getOperand(1);
13527 if (!Subtarget->hasSSE2())
13530 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
13534 V = LowerScalarVariableShift(Op, DAG, Subtarget);
13538 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
13540 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
13541 if (Subtarget->hasInt256()) {
13542 if (Op.getOpcode() == ISD::SRL &&
13543 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13544 VT == MVT::v4i64 || VT == MVT::v8i32))
13546 if (Op.getOpcode() == ISD::SHL &&
13547 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13548 VT == MVT::v4i64 || VT == MVT::v8i32))
13550 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
13554 // If possible, lower this packed shift into a vector multiply instead of
13555 // expanding it into a sequence of scalar shifts.
13556 // Do this only if the vector shift count is a constant build_vector.
13557 if (Op.getOpcode() == ISD::SHL &&
13558 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
13559 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
13560 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13561 SmallVector<SDValue, 8> Elts;
13562 EVT SVT = VT.getScalarType();
13563 unsigned SVTBits = SVT.getSizeInBits();
13564 const APInt &One = APInt(SVTBits, 1);
13565 unsigned NumElems = VT.getVectorNumElements();
13567 for (unsigned i=0; i !=NumElems; ++i) {
13568 SDValue Op = Amt->getOperand(i);
13569 if (Op->getOpcode() == ISD::UNDEF) {
13570 Elts.push_back(Op);
13574 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
13575 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
13576 uint64_t ShAmt = C.getZExtValue();
13577 if (ShAmt >= SVTBits) {
13578 Elts.push_back(DAG.getUNDEF(SVT));
13581 Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
13583 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Elts[0], NumElems);
13584 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
13587 // Lower SHL with variable shift amount.
13588 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
13589 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
13591 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
13592 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
13593 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
13594 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
13597 // If possible, lower this shift as a sequence of two shifts by
13598 // constant plus a MOVSS/MOVSD instead of scalarizing it.
13600 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
13602 // Could be rewritten as:
13603 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
13605 // The advantage is that the two shifts from the example would be
13606 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
13607 // the vector shift into four scalar shifts plus four pairs of vector
13609 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
13610 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13611 unsigned TargetOpcode = X86ISD::MOVSS;
13612 bool CanBeSimplified;
13613 // The splat value for the first packed shift (the 'X' from the example).
13614 SDValue Amt1 = Amt->getOperand(0);
13615 // The splat value for the second packed shift (the 'Y' from the example).
13616 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
13617 Amt->getOperand(2);
13619 // See if it is possible to replace this node with a sequence of
13620 // two shifts followed by a MOVSS/MOVSD
13621 if (VT == MVT::v4i32) {
13622 // Check if it is legal to use a MOVSS.
13623 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
13624 Amt2 == Amt->getOperand(3);
13625 if (!CanBeSimplified) {
13626 // Otherwise, check if we can still simplify this node using a MOVSD.
13627 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
13628 Amt->getOperand(2) == Amt->getOperand(3);
13629 TargetOpcode = X86ISD::MOVSD;
13630 Amt2 = Amt->getOperand(2);
13633 // Do similar checks for the case where the machine value type
13635 CanBeSimplified = Amt1 == Amt->getOperand(1);
13636 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
13637 CanBeSimplified = Amt2 == Amt->getOperand(i);
13639 if (!CanBeSimplified) {
13640 TargetOpcode = X86ISD::MOVSD;
13641 CanBeSimplified = true;
13642 Amt2 = Amt->getOperand(4);
13643 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
13644 CanBeSimplified = Amt1 == Amt->getOperand(i);
13645 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
13646 CanBeSimplified = Amt2 == Amt->getOperand(j);
13650 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
13651 isa<ConstantSDNode>(Amt2)) {
13652 // Replace this node with two shifts followed by a MOVSS/MOVSD.
13653 EVT CastVT = MVT::v4i32;
13655 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
13656 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
13658 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
13659 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
13660 if (TargetOpcode == X86ISD::MOVSD)
13661 CastVT = MVT::v2i64;
13662 SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
13663 SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
13664 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
13666 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13670 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
13671 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
13674 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
13675 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
13677 // Turn 'a' into a mask suitable for VSELECT
13678 SDValue VSelM = DAG.getConstant(0x80, VT);
13679 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13680 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13682 SDValue CM1 = DAG.getConstant(0x0f, VT);
13683 SDValue CM2 = DAG.getConstant(0x3f, VT);
13685 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
13686 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
13687 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
13688 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13689 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13692 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13693 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13694 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13696 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
13697 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
13698 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
13699 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13700 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13703 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13704 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13705 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13707 // return VSELECT(r, r+r, a);
13708 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
13709 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
13713 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
13714 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
13715 // solution better.
13716 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
13717 MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
13719 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
13720 R = DAG.getNode(ExtOpc, dl, NewVT, R);
13721 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
13722 return DAG.getNode(ISD::TRUNCATE, dl, VT,
13723 DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
13726 // Decompose 256-bit shifts into smaller 128-bit shifts.
13727 if (VT.is256BitVector()) {
13728 unsigned NumElems = VT.getVectorNumElements();
13729 MVT EltVT = VT.getVectorElementType();
13730 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13732 // Extract the two vectors
13733 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
13734 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
13736 // Recreate the shift amount vectors
13737 SDValue Amt1, Amt2;
13738 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13739 // Constant shift amount
13740 SmallVector<SDValue, 4> Amt1Csts;
13741 SmallVector<SDValue, 4> Amt2Csts;
13742 for (unsigned i = 0; i != NumElems/2; ++i)
13743 Amt1Csts.push_back(Amt->getOperand(i));
13744 for (unsigned i = NumElems/2; i != NumElems; ++i)
13745 Amt2Csts.push_back(Amt->getOperand(i));
13747 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
13748 &Amt1Csts[0], NumElems/2);
13749 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
13750 &Amt2Csts[0], NumElems/2);
13752 // Variable shift amount
13753 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
13754 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
13757 // Issue new vector shifts for the smaller types
13758 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
13759 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
13761 // Concatenate the result back
13762 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
13768 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
13769 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
13770 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
13771 // looks for this combo and may remove the "setcc" instruction if the "setcc"
13772 // has only one use.
13773 SDNode *N = Op.getNode();
13774 SDValue LHS = N->getOperand(0);
13775 SDValue RHS = N->getOperand(1);
13776 unsigned BaseOp = 0;
13779 switch (Op.getOpcode()) {
13780 default: llvm_unreachable("Unknown ovf instruction!");
13782 // A subtract of one will be selected as a INC. Note that INC doesn't
13783 // set CF, so we can't do this for UADDO.
13784 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13786 BaseOp = X86ISD::INC;
13787 Cond = X86::COND_O;
13790 BaseOp = X86ISD::ADD;
13791 Cond = X86::COND_O;
13794 BaseOp = X86ISD::ADD;
13795 Cond = X86::COND_B;
13798 // A subtract of one will be selected as a DEC. Note that DEC doesn't
13799 // set CF, so we can't do this for USUBO.
13800 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13802 BaseOp = X86ISD::DEC;
13803 Cond = X86::COND_O;
13806 BaseOp = X86ISD::SUB;
13807 Cond = X86::COND_O;
13810 BaseOp = X86ISD::SUB;
13811 Cond = X86::COND_B;
13814 BaseOp = X86ISD::SMUL;
13815 Cond = X86::COND_O;
13817 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
13818 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
13820 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
13823 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13824 DAG.getConstant(X86::COND_O, MVT::i32),
13825 SDValue(Sum.getNode(), 2));
13827 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13831 // Also sets EFLAGS.
13832 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
13833 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
13836 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
13837 DAG.getConstant(Cond, MVT::i32),
13838 SDValue(Sum.getNode(), 1));
13840 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13843 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
13844 SelectionDAG &DAG) const {
13846 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
13847 MVT VT = Op.getSimpleValueType();
13849 if (!Subtarget->hasSSE2() || !VT.isVector())
13852 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
13853 ExtraVT.getScalarType().getSizeInBits();
13855 switch (VT.SimpleTy) {
13856 default: return SDValue();
13859 if (!Subtarget->hasFp256())
13861 if (!Subtarget->hasInt256()) {
13862 // needs to be split
13863 unsigned NumElems = VT.getVectorNumElements();
13865 // Extract the LHS vectors
13866 SDValue LHS = Op.getOperand(0);
13867 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13868 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13870 MVT EltVT = VT.getVectorElementType();
13871 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13873 EVT ExtraEltVT = ExtraVT.getVectorElementType();
13874 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
13875 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
13877 SDValue Extra = DAG.getValueType(ExtraVT);
13879 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
13880 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
13882 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
13887 SDValue Op0 = Op.getOperand(0);
13888 SDValue Op00 = Op0.getOperand(0);
13890 // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
13891 if (Op0.getOpcode() == ISD::BITCAST &&
13892 Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
13893 // (sext (vzext x)) -> (vsext x)
13894 Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
13895 if (Tmp1.getNode()) {
13896 EVT ExtraEltVT = ExtraVT.getVectorElementType();
13897 // This folding is only valid when the in-reg type is a vector of i8,
13899 if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
13900 ExtraEltVT == MVT::i32) {
13901 SDValue Tmp1Op0 = Tmp1.getOperand(0);
13902 assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
13903 "This optimization is invalid without a VZEXT.");
13904 return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
13910 // If the above didn't work, then just use Shift-Left + Shift-Right.
13911 Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
13913 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
13919 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
13920 SelectionDAG &DAG) {
13922 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
13923 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
13924 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
13925 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
13927 // The only fence that needs an instruction is a sequentially-consistent
13928 // cross-thread fence.
13929 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
13930 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
13931 // no-sse2). There isn't any reason to disable it if the target processor
13933 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
13934 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
13936 SDValue Chain = Op.getOperand(0);
13937 SDValue Zero = DAG.getConstant(0, MVT::i32);
13939 DAG.getRegister(X86::ESP, MVT::i32), // Base
13940 DAG.getTargetConstant(1, MVT::i8), // Scale
13941 DAG.getRegister(0, MVT::i32), // Index
13942 DAG.getTargetConstant(0, MVT::i32), // Disp
13943 DAG.getRegister(0, MVT::i32), // Segment.
13947 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
13948 return SDValue(Res, 0);
13951 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
13952 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
13955 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
13956 SelectionDAG &DAG) {
13957 MVT T = Op.getSimpleValueType();
13961 switch(T.SimpleTy) {
13962 default: llvm_unreachable("Invalid value type!");
13963 case MVT::i8: Reg = X86::AL; size = 1; break;
13964 case MVT::i16: Reg = X86::AX; size = 2; break;
13965 case MVT::i32: Reg = X86::EAX; size = 4; break;
13967 assert(Subtarget->is64Bit() && "Node not type legal!");
13968 Reg = X86::RAX; size = 8;
13971 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
13972 Op.getOperand(2), SDValue());
13973 SDValue Ops[] = { cpIn.getValue(0),
13976 DAG.getTargetConstant(size, MVT::i8),
13977 cpIn.getValue(1) };
13978 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13979 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
13980 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
13981 Ops, array_lengthof(Ops), T, MMO);
13983 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
13987 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
13988 SelectionDAG &DAG) {
13989 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
13990 MVT DstVT = Op.getSimpleValueType();
13991 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
13992 Subtarget->hasMMX() && "Unexpected custom BITCAST");
13993 assert((DstVT == MVT::i64 ||
13994 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
13995 "Unexpected custom BITCAST");
13996 // i64 <=> MMX conversions are Legal.
13997 if (SrcVT==MVT::i64 && DstVT.isVector())
13999 if (DstVT==MVT::i64 && SrcVT.isVector())
14001 // MMX <=> MMX conversions are Legal.
14002 if (SrcVT.isVector() && DstVT.isVector())
14004 // All other conversions need to be expanded.
14008 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
14009 SDNode *Node = Op.getNode();
14011 EVT T = Node->getValueType(0);
14012 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
14013 DAG.getConstant(0, T), Node->getOperand(2));
14014 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
14015 cast<AtomicSDNode>(Node)->getMemoryVT(),
14016 Node->getOperand(0),
14017 Node->getOperand(1), negOp,
14018 cast<AtomicSDNode>(Node)->getMemOperand(),
14019 cast<AtomicSDNode>(Node)->getOrdering(),
14020 cast<AtomicSDNode>(Node)->getSynchScope());
14023 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
14024 SDNode *Node = Op.getNode();
14026 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14028 // Convert seq_cst store -> xchg
14029 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
14030 // FIXME: On 32-bit, store -> fist or movq would be more efficient
14031 // (The only way to get a 16-byte store is cmpxchg16b)
14032 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
14033 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
14034 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14035 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
14036 cast<AtomicSDNode>(Node)->getMemoryVT(),
14037 Node->getOperand(0),
14038 Node->getOperand(1), Node->getOperand(2),
14039 cast<AtomicSDNode>(Node)->getMemOperand(),
14040 cast<AtomicSDNode>(Node)->getOrdering(),
14041 cast<AtomicSDNode>(Node)->getSynchScope());
14042 return Swap.getValue(1);
14044 // Other atomic stores have a simple pattern.
14048 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
14049 EVT VT = Op.getNode()->getSimpleValueType(0);
14051 // Let legalize expand this if it isn't a legal type yet.
14052 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14055 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14058 bool ExtraOp = false;
14059 switch (Op.getOpcode()) {
14060 default: llvm_unreachable("Invalid code");
14061 case ISD::ADDC: Opc = X86ISD::ADD; break;
14062 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
14063 case ISD::SUBC: Opc = X86ISD::SUB; break;
14064 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
14068 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14070 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14071 Op.getOperand(1), Op.getOperand(2));
14074 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
14075 SelectionDAG &DAG) {
14076 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
14078 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
14079 // which returns the values as { float, float } (in XMM0) or
14080 // { double, double } (which is returned in XMM0, XMM1).
14082 SDValue Arg = Op.getOperand(0);
14083 EVT ArgVT = Arg.getValueType();
14084 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14086 TargetLowering::ArgListTy Args;
14087 TargetLowering::ArgListEntry Entry;
14091 Entry.isSExt = false;
14092 Entry.isZExt = false;
14093 Args.push_back(Entry);
14095 bool isF64 = ArgVT == MVT::f64;
14096 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
14097 // the small struct {f32, f32} is returned in (eax, edx). For f64,
14098 // the results are returned via SRet in memory.
14099 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
14100 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14101 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
14103 Type *RetTy = isF64
14104 ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
14105 : (Type*)VectorType::get(ArgTy, 4);
14107 CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
14108 false, false, false, false, 0,
14109 CallingConv::C, /*isTaillCall=*/false,
14110 /*doesNotRet=*/false, /*isReturnValueUsed*/true,
14111 Callee, Args, DAG, dl);
14112 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
14115 // Returned in xmm0 and xmm1.
14116 return CallResult.first;
14118 // Returned in bits 0:31 and 32:64 xmm0.
14119 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14120 CallResult.first, DAG.getIntPtrConstant(0));
14121 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14122 CallResult.first, DAG.getIntPtrConstant(1));
14123 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
14124 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
14127 /// LowerOperation - Provide custom lowering hooks for some operations.
14129 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
14130 switch (Op.getOpcode()) {
14131 default: llvm_unreachable("Should not custom lower this!");
14132 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
14133 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
14134 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op, Subtarget, DAG);
14135 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
14136 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
14137 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
14138 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
14139 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
14140 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
14141 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
14142 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
14143 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
14144 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
14145 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
14146 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
14147 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
14148 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
14149 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
14150 case ISD::SHL_PARTS:
14151 case ISD::SRA_PARTS:
14152 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
14153 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
14154 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
14155 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
14156 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
14157 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
14158 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
14159 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
14160 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
14161 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
14162 case ISD::FABS: return LowerFABS(Op, DAG);
14163 case ISD::FNEG: return LowerFNEG(Op, DAG);
14164 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
14165 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
14166 case ISD::SETCC: return LowerSETCC(Op, DAG);
14167 case ISD::SELECT: return LowerSELECT(Op, DAG);
14168 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
14169 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
14170 case ISD::VASTART: return LowerVASTART(Op, DAG);
14171 case ISD::VAARG: return LowerVAARG(Op, DAG);
14172 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
14173 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
14174 case ISD::INTRINSIC_VOID:
14175 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
14176 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
14177 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
14178 case ISD::FRAME_TO_ARGS_OFFSET:
14179 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
14180 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
14181 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
14182 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
14183 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
14184 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
14185 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
14186 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
14187 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
14188 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
14189 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
14190 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
14191 case ISD::UMUL_LOHI: return LowerUMUL_LOHI(Op, Subtarget, DAG);
14194 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
14200 case ISD::UMULO: return LowerXALUO(Op, DAG);
14201 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
14202 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
14206 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
14207 case ISD::ADD: return LowerADD(Op, DAG);
14208 case ISD::SUB: return LowerSUB(Op, DAG);
14209 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
14213 static void ReplaceATOMIC_LOAD(SDNode *Node,
14214 SmallVectorImpl<SDValue> &Results,
14215 SelectionDAG &DAG) {
14217 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14219 // Convert wide load -> cmpxchg8b/cmpxchg16b
14220 // FIXME: On 32-bit, load -> fild or movq would be more efficient
14221 // (The only way to get a 16-byte load is cmpxchg16b)
14222 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
14223 SDValue Zero = DAG.getConstant(0, VT);
14224 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
14225 Node->getOperand(0),
14226 Node->getOperand(1), Zero, Zero,
14227 cast<AtomicSDNode>(Node)->getMemOperand(),
14228 cast<AtomicSDNode>(Node)->getOrdering(),
14229 cast<AtomicSDNode>(Node)->getOrdering(),
14230 cast<AtomicSDNode>(Node)->getSynchScope());
14231 Results.push_back(Swap.getValue(0));
14232 Results.push_back(Swap.getValue(1));
14236 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
14237 SelectionDAG &DAG, unsigned NewOp) {
14239 assert (Node->getValueType(0) == MVT::i64 &&
14240 "Only know how to expand i64 atomics");
14242 SDValue Chain = Node->getOperand(0);
14243 SDValue In1 = Node->getOperand(1);
14244 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14245 Node->getOperand(2), DAG.getIntPtrConstant(0));
14246 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14247 Node->getOperand(2), DAG.getIntPtrConstant(1));
14248 SDValue Ops[] = { Chain, In1, In2L, In2H };
14249 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
14251 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, array_lengthof(Ops), MVT::i64,
14252 cast<MemSDNode>(Node)->getMemOperand());
14253 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
14254 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
14255 Results.push_back(Result.getValue(2));
14258 /// ReplaceNodeResults - Replace a node with an illegal result type
14259 /// with a new node built out of custom code.
14260 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
14261 SmallVectorImpl<SDValue>&Results,
14262 SelectionDAG &DAG) const {
14264 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14265 switch (N->getOpcode()) {
14267 llvm_unreachable("Do not know how to custom type legalize this operation!");
14268 case ISD::SIGN_EXTEND_INREG:
14273 // We don't want to expand or promote these.
14275 case ISD::FP_TO_SINT:
14276 case ISD::FP_TO_UINT: {
14277 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
14279 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
14282 std::pair<SDValue,SDValue> Vals =
14283 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
14284 SDValue FIST = Vals.first, StackSlot = Vals.second;
14285 if (FIST.getNode()) {
14286 EVT VT = N->getValueType(0);
14287 // Return a load from the stack slot.
14288 if (StackSlot.getNode())
14289 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
14290 MachinePointerInfo(),
14291 false, false, false, 0));
14293 Results.push_back(FIST);
14297 case ISD::UINT_TO_FP: {
14298 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14299 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
14300 N->getValueType(0) != MVT::v2f32)
14302 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
14304 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
14306 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
14307 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
14308 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
14309 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
14310 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
14311 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
14314 case ISD::FP_ROUND: {
14315 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
14317 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
14318 Results.push_back(V);
14321 case ISD::INTRINSIC_W_CHAIN: {
14322 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
14324 default : llvm_unreachable("Do not know how to custom type "
14325 "legalize this intrinsic operation!");
14326 case Intrinsic::x86_rdtsc:
14327 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14329 case Intrinsic::x86_rdtscp:
14330 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
14334 case ISD::READCYCLECOUNTER: {
14335 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14338 case ISD::ATOMIC_CMP_SWAP: {
14339 EVT T = N->getValueType(0);
14340 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
14341 bool Regs64bit = T == MVT::i128;
14342 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
14343 SDValue cpInL, cpInH;
14344 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14345 DAG.getConstant(0, HalfT));
14346 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14347 DAG.getConstant(1, HalfT));
14348 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
14349 Regs64bit ? X86::RAX : X86::EAX,
14351 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
14352 Regs64bit ? X86::RDX : X86::EDX,
14353 cpInH, cpInL.getValue(1));
14354 SDValue swapInL, swapInH;
14355 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14356 DAG.getConstant(0, HalfT));
14357 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14358 DAG.getConstant(1, HalfT));
14359 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
14360 Regs64bit ? X86::RBX : X86::EBX,
14361 swapInL, cpInH.getValue(1));
14362 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
14363 Regs64bit ? X86::RCX : X86::ECX,
14364 swapInH, swapInL.getValue(1));
14365 SDValue Ops[] = { swapInH.getValue(0),
14367 swapInH.getValue(1) };
14368 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14369 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
14370 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
14371 X86ISD::LCMPXCHG8_DAG;
14372 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
14373 Ops, array_lengthof(Ops), T, MMO);
14374 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
14375 Regs64bit ? X86::RAX : X86::EAX,
14376 HalfT, Result.getValue(1));
14377 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
14378 Regs64bit ? X86::RDX : X86::EDX,
14379 HalfT, cpOutL.getValue(2));
14380 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
14381 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
14382 Results.push_back(cpOutH.getValue(1));
14385 case ISD::ATOMIC_LOAD_ADD:
14386 case ISD::ATOMIC_LOAD_AND:
14387 case ISD::ATOMIC_LOAD_NAND:
14388 case ISD::ATOMIC_LOAD_OR:
14389 case ISD::ATOMIC_LOAD_SUB:
14390 case ISD::ATOMIC_LOAD_XOR:
14391 case ISD::ATOMIC_LOAD_MAX:
14392 case ISD::ATOMIC_LOAD_MIN:
14393 case ISD::ATOMIC_LOAD_UMAX:
14394 case ISD::ATOMIC_LOAD_UMIN:
14395 case ISD::ATOMIC_SWAP: {
14397 switch (N->getOpcode()) {
14398 default: llvm_unreachable("Unexpected opcode");
14399 case ISD::ATOMIC_LOAD_ADD:
14400 Opc = X86ISD::ATOMADD64_DAG;
14402 case ISD::ATOMIC_LOAD_AND:
14403 Opc = X86ISD::ATOMAND64_DAG;
14405 case ISD::ATOMIC_LOAD_NAND:
14406 Opc = X86ISD::ATOMNAND64_DAG;
14408 case ISD::ATOMIC_LOAD_OR:
14409 Opc = X86ISD::ATOMOR64_DAG;
14411 case ISD::ATOMIC_LOAD_SUB:
14412 Opc = X86ISD::ATOMSUB64_DAG;
14414 case ISD::ATOMIC_LOAD_XOR:
14415 Opc = X86ISD::ATOMXOR64_DAG;
14417 case ISD::ATOMIC_LOAD_MAX:
14418 Opc = X86ISD::ATOMMAX64_DAG;
14420 case ISD::ATOMIC_LOAD_MIN:
14421 Opc = X86ISD::ATOMMIN64_DAG;
14423 case ISD::ATOMIC_LOAD_UMAX:
14424 Opc = X86ISD::ATOMUMAX64_DAG;
14426 case ISD::ATOMIC_LOAD_UMIN:
14427 Opc = X86ISD::ATOMUMIN64_DAG;
14429 case ISD::ATOMIC_SWAP:
14430 Opc = X86ISD::ATOMSWAP64_DAG;
14433 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
14436 case ISD::ATOMIC_LOAD:
14437 ReplaceATOMIC_LOAD(N, Results, DAG);
14441 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
14443 default: return nullptr;
14444 case X86ISD::BSF: return "X86ISD::BSF";
14445 case X86ISD::BSR: return "X86ISD::BSR";
14446 case X86ISD::SHLD: return "X86ISD::SHLD";
14447 case X86ISD::SHRD: return "X86ISD::SHRD";
14448 case X86ISD::FAND: return "X86ISD::FAND";
14449 case X86ISD::FANDN: return "X86ISD::FANDN";
14450 case X86ISD::FOR: return "X86ISD::FOR";
14451 case X86ISD::FXOR: return "X86ISD::FXOR";
14452 case X86ISD::FSRL: return "X86ISD::FSRL";
14453 case X86ISD::FILD: return "X86ISD::FILD";
14454 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
14455 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
14456 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
14457 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
14458 case X86ISD::FLD: return "X86ISD::FLD";
14459 case X86ISD::FST: return "X86ISD::FST";
14460 case X86ISD::CALL: return "X86ISD::CALL";
14461 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
14462 case X86ISD::BT: return "X86ISD::BT";
14463 case X86ISD::CMP: return "X86ISD::CMP";
14464 case X86ISD::COMI: return "X86ISD::COMI";
14465 case X86ISD::UCOMI: return "X86ISD::UCOMI";
14466 case X86ISD::CMPM: return "X86ISD::CMPM";
14467 case X86ISD::CMPMU: return "X86ISD::CMPMU";
14468 case X86ISD::SETCC: return "X86ISD::SETCC";
14469 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
14470 case X86ISD::FSETCC: return "X86ISD::FSETCC";
14471 case X86ISD::CMOV: return "X86ISD::CMOV";
14472 case X86ISD::BRCOND: return "X86ISD::BRCOND";
14473 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
14474 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
14475 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
14476 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
14477 case X86ISD::Wrapper: return "X86ISD::Wrapper";
14478 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
14479 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
14480 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
14481 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
14482 case X86ISD::PINSRB: return "X86ISD::PINSRB";
14483 case X86ISD::PINSRW: return "X86ISD::PINSRW";
14484 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
14485 case X86ISD::ANDNP: return "X86ISD::ANDNP";
14486 case X86ISD::PSIGN: return "X86ISD::PSIGN";
14487 case X86ISD::BLENDV: return "X86ISD::BLENDV";
14488 case X86ISD::BLENDI: return "X86ISD::BLENDI";
14489 case X86ISD::SUBUS: return "X86ISD::SUBUS";
14490 case X86ISD::HADD: return "X86ISD::HADD";
14491 case X86ISD::HSUB: return "X86ISD::HSUB";
14492 case X86ISD::FHADD: return "X86ISD::FHADD";
14493 case X86ISD::FHSUB: return "X86ISD::FHSUB";
14494 case X86ISD::UMAX: return "X86ISD::UMAX";
14495 case X86ISD::UMIN: return "X86ISD::UMIN";
14496 case X86ISD::SMAX: return "X86ISD::SMAX";
14497 case X86ISD::SMIN: return "X86ISD::SMIN";
14498 case X86ISD::FMAX: return "X86ISD::FMAX";
14499 case X86ISD::FMIN: return "X86ISD::FMIN";
14500 case X86ISD::FMAXC: return "X86ISD::FMAXC";
14501 case X86ISD::FMINC: return "X86ISD::FMINC";
14502 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
14503 case X86ISD::FRCP: return "X86ISD::FRCP";
14504 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
14505 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
14506 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
14507 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
14508 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
14509 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
14510 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
14511 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
14512 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
14513 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
14514 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
14515 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
14516 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
14517 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
14518 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
14519 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
14520 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
14521 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
14522 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
14523 case X86ISD::VZEXT: return "X86ISD::VZEXT";
14524 case X86ISD::VSEXT: return "X86ISD::VSEXT";
14525 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
14526 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
14527 case X86ISD::VINSERT: return "X86ISD::VINSERT";
14528 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
14529 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
14530 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
14531 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
14532 case X86ISD::VSHL: return "X86ISD::VSHL";
14533 case X86ISD::VSRL: return "X86ISD::VSRL";
14534 case X86ISD::VSRA: return "X86ISD::VSRA";
14535 case X86ISD::VSHLI: return "X86ISD::VSHLI";
14536 case X86ISD::VSRLI: return "X86ISD::VSRLI";
14537 case X86ISD::VSRAI: return "X86ISD::VSRAI";
14538 case X86ISD::CMPP: return "X86ISD::CMPP";
14539 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
14540 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
14541 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
14542 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
14543 case X86ISD::ADD: return "X86ISD::ADD";
14544 case X86ISD::SUB: return "X86ISD::SUB";
14545 case X86ISD::ADC: return "X86ISD::ADC";
14546 case X86ISD::SBB: return "X86ISD::SBB";
14547 case X86ISD::SMUL: return "X86ISD::SMUL";
14548 case X86ISD::UMUL: return "X86ISD::UMUL";
14549 case X86ISD::INC: return "X86ISD::INC";
14550 case X86ISD::DEC: return "X86ISD::DEC";
14551 case X86ISD::OR: return "X86ISD::OR";
14552 case X86ISD::XOR: return "X86ISD::XOR";
14553 case X86ISD::AND: return "X86ISD::AND";
14554 case X86ISD::BEXTR: return "X86ISD::BEXTR";
14555 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
14556 case X86ISD::PTEST: return "X86ISD::PTEST";
14557 case X86ISD::TESTP: return "X86ISD::TESTP";
14558 case X86ISD::TESTM: return "X86ISD::TESTM";
14559 case X86ISD::TESTNM: return "X86ISD::TESTNM";
14560 case X86ISD::KORTEST: return "X86ISD::KORTEST";
14561 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
14562 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
14563 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
14564 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
14565 case X86ISD::SHUFP: return "X86ISD::SHUFP";
14566 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
14567 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
14568 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
14569 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
14570 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
14571 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
14572 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
14573 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
14574 case X86ISD::MOVSD: return "X86ISD::MOVSD";
14575 case X86ISD::MOVSS: return "X86ISD::MOVSS";
14576 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
14577 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
14578 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
14579 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
14580 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
14581 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
14582 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
14583 case X86ISD::VPERMV: return "X86ISD::VPERMV";
14584 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
14585 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
14586 case X86ISD::VPERMI: return "X86ISD::VPERMI";
14587 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
14588 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
14589 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
14590 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
14591 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
14592 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
14593 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
14594 case X86ISD::SAHF: return "X86ISD::SAHF";
14595 case X86ISD::RDRAND: return "X86ISD::RDRAND";
14596 case X86ISD::RDSEED: return "X86ISD::RDSEED";
14597 case X86ISD::FMADD: return "X86ISD::FMADD";
14598 case X86ISD::FMSUB: return "X86ISD::FMSUB";
14599 case X86ISD::FNMADD: return "X86ISD::FNMADD";
14600 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
14601 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
14602 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
14603 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
14604 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
14605 case X86ISD::XTEST: return "X86ISD::XTEST";
14609 // isLegalAddressingMode - Return true if the addressing mode represented
14610 // by AM is legal for this target, for a load/store of the specified type.
14611 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
14613 // X86 supports extremely general addressing modes.
14614 CodeModel::Model M = getTargetMachine().getCodeModel();
14615 Reloc::Model R = getTargetMachine().getRelocationModel();
14617 // X86 allows a sign-extended 32-bit immediate field as a displacement.
14618 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
14623 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
14625 // If a reference to this global requires an extra load, we can't fold it.
14626 if (isGlobalStubReference(GVFlags))
14629 // If BaseGV requires a register for the PIC base, we cannot also have a
14630 // BaseReg specified.
14631 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
14634 // If lower 4G is not available, then we must use rip-relative addressing.
14635 if ((M != CodeModel::Small || R != Reloc::Static) &&
14636 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
14640 switch (AM.Scale) {
14646 // These scales always work.
14651 // These scales are formed with basereg+scalereg. Only accept if there is
14656 default: // Other stuff never works.
14663 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
14664 unsigned Bits = Ty->getScalarSizeInBits();
14666 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
14667 // particularly cheaper than those without.
14671 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
14672 // variable shifts just as cheap as scalar ones.
14673 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
14676 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
14677 // fully general vector.
14681 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
14682 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14684 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
14685 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
14686 return NumBits1 > NumBits2;
14689 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
14690 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14693 if (!isTypeLegal(EVT::getEVT(Ty1)))
14696 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
14698 // Assuming the caller doesn't have a zeroext or signext return parameter,
14699 // truncation all the way down to i1 is valid.
14703 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
14704 return isInt<32>(Imm);
14707 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
14708 // Can also use sub to handle negated immediates.
14709 return isInt<32>(Imm);
14712 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
14713 if (!VT1.isInteger() || !VT2.isInteger())
14715 unsigned NumBits1 = VT1.getSizeInBits();
14716 unsigned NumBits2 = VT2.getSizeInBits();
14717 return NumBits1 > NumBits2;
14720 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
14721 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14722 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
14725 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
14726 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14727 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
14730 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14731 EVT VT1 = Val.getValueType();
14732 if (isZExtFree(VT1, VT2))
14735 if (Val.getOpcode() != ISD::LOAD)
14738 if (!VT1.isSimple() || !VT1.isInteger() ||
14739 !VT2.isSimple() || !VT2.isInteger())
14742 switch (VT1.getSimpleVT().SimpleTy) {
14747 // X86 has 8, 16, and 32-bit zero-extending loads.
14755 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
14756 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
14759 VT = VT.getScalarType();
14761 if (!VT.isSimple())
14764 switch (VT.getSimpleVT().SimpleTy) {
14775 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
14776 // i16 instructions are longer (0x66 prefix) and potentially slower.
14777 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
14780 /// isShuffleMaskLegal - Targets can use this to indicate that they only
14781 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
14782 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
14783 /// are assumed to be legal.
14785 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
14787 if (!VT.isSimple())
14790 MVT SVT = VT.getSimpleVT();
14792 // Very little shuffling can be done for 64-bit vectors right now.
14793 if (VT.getSizeInBits() == 64)
14796 // FIXME: pshufb, blends, shifts.
14797 return (SVT.getVectorNumElements() == 2 ||
14798 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
14799 isMOVLMask(M, SVT) ||
14800 isSHUFPMask(M, SVT) ||
14801 isPSHUFDMask(M, SVT) ||
14802 isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
14803 isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
14804 isPALIGNRMask(M, SVT, Subtarget) ||
14805 isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
14806 isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
14807 isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
14808 isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()));
14812 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
14814 if (!VT.isSimple())
14817 MVT SVT = VT.getSimpleVT();
14818 unsigned NumElts = SVT.getVectorNumElements();
14819 // FIXME: This collection of masks seems suspect.
14822 if (NumElts == 4 && SVT.is128BitVector()) {
14823 return (isMOVLMask(Mask, SVT) ||
14824 isCommutedMOVLMask(Mask, SVT, true) ||
14825 isSHUFPMask(Mask, SVT) ||
14826 isSHUFPMask(Mask, SVT, /* Commuted */ true));
14831 //===----------------------------------------------------------------------===//
14832 // X86 Scheduler Hooks
14833 //===----------------------------------------------------------------------===//
14835 /// Utility function to emit xbegin specifying the start of an RTM region.
14836 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
14837 const TargetInstrInfo *TII) {
14838 DebugLoc DL = MI->getDebugLoc();
14840 const BasicBlock *BB = MBB->getBasicBlock();
14841 MachineFunction::iterator I = MBB;
14844 // For the v = xbegin(), we generate
14855 MachineBasicBlock *thisMBB = MBB;
14856 MachineFunction *MF = MBB->getParent();
14857 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14858 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14859 MF->insert(I, mainMBB);
14860 MF->insert(I, sinkMBB);
14862 // Transfer the remainder of BB and its successor edges to sinkMBB.
14863 sinkMBB->splice(sinkMBB->begin(), MBB,
14864 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
14865 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14869 // # fallthrough to mainMBB
14870 // # abortion to sinkMBB
14871 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
14872 thisMBB->addSuccessor(mainMBB);
14873 thisMBB->addSuccessor(sinkMBB);
14877 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
14878 mainMBB->addSuccessor(sinkMBB);
14881 // EAX is live into the sinkMBB
14882 sinkMBB->addLiveIn(X86::EAX);
14883 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14884 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14887 MI->eraseFromParent();
14891 // Get CMPXCHG opcode for the specified data type.
14892 static unsigned getCmpXChgOpcode(EVT VT) {
14893 switch (VT.getSimpleVT().SimpleTy) {
14894 case MVT::i8: return X86::LCMPXCHG8;
14895 case MVT::i16: return X86::LCMPXCHG16;
14896 case MVT::i32: return X86::LCMPXCHG32;
14897 case MVT::i64: return X86::LCMPXCHG64;
14901 llvm_unreachable("Invalid operand size!");
14904 // Get LOAD opcode for the specified data type.
14905 static unsigned getLoadOpcode(EVT VT) {
14906 switch (VT.getSimpleVT().SimpleTy) {
14907 case MVT::i8: return X86::MOV8rm;
14908 case MVT::i16: return X86::MOV16rm;
14909 case MVT::i32: return X86::MOV32rm;
14910 case MVT::i64: return X86::MOV64rm;
14914 llvm_unreachable("Invalid operand size!");
14917 // Get opcode of the non-atomic one from the specified atomic instruction.
14918 static unsigned getNonAtomicOpcode(unsigned Opc) {
14920 case X86::ATOMAND8: return X86::AND8rr;
14921 case X86::ATOMAND16: return X86::AND16rr;
14922 case X86::ATOMAND32: return X86::AND32rr;
14923 case X86::ATOMAND64: return X86::AND64rr;
14924 case X86::ATOMOR8: return X86::OR8rr;
14925 case X86::ATOMOR16: return X86::OR16rr;
14926 case X86::ATOMOR32: return X86::OR32rr;
14927 case X86::ATOMOR64: return X86::OR64rr;
14928 case X86::ATOMXOR8: return X86::XOR8rr;
14929 case X86::ATOMXOR16: return X86::XOR16rr;
14930 case X86::ATOMXOR32: return X86::XOR32rr;
14931 case X86::ATOMXOR64: return X86::XOR64rr;
14933 llvm_unreachable("Unhandled atomic-load-op opcode!");
14936 // Get opcode of the non-atomic one from the specified atomic instruction with
14938 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
14939 unsigned &ExtraOpc) {
14941 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr;
14942 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr;
14943 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr;
14944 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr;
14945 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr;
14946 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
14947 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
14948 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
14949 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr;
14950 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
14951 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
14952 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
14953 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr;
14954 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
14955 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
14956 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
14957 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr;
14958 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
14959 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
14960 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
14962 llvm_unreachable("Unhandled atomic-load-op opcode!");
14965 // Get opcode of the non-atomic one from the specified atomic instruction for
14966 // 64-bit data type on 32-bit target.
14967 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
14969 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr;
14970 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr;
14971 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr;
14972 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr;
14973 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr;
14974 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
14975 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr;
14976 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr;
14977 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr;
14978 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr;
14980 llvm_unreachable("Unhandled atomic-load-op opcode!");
14983 // Get opcode of the non-atomic one from the specified atomic instruction for
14984 // 64-bit data type on 32-bit target with extra opcode.
14985 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
14987 unsigned &ExtraOpc) {
14989 case X86::ATOMNAND6432:
14990 ExtraOpc = X86::NOT32r;
14991 HiOpc = X86::AND32rr;
14992 return X86::AND32rr;
14994 llvm_unreachable("Unhandled atomic-load-op opcode!");
14997 // Get pseudo CMOV opcode from the specified data type.
14998 static unsigned getPseudoCMOVOpc(EVT VT) {
14999 switch (VT.getSimpleVT().SimpleTy) {
15000 case MVT::i8: return X86::CMOV_GR8;
15001 case MVT::i16: return X86::CMOV_GR16;
15002 case MVT::i32: return X86::CMOV_GR32;
15006 llvm_unreachable("Unknown CMOV opcode!");
15009 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
15010 // They will be translated into a spin-loop or compare-exchange loop from
15013 // dst = atomic-fetch-op MI.addr, MI.val
15019 // t1 = LOAD MI.addr
15021 // t4 = phi(t1, t3 / loop)
15022 // t2 = OP MI.val, t4
15024 // LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
15030 MachineBasicBlock *
15031 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
15032 MachineBasicBlock *MBB) const {
15033 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15034 DebugLoc DL = MI->getDebugLoc();
15036 MachineFunction *MF = MBB->getParent();
15037 MachineRegisterInfo &MRI = MF->getRegInfo();
15039 const BasicBlock *BB = MBB->getBasicBlock();
15040 MachineFunction::iterator I = MBB;
15043 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
15044 "Unexpected number of operands");
15046 assert(MI->hasOneMemOperand() &&
15047 "Expected atomic-load-op to have one memoperand");
15049 // Memory Reference
15050 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15051 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15053 unsigned DstReg, SrcReg;
15054 unsigned MemOpndSlot;
15056 unsigned CurOp = 0;
15058 DstReg = MI->getOperand(CurOp++).getReg();
15059 MemOpndSlot = CurOp;
15060 CurOp += X86::AddrNumOperands;
15061 SrcReg = MI->getOperand(CurOp++).getReg();
15063 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15064 MVT::SimpleValueType VT = *RC->vt_begin();
15065 unsigned t1 = MRI.createVirtualRegister(RC);
15066 unsigned t2 = MRI.createVirtualRegister(RC);
15067 unsigned t3 = MRI.createVirtualRegister(RC);
15068 unsigned t4 = MRI.createVirtualRegister(RC);
15069 unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
15071 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
15072 unsigned LOADOpc = getLoadOpcode(VT);
15074 // For the atomic load-arith operator, we generate
15077 // t1 = LOAD [MI.addr]
15079 // t4 = phi(t1 / thisMBB, t3 / mainMBB)
15080 // t1 = OP MI.val, EAX
15082 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
15088 MachineBasicBlock *thisMBB = MBB;
15089 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15090 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15091 MF->insert(I, mainMBB);
15092 MF->insert(I, sinkMBB);
15094 MachineInstrBuilder MIB;
15096 // Transfer the remainder of BB and its successor edges to sinkMBB.
15097 sinkMBB->splice(sinkMBB->begin(), MBB,
15098 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15099 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15102 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
15103 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15104 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15106 NewMO.setIsKill(false);
15107 MIB.addOperand(NewMO);
15109 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15110 unsigned flags = (*MMOI)->getFlags();
15111 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15112 MachineMemOperand *MMO =
15113 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15114 (*MMOI)->getSize(),
15115 (*MMOI)->getBaseAlignment(),
15116 (*MMOI)->getTBAAInfo(),
15117 (*MMOI)->getRanges());
15118 MIB.addMemOperand(MMO);
15121 thisMBB->addSuccessor(mainMBB);
15124 MachineBasicBlock *origMainMBB = mainMBB;
15127 MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
15128 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15130 unsigned Opc = MI->getOpcode();
15133 llvm_unreachable("Unhandled atomic-load-op opcode!");
15134 case X86::ATOMAND8:
15135 case X86::ATOMAND16:
15136 case X86::ATOMAND32:
15137 case X86::ATOMAND64:
15139 case X86::ATOMOR16:
15140 case X86::ATOMOR32:
15141 case X86::ATOMOR64:
15142 case X86::ATOMXOR8:
15143 case X86::ATOMXOR16:
15144 case X86::ATOMXOR32:
15145 case X86::ATOMXOR64: {
15146 unsigned ARITHOpc = getNonAtomicOpcode(Opc);
15147 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
15151 case X86::ATOMNAND8:
15152 case X86::ATOMNAND16:
15153 case X86::ATOMNAND32:
15154 case X86::ATOMNAND64: {
15155 unsigned Tmp = MRI.createVirtualRegister(RC);
15157 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
15158 BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
15160 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
15163 case X86::ATOMMAX8:
15164 case X86::ATOMMAX16:
15165 case X86::ATOMMAX32:
15166 case X86::ATOMMAX64:
15167 case X86::ATOMMIN8:
15168 case X86::ATOMMIN16:
15169 case X86::ATOMMIN32:
15170 case X86::ATOMMIN64:
15171 case X86::ATOMUMAX8:
15172 case X86::ATOMUMAX16:
15173 case X86::ATOMUMAX32:
15174 case X86::ATOMUMAX64:
15175 case X86::ATOMUMIN8:
15176 case X86::ATOMUMIN16:
15177 case X86::ATOMUMIN32:
15178 case X86::ATOMUMIN64: {
15180 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
15182 BuildMI(mainMBB, DL, TII->get(CMPOpc))
15186 if (Subtarget->hasCMov()) {
15187 if (VT != MVT::i8) {
15189 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
15193 // Promote i8 to i32 to use CMOV32
15194 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15195 const TargetRegisterClass *RC32 =
15196 TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
15197 unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
15198 unsigned AccReg32 = MRI.createVirtualRegister(RC32);
15199 unsigned Tmp = MRI.createVirtualRegister(RC32);
15201 unsigned Undef = MRI.createVirtualRegister(RC32);
15202 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
15204 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
15207 .addImm(X86::sub_8bit);
15208 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
15211 .addImm(X86::sub_8bit);
15213 BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
15217 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
15218 .addReg(Tmp, 0, X86::sub_8bit);
15221 // Use pseudo select and lower them.
15222 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
15223 "Invalid atomic-load-op transformation!");
15224 unsigned SelOpc = getPseudoCMOVOpc(VT);
15225 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
15226 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
15227 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
15228 .addReg(SrcReg).addReg(t4)
15230 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15231 // Replace the original PHI node as mainMBB is changed after CMOV
15233 BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
15234 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15235 Phi->eraseFromParent();
15241 // Copy PhyReg back from virtual register.
15242 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
15245 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15246 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15247 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15249 NewMO.setIsKill(false);
15250 MIB.addOperand(NewMO);
15253 MIB.setMemRefs(MMOBegin, MMOEnd);
15255 // Copy PhyReg back to virtual register.
15256 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
15259 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15261 mainMBB->addSuccessor(origMainMBB);
15262 mainMBB->addSuccessor(sinkMBB);
15265 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15266 TII->get(TargetOpcode::COPY), DstReg)
15269 MI->eraseFromParent();
15273 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
15274 // instructions. They will be translated into a spin-loop or compare-exchange
15278 // dst = atomic-fetch-op MI.addr, MI.val
15284 // t1L = LOAD [MI.addr + 0]
15285 // t1H = LOAD [MI.addr + 4]
15287 // t4L = phi(t1L, t3L / loop)
15288 // t4H = phi(t1H, t3H / loop)
15289 // t2L = OP MI.val.lo, t4L
15290 // t2H = OP MI.val.hi, t4H
15295 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15303 MachineBasicBlock *
15304 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
15305 MachineBasicBlock *MBB) const {
15306 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15307 DebugLoc DL = MI->getDebugLoc();
15309 MachineFunction *MF = MBB->getParent();
15310 MachineRegisterInfo &MRI = MF->getRegInfo();
15312 const BasicBlock *BB = MBB->getBasicBlock();
15313 MachineFunction::iterator I = MBB;
15316 assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
15317 "Unexpected number of operands");
15319 assert(MI->hasOneMemOperand() &&
15320 "Expected atomic-load-op32 to have one memoperand");
15322 // Memory Reference
15323 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15324 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15326 unsigned DstLoReg, DstHiReg;
15327 unsigned SrcLoReg, SrcHiReg;
15328 unsigned MemOpndSlot;
15330 unsigned CurOp = 0;
15332 DstLoReg = MI->getOperand(CurOp++).getReg();
15333 DstHiReg = MI->getOperand(CurOp++).getReg();
15334 MemOpndSlot = CurOp;
15335 CurOp += X86::AddrNumOperands;
15336 SrcLoReg = MI->getOperand(CurOp++).getReg();
15337 SrcHiReg = MI->getOperand(CurOp++).getReg();
15339 const TargetRegisterClass *RC = &X86::GR32RegClass;
15340 const TargetRegisterClass *RC8 = &X86::GR8RegClass;
15342 unsigned t1L = MRI.createVirtualRegister(RC);
15343 unsigned t1H = MRI.createVirtualRegister(RC);
15344 unsigned t2L = MRI.createVirtualRegister(RC);
15345 unsigned t2H = MRI.createVirtualRegister(RC);
15346 unsigned t3L = MRI.createVirtualRegister(RC);
15347 unsigned t3H = MRI.createVirtualRegister(RC);
15348 unsigned t4L = MRI.createVirtualRegister(RC);
15349 unsigned t4H = MRI.createVirtualRegister(RC);
15351 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
15352 unsigned LOADOpc = X86::MOV32rm;
15354 // For the atomic load-arith operator, we generate
15357 // t1L = LOAD [MI.addr + 0]
15358 // t1H = LOAD [MI.addr + 4]
15360 // t4L = phi(t1L / thisMBB, t3L / mainMBB)
15361 // t4H = phi(t1H / thisMBB, t3H / mainMBB)
15362 // t2L = OP MI.val.lo, t4L
15363 // t2H = OP MI.val.hi, t4H
15366 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15374 MachineBasicBlock *thisMBB = MBB;
15375 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15376 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15377 MF->insert(I, mainMBB);
15378 MF->insert(I, sinkMBB);
15380 MachineInstrBuilder MIB;
15382 // Transfer the remainder of BB and its successor edges to sinkMBB.
15383 sinkMBB->splice(sinkMBB->begin(), MBB,
15384 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15385 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15389 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
15390 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15391 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15393 NewMO.setIsKill(false);
15394 MIB.addOperand(NewMO);
15396 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15397 unsigned flags = (*MMOI)->getFlags();
15398 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15399 MachineMemOperand *MMO =
15400 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15401 (*MMOI)->getSize(),
15402 (*MMOI)->getBaseAlignment(),
15403 (*MMOI)->getTBAAInfo(),
15404 (*MMOI)->getRanges());
15405 MIB.addMemOperand(MMO);
15407 MachineInstr *LowMI = MIB;
15410 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
15411 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15412 if (i == X86::AddrDisp) {
15413 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
15415 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15417 NewMO.setIsKill(false);
15418 MIB.addOperand(NewMO);
15421 MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
15423 thisMBB->addSuccessor(mainMBB);
15426 MachineBasicBlock *origMainMBB = mainMBB;
15429 MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
15430 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15431 MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
15432 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15434 unsigned Opc = MI->getOpcode();
15437 llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
15438 case X86::ATOMAND6432:
15439 case X86::ATOMOR6432:
15440 case X86::ATOMXOR6432:
15441 case X86::ATOMADD6432:
15442 case X86::ATOMSUB6432: {
15444 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15445 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
15447 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
15451 case X86::ATOMNAND6432: {
15452 unsigned HiOpc, NOTOpc;
15453 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
15454 unsigned TmpL = MRI.createVirtualRegister(RC);
15455 unsigned TmpH = MRI.createVirtualRegister(RC);
15456 BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
15458 BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
15460 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
15461 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
15464 case X86::ATOMMAX6432:
15465 case X86::ATOMMIN6432:
15466 case X86::ATOMUMAX6432:
15467 case X86::ATOMUMIN6432: {
15469 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15470 unsigned cL = MRI.createVirtualRegister(RC8);
15471 unsigned cH = MRI.createVirtualRegister(RC8);
15472 unsigned cL32 = MRI.createVirtualRegister(RC);
15473 unsigned cH32 = MRI.createVirtualRegister(RC);
15474 unsigned cc = MRI.createVirtualRegister(RC);
15475 // cl := cmp src_lo, lo
15476 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15477 .addReg(SrcLoReg).addReg(t4L);
15478 BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
15479 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
15480 // ch := cmp src_hi, hi
15481 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15482 .addReg(SrcHiReg).addReg(t4H);
15483 BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
15484 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
15485 // cc := if (src_hi == hi) ? cl : ch;
15486 if (Subtarget->hasCMov()) {
15487 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
15488 .addReg(cH32).addReg(cL32);
15490 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
15491 .addReg(cH32).addReg(cL32)
15492 .addImm(X86::COND_E);
15493 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15495 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
15496 if (Subtarget->hasCMov()) {
15497 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
15498 .addReg(SrcLoReg).addReg(t4L);
15499 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
15500 .addReg(SrcHiReg).addReg(t4H);
15502 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
15503 .addReg(SrcLoReg).addReg(t4L)
15504 .addImm(X86::COND_NE);
15505 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15506 // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
15507 // 2nd CMOV lowering.
15508 mainMBB->addLiveIn(X86::EFLAGS);
15509 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
15510 .addReg(SrcHiReg).addReg(t4H)
15511 .addImm(X86::COND_NE);
15512 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15513 // Replace the original PHI node as mainMBB is changed after CMOV
15515 BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
15516 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15517 BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
15518 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15519 PhiL->eraseFromParent();
15520 PhiH->eraseFromParent();
15524 case X86::ATOMSWAP6432: {
15526 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15527 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
15528 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
15533 // Copy EDX:EAX back from HiReg:LoReg
15534 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
15535 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
15536 // Copy ECX:EBX from t1H:t1L
15537 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
15538 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
15540 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15541 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15542 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15544 NewMO.setIsKill(false);
15545 MIB.addOperand(NewMO);
15547 MIB.setMemRefs(MMOBegin, MMOEnd);
15549 // Copy EDX:EAX back to t3H:t3L
15550 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
15551 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
15553 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15555 mainMBB->addSuccessor(origMainMBB);
15556 mainMBB->addSuccessor(sinkMBB);
15559 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15560 TII->get(TargetOpcode::COPY), DstLoReg)
15562 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15563 TII->get(TargetOpcode::COPY), DstHiReg)
15566 MI->eraseFromParent();
15570 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
15571 // or XMM0_V32I8 in AVX all of this code can be replaced with that
15572 // in the .td file.
15573 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
15574 const TargetInstrInfo *TII) {
15576 switch (MI->getOpcode()) {
15577 default: llvm_unreachable("illegal opcode!");
15578 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
15579 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
15580 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
15581 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
15582 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
15583 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
15584 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
15585 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
15588 DebugLoc dl = MI->getDebugLoc();
15589 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15591 unsigned NumArgs = MI->getNumOperands();
15592 for (unsigned i = 1; i < NumArgs; ++i) {
15593 MachineOperand &Op = MI->getOperand(i);
15594 if (!(Op.isReg() && Op.isImplicit()))
15595 MIB.addOperand(Op);
15597 if (MI->hasOneMemOperand())
15598 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15600 BuildMI(*BB, MI, dl,
15601 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15602 .addReg(X86::XMM0);
15604 MI->eraseFromParent();
15608 // FIXME: Custom handling because TableGen doesn't support multiple implicit
15609 // defs in an instruction pattern
15610 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
15611 const TargetInstrInfo *TII) {
15613 switch (MI->getOpcode()) {
15614 default: llvm_unreachable("illegal opcode!");
15615 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
15616 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
15617 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
15618 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
15619 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
15620 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
15621 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
15622 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
15625 DebugLoc dl = MI->getDebugLoc();
15626 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15628 unsigned NumArgs = MI->getNumOperands(); // remove the results
15629 for (unsigned i = 1; i < NumArgs; ++i) {
15630 MachineOperand &Op = MI->getOperand(i);
15631 if (!(Op.isReg() && Op.isImplicit()))
15632 MIB.addOperand(Op);
15634 if (MI->hasOneMemOperand())
15635 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15637 BuildMI(*BB, MI, dl,
15638 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15641 MI->eraseFromParent();
15645 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
15646 const TargetInstrInfo *TII,
15647 const X86Subtarget* Subtarget) {
15648 DebugLoc dl = MI->getDebugLoc();
15650 // Address into RAX/EAX, other two args into ECX, EDX.
15651 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
15652 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
15653 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
15654 for (int i = 0; i < X86::AddrNumOperands; ++i)
15655 MIB.addOperand(MI->getOperand(i));
15657 unsigned ValOps = X86::AddrNumOperands;
15658 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
15659 .addReg(MI->getOperand(ValOps).getReg());
15660 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
15661 .addReg(MI->getOperand(ValOps+1).getReg());
15663 // The instruction doesn't actually take any operands though.
15664 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
15666 MI->eraseFromParent(); // The pseudo is gone now.
15670 MachineBasicBlock *
15671 X86TargetLowering::EmitVAARG64WithCustomInserter(
15673 MachineBasicBlock *MBB) const {
15674 // Emit va_arg instruction on X86-64.
15676 // Operands to this pseudo-instruction:
15677 // 0 ) Output : destination address (reg)
15678 // 1-5) Input : va_list address (addr, i64mem)
15679 // 6 ) ArgSize : Size (in bytes) of vararg type
15680 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
15681 // 8 ) Align : Alignment of type
15682 // 9 ) EFLAGS (implicit-def)
15684 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
15685 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
15687 unsigned DestReg = MI->getOperand(0).getReg();
15688 MachineOperand &Base = MI->getOperand(1);
15689 MachineOperand &Scale = MI->getOperand(2);
15690 MachineOperand &Index = MI->getOperand(3);
15691 MachineOperand &Disp = MI->getOperand(4);
15692 MachineOperand &Segment = MI->getOperand(5);
15693 unsigned ArgSize = MI->getOperand(6).getImm();
15694 unsigned ArgMode = MI->getOperand(7).getImm();
15695 unsigned Align = MI->getOperand(8).getImm();
15697 // Memory Reference
15698 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
15699 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15700 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15702 // Machine Information
15703 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15704 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
15705 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
15706 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
15707 DebugLoc DL = MI->getDebugLoc();
15709 // struct va_list {
15712 // i64 overflow_area (address)
15713 // i64 reg_save_area (address)
15715 // sizeof(va_list) = 24
15716 // alignment(va_list) = 8
15718 unsigned TotalNumIntRegs = 6;
15719 unsigned TotalNumXMMRegs = 8;
15720 bool UseGPOffset = (ArgMode == 1);
15721 bool UseFPOffset = (ArgMode == 2);
15722 unsigned MaxOffset = TotalNumIntRegs * 8 +
15723 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
15725 /* Align ArgSize to a multiple of 8 */
15726 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
15727 bool NeedsAlign = (Align > 8);
15729 MachineBasicBlock *thisMBB = MBB;
15730 MachineBasicBlock *overflowMBB;
15731 MachineBasicBlock *offsetMBB;
15732 MachineBasicBlock *endMBB;
15734 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
15735 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
15736 unsigned OffsetReg = 0;
15738 if (!UseGPOffset && !UseFPOffset) {
15739 // If we only pull from the overflow region, we don't create a branch.
15740 // We don't need to alter control flow.
15741 OffsetDestReg = 0; // unused
15742 OverflowDestReg = DestReg;
15744 offsetMBB = nullptr;
15745 overflowMBB = thisMBB;
15748 // First emit code to check if gp_offset (or fp_offset) is below the bound.
15749 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
15750 // If not, pull from overflow_area. (branch to overflowMBB)
15755 // offsetMBB overflowMBB
15760 // Registers for the PHI in endMBB
15761 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
15762 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
15764 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15765 MachineFunction *MF = MBB->getParent();
15766 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15767 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15768 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15770 MachineFunction::iterator MBBIter = MBB;
15773 // Insert the new basic blocks
15774 MF->insert(MBBIter, offsetMBB);
15775 MF->insert(MBBIter, overflowMBB);
15776 MF->insert(MBBIter, endMBB);
15778 // Transfer the remainder of MBB and its successor edges to endMBB.
15779 endMBB->splice(endMBB->begin(), thisMBB,
15780 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
15781 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
15783 // Make offsetMBB and overflowMBB successors of thisMBB
15784 thisMBB->addSuccessor(offsetMBB);
15785 thisMBB->addSuccessor(overflowMBB);
15787 // endMBB is a successor of both offsetMBB and overflowMBB
15788 offsetMBB->addSuccessor(endMBB);
15789 overflowMBB->addSuccessor(endMBB);
15791 // Load the offset value into a register
15792 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15793 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
15797 .addDisp(Disp, UseFPOffset ? 4 : 0)
15798 .addOperand(Segment)
15799 .setMemRefs(MMOBegin, MMOEnd);
15801 // Check if there is enough room left to pull this argument.
15802 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
15804 .addImm(MaxOffset + 8 - ArgSizeA8);
15806 // Branch to "overflowMBB" if offset >= max
15807 // Fall through to "offsetMBB" otherwise
15808 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
15809 .addMBB(overflowMBB);
15812 // In offsetMBB, emit code to use the reg_save_area.
15814 assert(OffsetReg != 0);
15816 // Read the reg_save_area address.
15817 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
15818 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
15823 .addOperand(Segment)
15824 .setMemRefs(MMOBegin, MMOEnd);
15826 // Zero-extend the offset
15827 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
15828 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
15831 .addImm(X86::sub_32bit);
15833 // Add the offset to the reg_save_area to get the final address.
15834 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
15835 .addReg(OffsetReg64)
15836 .addReg(RegSaveReg);
15838 // Compute the offset for the next argument
15839 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15840 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
15842 .addImm(UseFPOffset ? 16 : 8);
15844 // Store it back into the va_list.
15845 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
15849 .addDisp(Disp, UseFPOffset ? 4 : 0)
15850 .addOperand(Segment)
15851 .addReg(NextOffsetReg)
15852 .setMemRefs(MMOBegin, MMOEnd);
15855 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
15860 // Emit code to use overflow area
15863 // Load the overflow_area address into a register.
15864 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
15865 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
15870 .addOperand(Segment)
15871 .setMemRefs(MMOBegin, MMOEnd);
15873 // If we need to align it, do so. Otherwise, just copy the address
15874 // to OverflowDestReg.
15876 // Align the overflow address
15877 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
15878 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
15880 // aligned_addr = (addr + (align-1)) & ~(align-1)
15881 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
15882 .addReg(OverflowAddrReg)
15885 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
15887 .addImm(~(uint64_t)(Align-1));
15889 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
15890 .addReg(OverflowAddrReg);
15893 // Compute the next overflow address after this argument.
15894 // (the overflow address should be kept 8-byte aligned)
15895 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
15896 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
15897 .addReg(OverflowDestReg)
15898 .addImm(ArgSizeA8);
15900 // Store the new overflow address.
15901 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
15906 .addOperand(Segment)
15907 .addReg(NextAddrReg)
15908 .setMemRefs(MMOBegin, MMOEnd);
15910 // If we branched, emit the PHI to the front of endMBB.
15912 BuildMI(*endMBB, endMBB->begin(), DL,
15913 TII->get(X86::PHI), DestReg)
15914 .addReg(OffsetDestReg).addMBB(offsetMBB)
15915 .addReg(OverflowDestReg).addMBB(overflowMBB);
15918 // Erase the pseudo instruction
15919 MI->eraseFromParent();
15924 MachineBasicBlock *
15925 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
15927 MachineBasicBlock *MBB) const {
15928 // Emit code to save XMM registers to the stack. The ABI says that the
15929 // number of registers to save is given in %al, so it's theoretically
15930 // possible to do an indirect jump trick to avoid saving all of them,
15931 // however this code takes a simpler approach and just executes all
15932 // of the stores if %al is non-zero. It's less code, and it's probably
15933 // easier on the hardware branch predictor, and stores aren't all that
15934 // expensive anyway.
15936 // Create the new basic blocks. One block contains all the XMM stores,
15937 // and one block is the final destination regardless of whether any
15938 // stores were performed.
15939 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15940 MachineFunction *F = MBB->getParent();
15941 MachineFunction::iterator MBBIter = MBB;
15943 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
15944 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
15945 F->insert(MBBIter, XMMSaveMBB);
15946 F->insert(MBBIter, EndMBB);
15948 // Transfer the remainder of MBB and its successor edges to EndMBB.
15949 EndMBB->splice(EndMBB->begin(), MBB,
15950 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15951 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
15953 // The original block will now fall through to the XMM save block.
15954 MBB->addSuccessor(XMMSaveMBB);
15955 // The XMMSaveMBB will fall through to the end block.
15956 XMMSaveMBB->addSuccessor(EndMBB);
15958 // Now add the instructions.
15959 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15960 DebugLoc DL = MI->getDebugLoc();
15962 unsigned CountReg = MI->getOperand(0).getReg();
15963 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
15964 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
15966 if (!Subtarget->isTargetWin64()) {
15967 // If %al is 0, branch around the XMM save block.
15968 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
15969 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
15970 MBB->addSuccessor(EndMBB);
15973 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
15974 // that was just emitted, but clearly shouldn't be "saved".
15975 assert((MI->getNumOperands() <= 3 ||
15976 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
15977 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
15978 && "Expected last argument to be EFLAGS");
15979 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
15980 // In the XMM save block, save all the XMM argument registers.
15981 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
15982 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
15983 MachineMemOperand *MMO =
15984 F->getMachineMemOperand(
15985 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
15986 MachineMemOperand::MOStore,
15987 /*Size=*/16, /*Align=*/16);
15988 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
15989 .addFrameIndex(RegSaveFrameIndex)
15990 .addImm(/*Scale=*/1)
15991 .addReg(/*IndexReg=*/0)
15992 .addImm(/*Disp=*/Offset)
15993 .addReg(/*Segment=*/0)
15994 .addReg(MI->getOperand(i).getReg())
15995 .addMemOperand(MMO);
15998 MI->eraseFromParent(); // The pseudo instruction is gone now.
16003 // The EFLAGS operand of SelectItr might be missing a kill marker
16004 // because there were multiple uses of EFLAGS, and ISel didn't know
16005 // which to mark. Figure out whether SelectItr should have had a
16006 // kill marker, and set it if it should. Returns the correct kill
16008 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
16009 MachineBasicBlock* BB,
16010 const TargetRegisterInfo* TRI) {
16011 // Scan forward through BB for a use/def of EFLAGS.
16012 MachineBasicBlock::iterator miI(std::next(SelectItr));
16013 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
16014 const MachineInstr& mi = *miI;
16015 if (mi.readsRegister(X86::EFLAGS))
16017 if (mi.definesRegister(X86::EFLAGS))
16018 break; // Should have kill-flag - update below.
16021 // If we hit the end of the block, check whether EFLAGS is live into a
16023 if (miI == BB->end()) {
16024 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
16025 sEnd = BB->succ_end();
16026 sItr != sEnd; ++sItr) {
16027 MachineBasicBlock* succ = *sItr;
16028 if (succ->isLiveIn(X86::EFLAGS))
16033 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
16034 // out. SelectMI should have a kill flag on EFLAGS.
16035 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
16039 MachineBasicBlock *
16040 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
16041 MachineBasicBlock *BB) const {
16042 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16043 DebugLoc DL = MI->getDebugLoc();
16045 // To "insert" a SELECT_CC instruction, we actually have to insert the
16046 // diamond control-flow pattern. The incoming instruction knows the
16047 // destination vreg to set, the condition code register to branch on, the
16048 // true/false values to select between, and a branch opcode to use.
16049 const BasicBlock *LLVM_BB = BB->getBasicBlock();
16050 MachineFunction::iterator It = BB;
16056 // cmpTY ccX, r1, r2
16058 // fallthrough --> copy0MBB
16059 MachineBasicBlock *thisMBB = BB;
16060 MachineFunction *F = BB->getParent();
16061 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
16062 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
16063 F->insert(It, copy0MBB);
16064 F->insert(It, sinkMBB);
16066 // If the EFLAGS register isn't dead in the terminator, then claim that it's
16067 // live into the sink and copy blocks.
16068 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
16069 if (!MI->killsRegister(X86::EFLAGS) &&
16070 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
16071 copy0MBB->addLiveIn(X86::EFLAGS);
16072 sinkMBB->addLiveIn(X86::EFLAGS);
16075 // Transfer the remainder of BB and its successor edges to sinkMBB.
16076 sinkMBB->splice(sinkMBB->begin(), BB,
16077 std::next(MachineBasicBlock::iterator(MI)), BB->end());
16078 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
16080 // Add the true and fallthrough blocks as its successors.
16081 BB->addSuccessor(copy0MBB);
16082 BB->addSuccessor(sinkMBB);
16084 // Create the conditional branch instruction.
16086 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
16087 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
16090 // %FalseValue = ...
16091 // # fallthrough to sinkMBB
16092 copy0MBB->addSuccessor(sinkMBB);
16095 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
16097 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16098 TII->get(X86::PHI), MI->getOperand(0).getReg())
16099 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
16100 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
16102 MI->eraseFromParent(); // The pseudo instruction is gone now.
16106 MachineBasicBlock *
16107 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
16108 bool Is64Bit) const {
16109 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16110 DebugLoc DL = MI->getDebugLoc();
16111 MachineFunction *MF = BB->getParent();
16112 const BasicBlock *LLVM_BB = BB->getBasicBlock();
16114 assert(MF->shouldSplitStack());
16116 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
16117 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
16120 // ... [Till the alloca]
16121 // If stacklet is not large enough, jump to mallocMBB
16124 // Allocate by subtracting from RSP
16125 // Jump to continueMBB
16128 // Allocate by call to runtime
16132 // [rest of original BB]
16135 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16136 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16137 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16139 MachineRegisterInfo &MRI = MF->getRegInfo();
16140 const TargetRegisterClass *AddrRegClass =
16141 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
16143 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16144 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16145 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
16146 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
16147 sizeVReg = MI->getOperand(1).getReg(),
16148 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
16150 MachineFunction::iterator MBBIter = BB;
16153 MF->insert(MBBIter, bumpMBB);
16154 MF->insert(MBBIter, mallocMBB);
16155 MF->insert(MBBIter, continueMBB);
16157 continueMBB->splice(continueMBB->begin(), BB,
16158 std::next(MachineBasicBlock::iterator(MI)), BB->end());
16159 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
16161 // Add code to the main basic block to check if the stack limit has been hit,
16162 // and if so, jump to mallocMBB otherwise to bumpMBB.
16163 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
16164 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
16165 .addReg(tmpSPVReg).addReg(sizeVReg);
16166 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
16167 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
16168 .addReg(SPLimitVReg);
16169 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
16171 // bumpMBB simply decreases the stack pointer, since we know the current
16172 // stacklet has enough space.
16173 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
16174 .addReg(SPLimitVReg);
16175 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
16176 .addReg(SPLimitVReg);
16177 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16179 // Calls into a routine in libgcc to allocate more space from the heap.
16180 const uint32_t *RegMask =
16181 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16183 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
16185 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
16186 .addExternalSymbol("__morestack_allocate_stack_space")
16187 .addRegMask(RegMask)
16188 .addReg(X86::RDI, RegState::Implicit)
16189 .addReg(X86::RAX, RegState::ImplicitDefine);
16191 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
16193 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
16194 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
16195 .addExternalSymbol("__morestack_allocate_stack_space")
16196 .addRegMask(RegMask)
16197 .addReg(X86::EAX, RegState::ImplicitDefine);
16201 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
16204 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
16205 .addReg(Is64Bit ? X86::RAX : X86::EAX);
16206 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16208 // Set up the CFG correctly.
16209 BB->addSuccessor(bumpMBB);
16210 BB->addSuccessor(mallocMBB);
16211 mallocMBB->addSuccessor(continueMBB);
16212 bumpMBB->addSuccessor(continueMBB);
16214 // Take care of the PHI nodes.
16215 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
16216 MI->getOperand(0).getReg())
16217 .addReg(mallocPtrVReg).addMBB(mallocMBB)
16218 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
16220 // Delete the original pseudo instruction.
16221 MI->eraseFromParent();
16224 return continueMBB;
16227 MachineBasicBlock *
16228 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
16229 MachineBasicBlock *BB) const {
16230 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16231 DebugLoc DL = MI->getDebugLoc();
16233 assert(!Subtarget->isTargetMacho());
16235 // The lowering is pretty easy: we're just emitting the call to _alloca. The
16236 // non-trivial part is impdef of ESP.
16238 if (Subtarget->isTargetWin64()) {
16239 if (Subtarget->isTargetCygMing()) {
16240 // ___chkstk(Mingw64):
16241 // Clobbers R10, R11, RAX and EFLAGS.
16243 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16244 .addExternalSymbol("___chkstk")
16245 .addReg(X86::RAX, RegState::Implicit)
16246 .addReg(X86::RSP, RegState::Implicit)
16247 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
16248 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
16249 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16251 // __chkstk(MSVCRT): does not update stack pointer.
16252 // Clobbers R10, R11 and EFLAGS.
16253 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16254 .addExternalSymbol("__chkstk")
16255 .addReg(X86::RAX, RegState::Implicit)
16256 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16257 // RAX has the offset to be subtracted from RSP.
16258 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
16263 const char *StackProbeSymbol =
16264 Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
16266 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
16267 .addExternalSymbol(StackProbeSymbol)
16268 .addReg(X86::EAX, RegState::Implicit)
16269 .addReg(X86::ESP, RegState::Implicit)
16270 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
16271 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
16272 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16275 MI->eraseFromParent(); // The pseudo instruction is gone now.
16279 MachineBasicBlock *
16280 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
16281 MachineBasicBlock *BB) const {
16282 // This is pretty easy. We're taking the value that we received from
16283 // our load from the relocation, sticking it in either RDI (x86-64)
16284 // or EAX and doing an indirect call. The return value will then
16285 // be in the normal return register.
16286 const X86InstrInfo *TII
16287 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
16288 DebugLoc DL = MI->getDebugLoc();
16289 MachineFunction *F = BB->getParent();
16291 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
16292 assert(MI->getOperand(3).isGlobal() && "This should be a global");
16294 // Get a register mask for the lowered call.
16295 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
16296 // proper register mask.
16297 const uint32_t *RegMask =
16298 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16299 if (Subtarget->is64Bit()) {
16300 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16301 TII->get(X86::MOV64rm), X86::RDI)
16303 .addImm(0).addReg(0)
16304 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16305 MI->getOperand(3).getTargetFlags())
16307 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
16308 addDirectMem(MIB, X86::RDI);
16309 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
16310 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
16311 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16312 TII->get(X86::MOV32rm), X86::EAX)
16314 .addImm(0).addReg(0)
16315 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16316 MI->getOperand(3).getTargetFlags())
16318 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16319 addDirectMem(MIB, X86::EAX);
16320 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16322 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16323 TII->get(X86::MOV32rm), X86::EAX)
16324 .addReg(TII->getGlobalBaseReg(F))
16325 .addImm(0).addReg(0)
16326 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16327 MI->getOperand(3).getTargetFlags())
16329 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16330 addDirectMem(MIB, X86::EAX);
16331 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16334 MI->eraseFromParent(); // The pseudo instruction is gone now.
16338 MachineBasicBlock *
16339 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
16340 MachineBasicBlock *MBB) const {
16341 DebugLoc DL = MI->getDebugLoc();
16342 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16344 MachineFunction *MF = MBB->getParent();
16345 MachineRegisterInfo &MRI = MF->getRegInfo();
16347 const BasicBlock *BB = MBB->getBasicBlock();
16348 MachineFunction::iterator I = MBB;
16351 // Memory Reference
16352 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16353 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16356 unsigned MemOpndSlot = 0;
16358 unsigned CurOp = 0;
16360 DstReg = MI->getOperand(CurOp++).getReg();
16361 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
16362 assert(RC->hasType(MVT::i32) && "Invalid destination!");
16363 unsigned mainDstReg = MRI.createVirtualRegister(RC);
16364 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
16366 MemOpndSlot = CurOp;
16368 MVT PVT = getPointerTy();
16369 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16370 "Invalid Pointer Size!");
16372 // For v = setjmp(buf), we generate
16375 // buf[LabelOffset] = restoreMBB
16376 // SjLjSetup restoreMBB
16382 // v = phi(main, restore)
16387 MachineBasicBlock *thisMBB = MBB;
16388 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16389 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16390 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
16391 MF->insert(I, mainMBB);
16392 MF->insert(I, sinkMBB);
16393 MF->push_back(restoreMBB);
16395 MachineInstrBuilder MIB;
16397 // Transfer the remainder of BB and its successor edges to sinkMBB.
16398 sinkMBB->splice(sinkMBB->begin(), MBB,
16399 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16400 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16403 unsigned PtrStoreOpc = 0;
16404 unsigned LabelReg = 0;
16405 const int64_t LabelOffset = 1 * PVT.getStoreSize();
16406 Reloc::Model RM = getTargetMachine().getRelocationModel();
16407 bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
16408 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
16410 // Prepare IP either in reg or imm.
16411 if (!UseImmLabel) {
16412 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
16413 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
16414 LabelReg = MRI.createVirtualRegister(PtrRC);
16415 if (Subtarget->is64Bit()) {
16416 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
16420 .addMBB(restoreMBB)
16423 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
16424 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
16425 .addReg(XII->getGlobalBaseReg(MF))
16428 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
16432 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
16434 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
16435 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16436 if (i == X86::AddrDisp)
16437 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
16439 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
16442 MIB.addReg(LabelReg);
16444 MIB.addMBB(restoreMBB);
16445 MIB.setMemRefs(MMOBegin, MMOEnd);
16447 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
16448 .addMBB(restoreMBB);
16450 const X86RegisterInfo *RegInfo =
16451 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16452 MIB.addRegMask(RegInfo->getNoPreservedMask());
16453 thisMBB->addSuccessor(mainMBB);
16454 thisMBB->addSuccessor(restoreMBB);
16458 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
16459 mainMBB->addSuccessor(sinkMBB);
16462 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16463 TII->get(X86::PHI), DstReg)
16464 .addReg(mainDstReg).addMBB(mainMBB)
16465 .addReg(restoreDstReg).addMBB(restoreMBB);
16468 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
16469 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
16470 restoreMBB->addSuccessor(sinkMBB);
16472 MI->eraseFromParent();
16476 MachineBasicBlock *
16477 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
16478 MachineBasicBlock *MBB) const {
16479 DebugLoc DL = MI->getDebugLoc();
16480 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16482 MachineFunction *MF = MBB->getParent();
16483 MachineRegisterInfo &MRI = MF->getRegInfo();
16485 // Memory Reference
16486 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16487 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16489 MVT PVT = getPointerTy();
16490 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16491 "Invalid Pointer Size!");
16493 const TargetRegisterClass *RC =
16494 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
16495 unsigned Tmp = MRI.createVirtualRegister(RC);
16496 // Since FP is only updated here but NOT referenced, it's treated as GPR.
16497 const X86RegisterInfo *RegInfo =
16498 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16499 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
16500 unsigned SP = RegInfo->getStackRegister();
16502 MachineInstrBuilder MIB;
16504 const int64_t LabelOffset = 1 * PVT.getStoreSize();
16505 const int64_t SPOffset = 2 * PVT.getStoreSize();
16507 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
16508 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
16511 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
16512 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
16513 MIB.addOperand(MI->getOperand(i));
16514 MIB.setMemRefs(MMOBegin, MMOEnd);
16516 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
16517 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16518 if (i == X86::AddrDisp)
16519 MIB.addDisp(MI->getOperand(i), LabelOffset);
16521 MIB.addOperand(MI->getOperand(i));
16523 MIB.setMemRefs(MMOBegin, MMOEnd);
16525 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
16526 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16527 if (i == X86::AddrDisp)
16528 MIB.addDisp(MI->getOperand(i), SPOffset);
16530 MIB.addOperand(MI->getOperand(i));
16532 MIB.setMemRefs(MMOBegin, MMOEnd);
16534 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
16536 MI->eraseFromParent();
16540 // Replace 213-type (isel default) FMA3 instructions with 231-type for
16541 // accumulator loops. Writing back to the accumulator allows the coalescer
16542 // to remove extra copies in the loop.
16543 MachineBasicBlock *
16544 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
16545 MachineBasicBlock *MBB) const {
16546 MachineOperand &AddendOp = MI->getOperand(3);
16548 // Bail out early if the addend isn't a register - we can't switch these.
16549 if (!AddendOp.isReg())
16552 MachineFunction &MF = *MBB->getParent();
16553 MachineRegisterInfo &MRI = MF.getRegInfo();
16555 // Check whether the addend is defined by a PHI:
16556 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
16557 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
16558 if (!AddendDef.isPHI())
16561 // Look for the following pattern:
16563 // %addend = phi [%entry, 0], [%loop, %result]
16565 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
16569 // %addend = phi [%entry, 0], [%loop, %result]
16571 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
16573 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
16574 assert(AddendDef.getOperand(i).isReg());
16575 MachineOperand PHISrcOp = AddendDef.getOperand(i);
16576 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
16577 if (&PHISrcInst == MI) {
16578 // Found a matching instruction.
16579 unsigned NewFMAOpc = 0;
16580 switch (MI->getOpcode()) {
16581 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
16582 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
16583 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
16584 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
16585 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
16586 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
16587 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
16588 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
16589 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
16590 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
16591 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
16592 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
16593 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
16594 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
16595 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
16596 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
16597 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
16598 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
16599 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
16600 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
16601 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
16602 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
16603 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
16604 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
16605 default: llvm_unreachable("Unrecognized FMA variant.");
16608 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
16609 MachineInstrBuilder MIB =
16610 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
16611 .addOperand(MI->getOperand(0))
16612 .addOperand(MI->getOperand(3))
16613 .addOperand(MI->getOperand(2))
16614 .addOperand(MI->getOperand(1));
16615 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
16616 MI->eraseFromParent();
16623 MachineBasicBlock *
16624 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
16625 MachineBasicBlock *BB) const {
16626 switch (MI->getOpcode()) {
16627 default: llvm_unreachable("Unexpected instr type to insert");
16628 case X86::TAILJMPd64:
16629 case X86::TAILJMPr64:
16630 case X86::TAILJMPm64:
16631 llvm_unreachable("TAILJMP64 would not be touched here.");
16632 case X86::TCRETURNdi64:
16633 case X86::TCRETURNri64:
16634 case X86::TCRETURNmi64:
16636 case X86::WIN_ALLOCA:
16637 return EmitLoweredWinAlloca(MI, BB);
16638 case X86::SEG_ALLOCA_32:
16639 return EmitLoweredSegAlloca(MI, BB, false);
16640 case X86::SEG_ALLOCA_64:
16641 return EmitLoweredSegAlloca(MI, BB, true);
16642 case X86::TLSCall_32:
16643 case X86::TLSCall_64:
16644 return EmitLoweredTLSCall(MI, BB);
16645 case X86::CMOV_GR8:
16646 case X86::CMOV_FR32:
16647 case X86::CMOV_FR64:
16648 case X86::CMOV_V4F32:
16649 case X86::CMOV_V2F64:
16650 case X86::CMOV_V2I64:
16651 case X86::CMOV_V8F32:
16652 case X86::CMOV_V4F64:
16653 case X86::CMOV_V4I64:
16654 case X86::CMOV_V16F32:
16655 case X86::CMOV_V8F64:
16656 case X86::CMOV_V8I64:
16657 case X86::CMOV_GR16:
16658 case X86::CMOV_GR32:
16659 case X86::CMOV_RFP32:
16660 case X86::CMOV_RFP64:
16661 case X86::CMOV_RFP80:
16662 return EmitLoweredSelect(MI, BB);
16664 case X86::FP32_TO_INT16_IN_MEM:
16665 case X86::FP32_TO_INT32_IN_MEM:
16666 case X86::FP32_TO_INT64_IN_MEM:
16667 case X86::FP64_TO_INT16_IN_MEM:
16668 case X86::FP64_TO_INT32_IN_MEM:
16669 case X86::FP64_TO_INT64_IN_MEM:
16670 case X86::FP80_TO_INT16_IN_MEM:
16671 case X86::FP80_TO_INT32_IN_MEM:
16672 case X86::FP80_TO_INT64_IN_MEM: {
16673 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16674 DebugLoc DL = MI->getDebugLoc();
16676 // Change the floating point control register to use "round towards zero"
16677 // mode when truncating to an integer value.
16678 MachineFunction *F = BB->getParent();
16679 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
16680 addFrameReference(BuildMI(*BB, MI, DL,
16681 TII->get(X86::FNSTCW16m)), CWFrameIdx);
16683 // Load the old value of the high byte of the control word...
16685 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
16686 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
16689 // Set the high part to be round to zero...
16690 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
16693 // Reload the modified control word now...
16694 addFrameReference(BuildMI(*BB, MI, DL,
16695 TII->get(X86::FLDCW16m)), CWFrameIdx);
16697 // Restore the memory image of control word to original value
16698 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
16701 // Get the X86 opcode to use.
16703 switch (MI->getOpcode()) {
16704 default: llvm_unreachable("illegal opcode!");
16705 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
16706 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
16707 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
16708 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
16709 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
16710 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
16711 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
16712 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
16713 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
16717 MachineOperand &Op = MI->getOperand(0);
16719 AM.BaseType = X86AddressMode::RegBase;
16720 AM.Base.Reg = Op.getReg();
16722 AM.BaseType = X86AddressMode::FrameIndexBase;
16723 AM.Base.FrameIndex = Op.getIndex();
16725 Op = MI->getOperand(1);
16727 AM.Scale = Op.getImm();
16728 Op = MI->getOperand(2);
16730 AM.IndexReg = Op.getImm();
16731 Op = MI->getOperand(3);
16732 if (Op.isGlobal()) {
16733 AM.GV = Op.getGlobal();
16735 AM.Disp = Op.getImm();
16737 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
16738 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
16740 // Reload the original control word now.
16741 addFrameReference(BuildMI(*BB, MI, DL,
16742 TII->get(X86::FLDCW16m)), CWFrameIdx);
16744 MI->eraseFromParent(); // The pseudo instruction is gone now.
16747 // String/text processing lowering.
16748 case X86::PCMPISTRM128REG:
16749 case X86::VPCMPISTRM128REG:
16750 case X86::PCMPISTRM128MEM:
16751 case X86::VPCMPISTRM128MEM:
16752 case X86::PCMPESTRM128REG:
16753 case X86::VPCMPESTRM128REG:
16754 case X86::PCMPESTRM128MEM:
16755 case X86::VPCMPESTRM128MEM:
16756 assert(Subtarget->hasSSE42() &&
16757 "Target must have SSE4.2 or AVX features enabled");
16758 return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
16760 // String/text processing lowering.
16761 case X86::PCMPISTRIREG:
16762 case X86::VPCMPISTRIREG:
16763 case X86::PCMPISTRIMEM:
16764 case X86::VPCMPISTRIMEM:
16765 case X86::PCMPESTRIREG:
16766 case X86::VPCMPESTRIREG:
16767 case X86::PCMPESTRIMEM:
16768 case X86::VPCMPESTRIMEM:
16769 assert(Subtarget->hasSSE42() &&
16770 "Target must have SSE4.2 or AVX features enabled");
16771 return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
16773 // Thread synchronization.
16775 return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
16779 return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
16781 // Atomic Lowering.
16782 case X86::ATOMAND8:
16783 case X86::ATOMAND16:
16784 case X86::ATOMAND32:
16785 case X86::ATOMAND64:
16788 case X86::ATOMOR16:
16789 case X86::ATOMOR32:
16790 case X86::ATOMOR64:
16792 case X86::ATOMXOR16:
16793 case X86::ATOMXOR8:
16794 case X86::ATOMXOR32:
16795 case X86::ATOMXOR64:
16797 case X86::ATOMNAND8:
16798 case X86::ATOMNAND16:
16799 case X86::ATOMNAND32:
16800 case X86::ATOMNAND64:
16802 case X86::ATOMMAX8:
16803 case X86::ATOMMAX16:
16804 case X86::ATOMMAX32:
16805 case X86::ATOMMAX64:
16807 case X86::ATOMMIN8:
16808 case X86::ATOMMIN16:
16809 case X86::ATOMMIN32:
16810 case X86::ATOMMIN64:
16812 case X86::ATOMUMAX8:
16813 case X86::ATOMUMAX16:
16814 case X86::ATOMUMAX32:
16815 case X86::ATOMUMAX64:
16817 case X86::ATOMUMIN8:
16818 case X86::ATOMUMIN16:
16819 case X86::ATOMUMIN32:
16820 case X86::ATOMUMIN64:
16821 return EmitAtomicLoadArith(MI, BB);
16823 // This group does 64-bit operations on a 32-bit host.
16824 case X86::ATOMAND6432:
16825 case X86::ATOMOR6432:
16826 case X86::ATOMXOR6432:
16827 case X86::ATOMNAND6432:
16828 case X86::ATOMADD6432:
16829 case X86::ATOMSUB6432:
16830 case X86::ATOMMAX6432:
16831 case X86::ATOMMIN6432:
16832 case X86::ATOMUMAX6432:
16833 case X86::ATOMUMIN6432:
16834 case X86::ATOMSWAP6432:
16835 return EmitAtomicLoadArith6432(MI, BB);
16837 case X86::VASTART_SAVE_XMM_REGS:
16838 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
16840 case X86::VAARG_64:
16841 return EmitVAARG64WithCustomInserter(MI, BB);
16843 case X86::EH_SjLj_SetJmp32:
16844 case X86::EH_SjLj_SetJmp64:
16845 return emitEHSjLjSetJmp(MI, BB);
16847 case X86::EH_SjLj_LongJmp32:
16848 case X86::EH_SjLj_LongJmp64:
16849 return emitEHSjLjLongJmp(MI, BB);
16851 case TargetOpcode::STACKMAP:
16852 case TargetOpcode::PATCHPOINT:
16853 return emitPatchPoint(MI, BB);
16855 case X86::VFMADDPDr213r:
16856 case X86::VFMADDPSr213r:
16857 case X86::VFMADDSDr213r:
16858 case X86::VFMADDSSr213r:
16859 case X86::VFMSUBPDr213r:
16860 case X86::VFMSUBPSr213r:
16861 case X86::VFMSUBSDr213r:
16862 case X86::VFMSUBSSr213r:
16863 case X86::VFNMADDPDr213r:
16864 case X86::VFNMADDPSr213r:
16865 case X86::VFNMADDSDr213r:
16866 case X86::VFNMADDSSr213r:
16867 case X86::VFNMSUBPDr213r:
16868 case X86::VFNMSUBPSr213r:
16869 case X86::VFNMSUBSDr213r:
16870 case X86::VFNMSUBSSr213r:
16871 case X86::VFMADDPDr213rY:
16872 case X86::VFMADDPSr213rY:
16873 case X86::VFMSUBPDr213rY:
16874 case X86::VFMSUBPSr213rY:
16875 case X86::VFNMADDPDr213rY:
16876 case X86::VFNMADDPSr213rY:
16877 case X86::VFNMSUBPDr213rY:
16878 case X86::VFNMSUBPSr213rY:
16879 return emitFMA3Instr(MI, BB);
16883 //===----------------------------------------------------------------------===//
16884 // X86 Optimization Hooks
16885 //===----------------------------------------------------------------------===//
16887 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
16890 const SelectionDAG &DAG,
16891 unsigned Depth) const {
16892 unsigned BitWidth = KnownZero.getBitWidth();
16893 unsigned Opc = Op.getOpcode();
16894 assert((Opc >= ISD::BUILTIN_OP_END ||
16895 Opc == ISD::INTRINSIC_WO_CHAIN ||
16896 Opc == ISD::INTRINSIC_W_CHAIN ||
16897 Opc == ISD::INTRINSIC_VOID) &&
16898 "Should use MaskedValueIsZero if you don't know whether Op"
16899 " is a target node!");
16901 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
16915 // These nodes' second result is a boolean.
16916 if (Op.getResNo() == 0)
16919 case X86ISD::SETCC:
16920 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
16922 case ISD::INTRINSIC_WO_CHAIN: {
16923 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16924 unsigned NumLoBits = 0;
16927 case Intrinsic::x86_sse_movmsk_ps:
16928 case Intrinsic::x86_avx_movmsk_ps_256:
16929 case Intrinsic::x86_sse2_movmsk_pd:
16930 case Intrinsic::x86_avx_movmsk_pd_256:
16931 case Intrinsic::x86_mmx_pmovmskb:
16932 case Intrinsic::x86_sse2_pmovmskb_128:
16933 case Intrinsic::x86_avx2_pmovmskb: {
16934 // High bits of movmskp{s|d}, pmovmskb are known zero.
16936 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
16937 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
16938 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
16939 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
16940 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
16941 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
16942 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
16943 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
16945 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
16954 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
16956 const SelectionDAG &,
16957 unsigned Depth) const {
16958 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
16959 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
16960 return Op.getValueType().getScalarType().getSizeInBits();
16966 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
16967 /// node is a GlobalAddress + offset.
16968 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
16969 const GlobalValue* &GA,
16970 int64_t &Offset) const {
16971 if (N->getOpcode() == X86ISD::Wrapper) {
16972 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
16973 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
16974 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
16978 return TargetLowering::isGAPlusOffset(N, GA, Offset);
16981 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
16982 /// same as extracting the high 128-bit part of 256-bit vector and then
16983 /// inserting the result into the low part of a new 256-bit vector
16984 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
16985 EVT VT = SVOp->getValueType(0);
16986 unsigned NumElems = VT.getVectorNumElements();
16988 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
16989 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
16990 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
16991 SVOp->getMaskElt(j) >= 0)
16997 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
16998 /// same as extracting the low 128-bit part of 256-bit vector and then
16999 /// inserting the result into the high part of a new 256-bit vector
17000 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
17001 EVT VT = SVOp->getValueType(0);
17002 unsigned NumElems = VT.getVectorNumElements();
17004 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17005 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
17006 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17007 SVOp->getMaskElt(j) >= 0)
17013 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
17014 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
17015 TargetLowering::DAGCombinerInfo &DCI,
17016 const X86Subtarget* Subtarget) {
17018 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17019 SDValue V1 = SVOp->getOperand(0);
17020 SDValue V2 = SVOp->getOperand(1);
17021 EVT VT = SVOp->getValueType(0);
17022 unsigned NumElems = VT.getVectorNumElements();
17024 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
17025 V2.getOpcode() == ISD::CONCAT_VECTORS) {
17029 // V UNDEF BUILD_VECTOR UNDEF
17031 // CONCAT_VECTOR CONCAT_VECTOR
17034 // RESULT: V + zero extended
17036 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
17037 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
17038 V1.getOperand(1).getOpcode() != ISD::UNDEF)
17041 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
17044 // To match the shuffle mask, the first half of the mask should
17045 // be exactly the first vector, and all the rest a splat with the
17046 // first element of the second one.
17047 for (unsigned i = 0; i != NumElems/2; ++i)
17048 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
17049 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
17052 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
17053 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
17054 if (Ld->hasNUsesOfValue(1, 0)) {
17055 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
17056 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
17058 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
17059 array_lengthof(Ops),
17061 Ld->getPointerInfo(),
17062 Ld->getAlignment(),
17063 false/*isVolatile*/, true/*ReadMem*/,
17064 false/*WriteMem*/);
17066 // Make sure the newly-created LOAD is in the same position as Ld in
17067 // terms of dependency. We create a TokenFactor for Ld and ResNode,
17068 // and update uses of Ld's output chain to use the TokenFactor.
17069 if (Ld->hasAnyUseOfValue(1)) {
17070 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17071 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
17072 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
17073 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
17074 SDValue(ResNode.getNode(), 1));
17077 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
17081 // Emit a zeroed vector and insert the desired subvector on its
17083 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17084 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
17085 return DCI.CombineTo(N, InsV);
17088 //===--------------------------------------------------------------------===//
17089 // Combine some shuffles into subvector extracts and inserts:
17092 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17093 if (isShuffleHigh128VectorInsertLow(SVOp)) {
17094 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
17095 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
17096 return DCI.CombineTo(N, InsV);
17099 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17100 if (isShuffleLow128VectorInsertHigh(SVOp)) {
17101 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
17102 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
17103 return DCI.CombineTo(N, InsV);
17109 /// PerformShuffleCombine - Performs several different shuffle combines.
17110 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
17111 TargetLowering::DAGCombinerInfo &DCI,
17112 const X86Subtarget *Subtarget) {
17114 EVT VT = N->getValueType(0);
17116 // Don't create instructions with illegal types after legalize types has run.
17117 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17118 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
17121 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
17122 if (Subtarget->hasFp256() && VT.is256BitVector() &&
17123 N->getOpcode() == ISD::VECTOR_SHUFFLE)
17124 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
17126 // Only handle 128 wide vector from here on.
17127 if (!VT.is128BitVector())
17130 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
17131 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
17132 // consecutive, non-overlapping, and in the right order.
17133 SmallVector<SDValue, 16> Elts;
17134 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
17135 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
17137 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
17140 /// PerformTruncateCombine - Converts truncate operation to
17141 /// a sequence of vector shuffle operations.
17142 /// It is possible when we truncate 256-bit vector to 128-bit vector
17143 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
17144 TargetLowering::DAGCombinerInfo &DCI,
17145 const X86Subtarget *Subtarget) {
17149 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
17150 /// specific shuffle of a load can be folded into a single element load.
17151 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
17152 /// shuffles have been customed lowered so we need to handle those here.
17153 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
17154 TargetLowering::DAGCombinerInfo &DCI) {
17155 if (DCI.isBeforeLegalizeOps())
17158 SDValue InVec = N->getOperand(0);
17159 SDValue EltNo = N->getOperand(1);
17161 if (!isa<ConstantSDNode>(EltNo))
17164 EVT VT = InVec.getValueType();
17166 bool HasShuffleIntoBitcast = false;
17167 if (InVec.getOpcode() == ISD::BITCAST) {
17168 // Don't duplicate a load with other uses.
17169 if (!InVec.hasOneUse())
17171 EVT BCVT = InVec.getOperand(0).getValueType();
17172 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
17174 InVec = InVec.getOperand(0);
17175 HasShuffleIntoBitcast = true;
17178 if (!isTargetShuffle(InVec.getOpcode()))
17181 // Don't duplicate a load with other uses.
17182 if (!InVec.hasOneUse())
17185 SmallVector<int, 16> ShuffleMask;
17187 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
17191 // Select the input vector, guarding against out of range extract vector.
17192 unsigned NumElems = VT.getVectorNumElements();
17193 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
17194 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
17195 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
17196 : InVec.getOperand(1);
17198 // If inputs to shuffle are the same for both ops, then allow 2 uses
17199 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
17201 if (LdNode.getOpcode() == ISD::BITCAST) {
17202 // Don't duplicate a load with other uses.
17203 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
17206 AllowedUses = 1; // only allow 1 load use if we have a bitcast
17207 LdNode = LdNode.getOperand(0);
17210 if (!ISD::isNormalLoad(LdNode.getNode()))
17213 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
17215 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
17218 if (HasShuffleIntoBitcast) {
17219 // If there's a bitcast before the shuffle, check if the load type and
17220 // alignment is valid.
17221 unsigned Align = LN0->getAlignment();
17222 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17223 unsigned NewAlign = TLI.getDataLayout()->
17224 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
17226 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
17230 // All checks match so transform back to vector_shuffle so that DAG combiner
17231 // can finish the job
17234 // Create shuffle node taking into account the case that its a unary shuffle
17235 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
17236 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
17237 InVec.getOperand(0), Shuffle,
17239 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
17240 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
17244 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
17245 /// generation and convert it from being a bunch of shuffles and extracts
17246 /// to a simple store and scalar loads to extract the elements.
17247 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
17248 TargetLowering::DAGCombinerInfo &DCI) {
17249 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
17250 if (NewOp.getNode())
17253 SDValue InputVector = N->getOperand(0);
17255 // Detect whether we are trying to convert from mmx to i32 and the bitcast
17256 // from mmx to v2i32 has a single usage.
17257 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
17258 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
17259 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
17260 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
17261 N->getValueType(0),
17262 InputVector.getNode()->getOperand(0));
17264 // Only operate on vectors of 4 elements, where the alternative shuffling
17265 // gets to be more expensive.
17266 if (InputVector.getValueType() != MVT::v4i32)
17269 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
17270 // single use which is a sign-extend or zero-extend, and all elements are
17272 SmallVector<SDNode *, 4> Uses;
17273 unsigned ExtractedElements = 0;
17274 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
17275 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
17276 if (UI.getUse().getResNo() != InputVector.getResNo())
17279 SDNode *Extract = *UI;
17280 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
17283 if (Extract->getValueType(0) != MVT::i32)
17285 if (!Extract->hasOneUse())
17287 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
17288 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
17290 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
17293 // Record which element was extracted.
17294 ExtractedElements |=
17295 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
17297 Uses.push_back(Extract);
17300 // If not all the elements were used, this may not be worthwhile.
17301 if (ExtractedElements != 15)
17304 // Ok, we've now decided to do the transformation.
17305 SDLoc dl(InputVector);
17307 // Store the value to a temporary stack slot.
17308 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
17309 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
17310 MachinePointerInfo(), false, false, 0);
17312 // Replace each use (extract) with a load of the appropriate element.
17313 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
17314 UE = Uses.end(); UI != UE; ++UI) {
17315 SDNode *Extract = *UI;
17317 // cOMpute the element's address.
17318 SDValue Idx = Extract->getOperand(1);
17320 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
17321 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
17322 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17323 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
17325 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
17326 StackPtr, OffsetVal);
17328 // Load the scalar.
17329 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
17330 ScalarAddr, MachinePointerInfo(),
17331 false, false, false, 0);
17333 // Replace the exact with the load.
17334 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
17337 // The replacement was made in place; don't return anything.
17341 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
17342 static std::pair<unsigned, bool>
17343 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
17344 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
17345 if (!VT.isVector())
17346 return std::make_pair(0, false);
17348 bool NeedSplit = false;
17349 switch (VT.getSimpleVT().SimpleTy) {
17350 default: return std::make_pair(0, false);
17354 if (!Subtarget->hasAVX2())
17356 if (!Subtarget->hasAVX())
17357 return std::make_pair(0, false);
17362 if (!Subtarget->hasSSE2())
17363 return std::make_pair(0, false);
17366 // SSE2 has only a small subset of the operations.
17367 bool hasUnsigned = Subtarget->hasSSE41() ||
17368 (Subtarget->hasSSE2() && VT == MVT::v16i8);
17369 bool hasSigned = Subtarget->hasSSE41() ||
17370 (Subtarget->hasSSE2() && VT == MVT::v8i16);
17372 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17375 // Check for x CC y ? x : y.
17376 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17377 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17382 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17385 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17388 Opc = hasSigned ? X86ISD::SMIN : 0; break;
17391 Opc = hasSigned ? X86ISD::SMAX : 0; break;
17393 // Check for x CC y ? y : x -- a min/max with reversed arms.
17394 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17395 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17400 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17403 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17406 Opc = hasSigned ? X86ISD::SMAX : 0; break;
17409 Opc = hasSigned ? X86ISD::SMIN : 0; break;
17413 return std::make_pair(Opc, NeedSplit);
17416 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
17418 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
17419 TargetLowering::DAGCombinerInfo &DCI,
17420 const X86Subtarget *Subtarget) {
17422 SDValue Cond = N->getOperand(0);
17423 // Get the LHS/RHS of the select.
17424 SDValue LHS = N->getOperand(1);
17425 SDValue RHS = N->getOperand(2);
17426 EVT VT = LHS.getValueType();
17427 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17429 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
17430 // instructions match the semantics of the common C idiom x<y?x:y but not
17431 // x<=y?x:y, because of how they handle negative zero (which can be
17432 // ignored in unsafe-math mode).
17433 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
17434 VT != MVT::f80 && TLI.isTypeLegal(VT) &&
17435 (Subtarget->hasSSE2() ||
17436 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
17437 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17439 unsigned Opcode = 0;
17440 // Check for x CC y ? x : y.
17441 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17442 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17446 // Converting this to a min would handle NaNs incorrectly, and swapping
17447 // the operands would cause it to handle comparisons between positive
17448 // and negative zero incorrectly.
17449 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17450 if (!DAG.getTarget().Options.UnsafeFPMath &&
17451 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17453 std::swap(LHS, RHS);
17455 Opcode = X86ISD::FMIN;
17458 // Converting this to a min would handle comparisons between positive
17459 // and negative zero incorrectly.
17460 if (!DAG.getTarget().Options.UnsafeFPMath &&
17461 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17463 Opcode = X86ISD::FMIN;
17466 // Converting this to a min would handle both negative zeros and NaNs
17467 // incorrectly, but we can swap the operands to fix both.
17468 std::swap(LHS, RHS);
17472 Opcode = X86ISD::FMIN;
17476 // Converting this to a max would handle comparisons between positive
17477 // and negative zero incorrectly.
17478 if (!DAG.getTarget().Options.UnsafeFPMath &&
17479 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17481 Opcode = X86ISD::FMAX;
17484 // Converting this to a max would handle NaNs incorrectly, and swapping
17485 // the operands would cause it to handle comparisons between positive
17486 // and negative zero incorrectly.
17487 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17488 if (!DAG.getTarget().Options.UnsafeFPMath &&
17489 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17491 std::swap(LHS, RHS);
17493 Opcode = X86ISD::FMAX;
17496 // Converting this to a max would handle both negative zeros and NaNs
17497 // incorrectly, but we can swap the operands to fix both.
17498 std::swap(LHS, RHS);
17502 Opcode = X86ISD::FMAX;
17505 // Check for x CC y ? y : x -- a min/max with reversed arms.
17506 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17507 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17511 // Converting this to a min would handle comparisons between positive
17512 // and negative zero incorrectly, and swapping the operands would
17513 // cause it to handle NaNs incorrectly.
17514 if (!DAG.getTarget().Options.UnsafeFPMath &&
17515 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
17516 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17518 std::swap(LHS, RHS);
17520 Opcode = X86ISD::FMIN;
17523 // Converting this to a min would handle NaNs incorrectly.
17524 if (!DAG.getTarget().Options.UnsafeFPMath &&
17525 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
17527 Opcode = X86ISD::FMIN;
17530 // Converting this to a min would handle both negative zeros and NaNs
17531 // incorrectly, but we can swap the operands to fix both.
17532 std::swap(LHS, RHS);
17536 Opcode = X86ISD::FMIN;
17540 // Converting this to a max would handle NaNs incorrectly.
17541 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17543 Opcode = X86ISD::FMAX;
17546 // Converting this to a max would handle comparisons between positive
17547 // and negative zero incorrectly, and swapping the operands would
17548 // cause it to handle NaNs incorrectly.
17549 if (!DAG.getTarget().Options.UnsafeFPMath &&
17550 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
17551 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17553 std::swap(LHS, RHS);
17555 Opcode = X86ISD::FMAX;
17558 // Converting this to a max would handle both negative zeros and NaNs
17559 // incorrectly, but we can swap the operands to fix both.
17560 std::swap(LHS, RHS);
17564 Opcode = X86ISD::FMAX;
17570 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
17573 EVT CondVT = Cond.getValueType();
17574 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
17575 CondVT.getVectorElementType() == MVT::i1) {
17576 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
17577 // lowering on AVX-512. In this case we convert it to
17578 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
17579 // The same situation for all 128 and 256-bit vectors of i8 and i16
17580 EVT OpVT = LHS.getValueType();
17581 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
17582 (OpVT.getVectorElementType() == MVT::i8 ||
17583 OpVT.getVectorElementType() == MVT::i16)) {
17584 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
17585 DCI.AddToWorklist(Cond.getNode());
17586 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
17589 // If this is a select between two integer constants, try to do some
17591 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
17592 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
17593 // Don't do this for crazy integer types.
17594 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
17595 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
17596 // so that TrueC (the true value) is larger than FalseC.
17597 bool NeedsCondInvert = false;
17599 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
17600 // Efficiently invertible.
17601 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
17602 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
17603 isa<ConstantSDNode>(Cond.getOperand(1))))) {
17604 NeedsCondInvert = true;
17605 std::swap(TrueC, FalseC);
17608 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
17609 if (FalseC->getAPIntValue() == 0 &&
17610 TrueC->getAPIntValue().isPowerOf2()) {
17611 if (NeedsCondInvert) // Invert the condition if needed.
17612 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17613 DAG.getConstant(1, Cond.getValueType()));
17615 // Zero extend the condition if needed.
17616 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
17618 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17619 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
17620 DAG.getConstant(ShAmt, MVT::i8));
17623 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
17624 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17625 if (NeedsCondInvert) // Invert the condition if needed.
17626 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17627 DAG.getConstant(1, Cond.getValueType()));
17629 // Zero extend the condition if needed.
17630 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17631 FalseC->getValueType(0), Cond);
17632 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17633 SDValue(FalseC, 0));
17636 // Optimize cases that will turn into an LEA instruction. This requires
17637 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17638 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17639 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17640 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17642 bool isFastMultiplier = false;
17644 switch ((unsigned char)Diff) {
17646 case 1: // result = add base, cond
17647 case 2: // result = lea base( , cond*2)
17648 case 3: // result = lea base(cond, cond*2)
17649 case 4: // result = lea base( , cond*4)
17650 case 5: // result = lea base(cond, cond*4)
17651 case 8: // result = lea base( , cond*8)
17652 case 9: // result = lea base(cond, cond*8)
17653 isFastMultiplier = true;
17658 if (isFastMultiplier) {
17659 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
17660 if (NeedsCondInvert) // Invert the condition if needed.
17661 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17662 DAG.getConstant(1, Cond.getValueType()));
17664 // Zero extend the condition if needed.
17665 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
17667 // Scale the condition by the difference.
17669 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
17670 DAG.getConstant(Diff, Cond.getValueType()));
17672 // Add the base if non-zero.
17673 if (FalseC->getAPIntValue() != 0)
17674 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17675 SDValue(FalseC, 0));
17682 // Canonicalize max and min:
17683 // (x > y) ? x : y -> (x >= y) ? x : y
17684 // (x < y) ? x : y -> (x <= y) ? x : y
17685 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
17686 // the need for an extra compare
17687 // against zero. e.g.
17688 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
17690 // testl %edi, %edi
17692 // cmovgl %edi, %eax
17696 // cmovsl %eax, %edi
17697 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
17698 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17699 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17700 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17705 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
17706 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
17707 Cond.getOperand(0), Cond.getOperand(1), NewCC);
17708 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
17713 // Early exit check
17714 if (!TLI.isTypeLegal(VT))
17717 // Match VSELECTs into subs with unsigned saturation.
17718 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17719 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
17720 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
17721 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
17722 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17724 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
17725 // left side invert the predicate to simplify logic below.
17727 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
17729 CC = ISD::getSetCCInverse(CC, true);
17730 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
17734 if (Other.getNode() && Other->getNumOperands() == 2 &&
17735 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
17736 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
17737 SDValue CondRHS = Cond->getOperand(1);
17739 // Look for a general sub with unsigned saturation first.
17740 // x >= y ? x-y : 0 --> subus x, y
17741 // x > y ? x-y : 0 --> subus x, y
17742 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
17743 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
17744 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17746 // If the RHS is a constant we have to reverse the const canonicalization.
17747 // x > C-1 ? x+-C : 0 --> subus x, C
17748 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
17749 isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
17750 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17751 if (CondRHS.getConstantOperandVal(0) == -A-1)
17752 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
17753 DAG.getConstant(-A, VT));
17756 // Another special case: If C was a sign bit, the sub has been
17757 // canonicalized into a xor.
17758 // FIXME: Would it be better to use ComputeMaskedBits to determine whether
17759 // it's safe to decanonicalize the xor?
17760 // x s< 0 ? x^C : 0 --> subus x, C
17761 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
17762 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
17763 isSplatVector(OpRHS.getNode())) {
17764 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17766 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17771 // Try to match a min/max vector operation.
17772 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
17773 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
17774 unsigned Opc = ret.first;
17775 bool NeedSplit = ret.second;
17777 if (Opc && NeedSplit) {
17778 unsigned NumElems = VT.getVectorNumElements();
17779 // Extract the LHS vectors
17780 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
17781 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
17783 // Extract the RHS vectors
17784 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
17785 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
17787 // Create min/max for each subvector
17788 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
17789 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
17791 // Merge the result
17792 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
17794 return DAG.getNode(Opc, DL, VT, LHS, RHS);
17797 // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
17798 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17799 // Check if SETCC has already been promoted
17800 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
17801 // Check that condition value type matches vselect operand type
17804 assert(Cond.getValueType().isVector() &&
17805 "vector select expects a vector selector!");
17807 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
17808 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
17810 if (!TValIsAllOnes && !FValIsAllZeros) {
17811 // Try invert the condition if true value is not all 1s and false value
17813 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
17814 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
17816 if (TValIsAllZeros || FValIsAllOnes) {
17817 SDValue CC = Cond.getOperand(2);
17818 ISD::CondCode NewCC =
17819 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
17820 Cond.getOperand(0).getValueType().isInteger());
17821 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
17822 std::swap(LHS, RHS);
17823 TValIsAllOnes = FValIsAllOnes;
17824 FValIsAllZeros = TValIsAllZeros;
17828 if (TValIsAllOnes || FValIsAllZeros) {
17831 if (TValIsAllOnes && FValIsAllZeros)
17833 else if (TValIsAllOnes)
17834 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
17835 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
17836 else if (FValIsAllZeros)
17837 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
17838 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
17840 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
17844 // Try to fold this VSELECT into a MOVSS/MOVSD
17845 if (N->getOpcode() == ISD::VSELECT &&
17846 Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
17847 if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
17848 (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
17849 bool CanFold = false;
17850 unsigned NumElems = Cond.getNumOperands();
17854 if (isZero(Cond.getOperand(0))) {
17857 // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
17858 // fold (vselect <0,-1> -> (movsd A, B)
17859 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17860 CanFold = isAllOnes(Cond.getOperand(i));
17861 } else if (isAllOnes(Cond.getOperand(0))) {
17865 // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
17866 // fold (vselect <-1,0> -> (movsd B, A)
17867 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17868 CanFold = isZero(Cond.getOperand(i));
17872 if (VT == MVT::v4i32 || VT == MVT::v4f32)
17873 return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
17874 return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
17877 if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
17878 // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
17879 // (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
17880 // (v2i64 (bitcast B)))))
17882 // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
17883 // (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
17884 // (v2f64 (bitcast B)))))
17886 // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
17887 // (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
17888 // (v2i64 (bitcast A)))))
17890 // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
17891 // (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
17892 // (v2f64 (bitcast A)))))
17894 CanFold = (isZero(Cond.getOperand(0)) &&
17895 isZero(Cond.getOperand(1)) &&
17896 isAllOnes(Cond.getOperand(2)) &&
17897 isAllOnes(Cond.getOperand(3)));
17899 if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
17900 isAllOnes(Cond.getOperand(1)) &&
17901 isZero(Cond.getOperand(2)) &&
17902 isZero(Cond.getOperand(3))) {
17904 std::swap(LHS, RHS);
17908 EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
17909 SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
17910 SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
17911 SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
17913 return DAG.getNode(ISD::BITCAST, DL, VT, Select);
17919 // If we know that this node is legal then we know that it is going to be
17920 // matched by one of the SSE/AVX BLEND instructions. These instructions only
17921 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
17922 // to simplify previous instructions.
17923 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
17924 !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
17925 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
17927 // Don't optimize vector selects that map to mask-registers.
17931 // Check all uses of that condition operand to check whether it will be
17932 // consumed by non-BLEND instructions, which may depend on all bits are set
17934 for (SDNode::use_iterator I = Cond->use_begin(),
17935 E = Cond->use_end(); I != E; ++I)
17936 if (I->getOpcode() != ISD::VSELECT)
17937 // TODO: Add other opcodes eventually lowered into BLEND.
17940 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
17941 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
17943 APInt KnownZero, KnownOne;
17944 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
17945 DCI.isBeforeLegalizeOps());
17946 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
17947 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
17948 DCI.CommitTargetLoweringOpt(TLO);
17954 // Check whether a boolean test is testing a boolean value generated by
17955 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
17958 // Simplify the following patterns:
17959 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
17960 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
17961 // to (Op EFLAGS Cond)
17963 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
17964 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
17965 // to (Op EFLAGS !Cond)
17967 // where Op could be BRCOND or CMOV.
17969 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
17970 // Quit if not CMP and SUB with its value result used.
17971 if (Cmp.getOpcode() != X86ISD::CMP &&
17972 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
17975 // Quit if not used as a boolean value.
17976 if (CC != X86::COND_E && CC != X86::COND_NE)
17979 // Check CMP operands. One of them should be 0 or 1 and the other should be
17980 // an SetCC or extended from it.
17981 SDValue Op1 = Cmp.getOperand(0);
17982 SDValue Op2 = Cmp.getOperand(1);
17985 const ConstantSDNode* C = nullptr;
17986 bool needOppositeCond = (CC == X86::COND_E);
17987 bool checkAgainstTrue = false; // Is it a comparison against 1?
17989 if ((C = dyn_cast<ConstantSDNode>(Op1)))
17991 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
17993 else // Quit if all operands are not constants.
17996 if (C->getZExtValue() == 1) {
17997 needOppositeCond = !needOppositeCond;
17998 checkAgainstTrue = true;
17999 } else if (C->getZExtValue() != 0)
18000 // Quit if the constant is neither 0 or 1.
18003 bool truncatedToBoolWithAnd = false;
18004 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
18005 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
18006 SetCC.getOpcode() == ISD::TRUNCATE ||
18007 SetCC.getOpcode() == ISD::AND) {
18008 if (SetCC.getOpcode() == ISD::AND) {
18010 ConstantSDNode *CS;
18011 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
18012 CS->getZExtValue() == 1)
18014 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
18015 CS->getZExtValue() == 1)
18019 SetCC = SetCC.getOperand(OpIdx);
18020 truncatedToBoolWithAnd = true;
18022 SetCC = SetCC.getOperand(0);
18025 switch (SetCC.getOpcode()) {
18026 case X86ISD::SETCC_CARRY:
18027 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
18028 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
18029 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
18030 // truncated to i1 using 'and'.
18031 if (checkAgainstTrue && !truncatedToBoolWithAnd)
18033 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
18034 "Invalid use of SETCC_CARRY!");
18036 case X86ISD::SETCC:
18037 // Set the condition code or opposite one if necessary.
18038 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
18039 if (needOppositeCond)
18040 CC = X86::GetOppositeBranchCondition(CC);
18041 return SetCC.getOperand(1);
18042 case X86ISD::CMOV: {
18043 // Check whether false/true value has canonical one, i.e. 0 or 1.
18044 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
18045 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
18046 // Quit if true value is not a constant.
18049 // Quit if false value is not a constant.
18051 SDValue Op = SetCC.getOperand(0);
18052 // Skip 'zext' or 'trunc' node.
18053 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
18054 Op.getOpcode() == ISD::TRUNCATE)
18055 Op = Op.getOperand(0);
18056 // A special case for rdrand/rdseed, where 0 is set if false cond is
18058 if ((Op.getOpcode() != X86ISD::RDRAND &&
18059 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
18062 // Quit if false value is not the constant 0 or 1.
18063 bool FValIsFalse = true;
18064 if (FVal && FVal->getZExtValue() != 0) {
18065 if (FVal->getZExtValue() != 1)
18067 // If FVal is 1, opposite cond is needed.
18068 needOppositeCond = !needOppositeCond;
18069 FValIsFalse = false;
18071 // Quit if TVal is not the constant opposite of FVal.
18072 if (FValIsFalse && TVal->getZExtValue() != 1)
18074 if (!FValIsFalse && TVal->getZExtValue() != 0)
18076 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
18077 if (needOppositeCond)
18078 CC = X86::GetOppositeBranchCondition(CC);
18079 return SetCC.getOperand(3);
18086 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
18087 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
18088 TargetLowering::DAGCombinerInfo &DCI,
18089 const X86Subtarget *Subtarget) {
18092 // If the flag operand isn't dead, don't touch this CMOV.
18093 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
18096 SDValue FalseOp = N->getOperand(0);
18097 SDValue TrueOp = N->getOperand(1);
18098 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
18099 SDValue Cond = N->getOperand(3);
18101 if (CC == X86::COND_E || CC == X86::COND_NE) {
18102 switch (Cond.getOpcode()) {
18106 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
18107 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
18108 return (CC == X86::COND_E) ? FalseOp : TrueOp;
18114 Flags = checkBoolTestSetCCCombine(Cond, CC);
18115 if (Flags.getNode() &&
18116 // Extra check as FCMOV only supports a subset of X86 cond.
18117 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
18118 SDValue Ops[] = { FalseOp, TrueOp,
18119 DAG.getConstant(CC, MVT::i8), Flags };
18120 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
18121 Ops, array_lengthof(Ops));
18124 // If this is a select between two integer constants, try to do some
18125 // optimizations. Note that the operands are ordered the opposite of SELECT
18127 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
18128 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
18129 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
18130 // larger than FalseC (the false value).
18131 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
18132 CC = X86::GetOppositeBranchCondition(CC);
18133 std::swap(TrueC, FalseC);
18134 std::swap(TrueOp, FalseOp);
18137 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
18138 // This is efficient for any integer data type (including i8/i16) and
18140 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
18141 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18142 DAG.getConstant(CC, MVT::i8), Cond);
18144 // Zero extend the condition if needed.
18145 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
18147 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18148 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
18149 DAG.getConstant(ShAmt, MVT::i8));
18150 if (N->getNumValues() == 2) // Dead flag value?
18151 return DCI.CombineTo(N, Cond, SDValue());
18155 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
18156 // for any integer data type, including i8/i16.
18157 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18158 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18159 DAG.getConstant(CC, MVT::i8), Cond);
18161 // Zero extend the condition if needed.
18162 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18163 FalseC->getValueType(0), Cond);
18164 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18165 SDValue(FalseC, 0));
18167 if (N->getNumValues() == 2) // Dead flag value?
18168 return DCI.CombineTo(N, Cond, SDValue());
18172 // Optimize cases that will turn into an LEA instruction. This requires
18173 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18174 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18175 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18176 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18178 bool isFastMultiplier = false;
18180 switch ((unsigned char)Diff) {
18182 case 1: // result = add base, cond
18183 case 2: // result = lea base( , cond*2)
18184 case 3: // result = lea base(cond, cond*2)
18185 case 4: // result = lea base( , cond*4)
18186 case 5: // result = lea base(cond, cond*4)
18187 case 8: // result = lea base( , cond*8)
18188 case 9: // result = lea base(cond, cond*8)
18189 isFastMultiplier = true;
18194 if (isFastMultiplier) {
18195 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18196 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18197 DAG.getConstant(CC, MVT::i8), Cond);
18198 // Zero extend the condition if needed.
18199 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18201 // Scale the condition by the difference.
18203 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18204 DAG.getConstant(Diff, Cond.getValueType()));
18206 // Add the base if non-zero.
18207 if (FalseC->getAPIntValue() != 0)
18208 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18209 SDValue(FalseC, 0));
18210 if (N->getNumValues() == 2) // Dead flag value?
18211 return DCI.CombineTo(N, Cond, SDValue());
18218 // Handle these cases:
18219 // (select (x != c), e, c) -> select (x != c), e, x),
18220 // (select (x == c), c, e) -> select (x == c), x, e)
18221 // where the c is an integer constant, and the "select" is the combination
18222 // of CMOV and CMP.
18224 // The rationale for this change is that the conditional-move from a constant
18225 // needs two instructions, however, conditional-move from a register needs
18226 // only one instruction.
18228 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
18229 // some instruction-combining opportunities. This opt needs to be
18230 // postponed as late as possible.
18232 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
18233 // the DCI.xxxx conditions are provided to postpone the optimization as
18234 // late as possible.
18236 ConstantSDNode *CmpAgainst = nullptr;
18237 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
18238 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
18239 !isa<ConstantSDNode>(Cond.getOperand(0))) {
18241 if (CC == X86::COND_NE &&
18242 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
18243 CC = X86::GetOppositeBranchCondition(CC);
18244 std::swap(TrueOp, FalseOp);
18247 if (CC == X86::COND_E &&
18248 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
18249 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
18250 DAG.getConstant(CC, MVT::i8), Cond };
18251 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
18252 array_lengthof(Ops));
18260 /// PerformMulCombine - Optimize a single multiply with constant into two
18261 /// in order to implement it with two cheaper instructions, e.g.
18262 /// LEA + SHL, LEA + LEA.
18263 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
18264 TargetLowering::DAGCombinerInfo &DCI) {
18265 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
18268 EVT VT = N->getValueType(0);
18269 if (VT != MVT::i64)
18272 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
18275 uint64_t MulAmt = C->getZExtValue();
18276 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
18279 uint64_t MulAmt1 = 0;
18280 uint64_t MulAmt2 = 0;
18281 if ((MulAmt % 9) == 0) {
18283 MulAmt2 = MulAmt / 9;
18284 } else if ((MulAmt % 5) == 0) {
18286 MulAmt2 = MulAmt / 5;
18287 } else if ((MulAmt % 3) == 0) {
18289 MulAmt2 = MulAmt / 3;
18292 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
18295 if (isPowerOf2_64(MulAmt2) &&
18296 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
18297 // If second multiplifer is pow2, issue it first. We want the multiply by
18298 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
18300 std::swap(MulAmt1, MulAmt2);
18303 if (isPowerOf2_64(MulAmt1))
18304 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
18305 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
18307 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
18308 DAG.getConstant(MulAmt1, VT));
18310 if (isPowerOf2_64(MulAmt2))
18311 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
18312 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
18314 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
18315 DAG.getConstant(MulAmt2, VT));
18317 // Do not add new nodes to DAG combiner worklist.
18318 DCI.CombineTo(N, NewMul, false);
18323 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
18324 SDValue N0 = N->getOperand(0);
18325 SDValue N1 = N->getOperand(1);
18326 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
18327 EVT VT = N0.getValueType();
18329 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
18330 // since the result of setcc_c is all zero's or all ones.
18331 if (VT.isInteger() && !VT.isVector() &&
18332 N1C && N0.getOpcode() == ISD::AND &&
18333 N0.getOperand(1).getOpcode() == ISD::Constant) {
18334 SDValue N00 = N0.getOperand(0);
18335 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
18336 ((N00.getOpcode() == ISD::ANY_EXTEND ||
18337 N00.getOpcode() == ISD::ZERO_EXTEND) &&
18338 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
18339 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
18340 APInt ShAmt = N1C->getAPIntValue();
18341 Mask = Mask.shl(ShAmt);
18343 return DAG.getNode(ISD::AND, SDLoc(N), VT,
18344 N00, DAG.getConstant(Mask, VT));
18348 // Hardware support for vector shifts is sparse which makes us scalarize the
18349 // vector operations in many cases. Also, on sandybridge ADD is faster than
18351 // (shl V, 1) -> add V,V
18352 if (isSplatVector(N1.getNode())) {
18353 assert(N0.getValueType().isVector() && "Invalid vector shift type");
18354 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
18355 // We shift all of the values by one. In many cases we do not have
18356 // hardware support for this operation. This is better expressed as an ADD
18358 if (N1C && (1 == N1C->getZExtValue())) {
18359 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
18366 /// \brief Returns a vector of 0s if the node in input is a vector logical
18367 /// shift by a constant amount which is known to be bigger than or equal
18368 /// to the vector element size in bits.
18369 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
18370 const X86Subtarget *Subtarget) {
18371 EVT VT = N->getValueType(0);
18373 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
18374 (!Subtarget->hasInt256() ||
18375 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
18378 SDValue Amt = N->getOperand(1);
18380 if (isSplatVector(Amt.getNode())) {
18381 SDValue SclrAmt = Amt->getOperand(0);
18382 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
18383 APInt ShiftAmt = C->getAPIntValue();
18384 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
18386 // SSE2/AVX2 logical shifts always return a vector of 0s
18387 // if the shift amount is bigger than or equal to
18388 // the element size. The constant shift amount will be
18389 // encoded as a 8-bit immediate.
18390 if (ShiftAmt.trunc(8).uge(MaxAmount))
18391 return getZeroVector(VT, Subtarget, DAG, DL);
18398 /// PerformShiftCombine - Combine shifts.
18399 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
18400 TargetLowering::DAGCombinerInfo &DCI,
18401 const X86Subtarget *Subtarget) {
18402 if (N->getOpcode() == ISD::SHL) {
18403 SDValue V = PerformSHLCombine(N, DAG);
18404 if (V.getNode()) return V;
18407 if (N->getOpcode() != ISD::SRA) {
18408 // Try to fold this logical shift into a zero vector.
18409 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
18410 if (V.getNode()) return V;
18416 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
18417 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
18418 // and friends. Likewise for OR -> CMPNEQSS.
18419 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
18420 TargetLowering::DAGCombinerInfo &DCI,
18421 const X86Subtarget *Subtarget) {
18424 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
18425 // we're requiring SSE2 for both.
18426 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
18427 SDValue N0 = N->getOperand(0);
18428 SDValue N1 = N->getOperand(1);
18429 SDValue CMP0 = N0->getOperand(1);
18430 SDValue CMP1 = N1->getOperand(1);
18433 // The SETCCs should both refer to the same CMP.
18434 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
18437 SDValue CMP00 = CMP0->getOperand(0);
18438 SDValue CMP01 = CMP0->getOperand(1);
18439 EVT VT = CMP00.getValueType();
18441 if (VT == MVT::f32 || VT == MVT::f64) {
18442 bool ExpectingFlags = false;
18443 // Check for any users that want flags:
18444 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
18445 !ExpectingFlags && UI != UE; ++UI)
18446 switch (UI->getOpcode()) {
18451 ExpectingFlags = true;
18453 case ISD::CopyToReg:
18454 case ISD::SIGN_EXTEND:
18455 case ISD::ZERO_EXTEND:
18456 case ISD::ANY_EXTEND:
18460 if (!ExpectingFlags) {
18461 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
18462 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
18464 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
18465 X86::CondCode tmp = cc0;
18470 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
18471 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
18472 // FIXME: need symbolic constants for these magic numbers.
18473 // See X86ATTInstPrinter.cpp:printSSECC().
18474 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
18475 if (Subtarget->hasAVX512()) {
18476 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
18477 CMP01, DAG.getConstant(x86cc, MVT::i8));
18478 if (N->getValueType(0) != MVT::i1)
18479 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
18483 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
18484 CMP00.getValueType(), CMP00, CMP01,
18485 DAG.getConstant(x86cc, MVT::i8));
18487 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
18488 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
18490 if (is64BitFP && !Subtarget->is64Bit()) {
18491 // On a 32-bit target, we cannot bitcast the 64-bit float to a
18492 // 64-bit integer, since that's not a legal type. Since
18493 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
18494 // bits, but can do this little dance to extract the lowest 32 bits
18495 // and work with those going forward.
18496 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
18498 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
18500 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
18501 Vector32, DAG.getIntPtrConstant(0));
18505 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
18506 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
18507 DAG.getConstant(1, IntVT));
18508 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
18509 return OneBitOfTruth;
18517 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
18518 /// so it can be folded inside ANDNP.
18519 static bool CanFoldXORWithAllOnes(const SDNode *N) {
18520 EVT VT = N->getValueType(0);
18522 // Match direct AllOnes for 128 and 256-bit vectors
18523 if (ISD::isBuildVectorAllOnes(N))
18526 // Look through a bit convert.
18527 if (N->getOpcode() == ISD::BITCAST)
18528 N = N->getOperand(0).getNode();
18530 // Sometimes the operand may come from a insert_subvector building a 256-bit
18532 if (VT.is256BitVector() &&
18533 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
18534 SDValue V1 = N->getOperand(0);
18535 SDValue V2 = N->getOperand(1);
18537 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
18538 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
18539 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
18540 ISD::isBuildVectorAllOnes(V2.getNode()))
18547 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
18548 // register. In most cases we actually compare or select YMM-sized registers
18549 // and mixing the two types creates horrible code. This method optimizes
18550 // some of the transition sequences.
18551 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
18552 TargetLowering::DAGCombinerInfo &DCI,
18553 const X86Subtarget *Subtarget) {
18554 EVT VT = N->getValueType(0);
18555 if (!VT.is256BitVector())
18558 assert((N->getOpcode() == ISD::ANY_EXTEND ||
18559 N->getOpcode() == ISD::ZERO_EXTEND ||
18560 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
18562 SDValue Narrow = N->getOperand(0);
18563 EVT NarrowVT = Narrow->getValueType(0);
18564 if (!NarrowVT.is128BitVector())
18567 if (Narrow->getOpcode() != ISD::XOR &&
18568 Narrow->getOpcode() != ISD::AND &&
18569 Narrow->getOpcode() != ISD::OR)
18572 SDValue N0 = Narrow->getOperand(0);
18573 SDValue N1 = Narrow->getOperand(1);
18576 // The Left side has to be a trunc.
18577 if (N0.getOpcode() != ISD::TRUNCATE)
18580 // The type of the truncated inputs.
18581 EVT WideVT = N0->getOperand(0)->getValueType(0);
18585 // The right side has to be a 'trunc' or a constant vector.
18586 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
18587 bool RHSConst = (isSplatVector(N1.getNode()) &&
18588 isa<ConstantSDNode>(N1->getOperand(0)));
18589 if (!RHSTrunc && !RHSConst)
18592 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18594 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
18597 // Set N0 and N1 to hold the inputs to the new wide operation.
18598 N0 = N0->getOperand(0);
18600 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
18601 N1->getOperand(0));
18602 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
18603 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
18604 } else if (RHSTrunc) {
18605 N1 = N1->getOperand(0);
18608 // Generate the wide operation.
18609 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
18610 unsigned Opcode = N->getOpcode();
18612 case ISD::ANY_EXTEND:
18614 case ISD::ZERO_EXTEND: {
18615 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
18616 APInt Mask = APInt::getAllOnesValue(InBits);
18617 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
18618 return DAG.getNode(ISD::AND, DL, VT,
18619 Op, DAG.getConstant(Mask, VT));
18621 case ISD::SIGN_EXTEND:
18622 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
18623 Op, DAG.getValueType(NarrowVT));
18625 llvm_unreachable("Unexpected opcode");
18629 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
18630 TargetLowering::DAGCombinerInfo &DCI,
18631 const X86Subtarget *Subtarget) {
18632 EVT VT = N->getValueType(0);
18633 if (DCI.isBeforeLegalizeOps())
18636 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18640 // Create BEXTR instructions
18641 // BEXTR is ((X >> imm) & (2**size-1))
18642 if (VT == MVT::i32 || VT == MVT::i64) {
18643 SDValue N0 = N->getOperand(0);
18644 SDValue N1 = N->getOperand(1);
18647 // Check for BEXTR.
18648 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
18649 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
18650 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
18651 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
18652 if (MaskNode && ShiftNode) {
18653 uint64_t Mask = MaskNode->getZExtValue();
18654 uint64_t Shift = ShiftNode->getZExtValue();
18655 if (isMask_64(Mask)) {
18656 uint64_t MaskSize = CountPopulation_64(Mask);
18657 if (Shift + MaskSize <= VT.getSizeInBits())
18658 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
18659 DAG.getConstant(Shift | (MaskSize << 8), VT));
18667 // Want to form ANDNP nodes:
18668 // 1) In the hopes of then easily combining them with OR and AND nodes
18669 // to form PBLEND/PSIGN.
18670 // 2) To match ANDN packed intrinsics
18671 if (VT != MVT::v2i64 && VT != MVT::v4i64)
18674 SDValue N0 = N->getOperand(0);
18675 SDValue N1 = N->getOperand(1);
18678 // Check LHS for vnot
18679 if (N0.getOpcode() == ISD::XOR &&
18680 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
18681 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
18682 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
18684 // Check RHS for vnot
18685 if (N1.getOpcode() == ISD::XOR &&
18686 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
18687 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
18688 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
18693 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
18694 TargetLowering::DAGCombinerInfo &DCI,
18695 const X86Subtarget *Subtarget) {
18696 if (DCI.isBeforeLegalizeOps())
18699 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18703 SDValue N0 = N->getOperand(0);
18704 SDValue N1 = N->getOperand(1);
18705 EVT VT = N->getValueType(0);
18707 // look for psign/blend
18708 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
18709 if (!Subtarget->hasSSSE3() ||
18710 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
18713 // Canonicalize pandn to RHS
18714 if (N0.getOpcode() == X86ISD::ANDNP)
18716 // or (and (m, y), (pandn m, x))
18717 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
18718 SDValue Mask = N1.getOperand(0);
18719 SDValue X = N1.getOperand(1);
18721 if (N0.getOperand(0) == Mask)
18722 Y = N0.getOperand(1);
18723 if (N0.getOperand(1) == Mask)
18724 Y = N0.getOperand(0);
18726 // Check to see if the mask appeared in both the AND and ANDNP and
18730 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
18731 // Look through mask bitcast.
18732 if (Mask.getOpcode() == ISD::BITCAST)
18733 Mask = Mask.getOperand(0);
18734 if (X.getOpcode() == ISD::BITCAST)
18735 X = X.getOperand(0);
18736 if (Y.getOpcode() == ISD::BITCAST)
18737 Y = Y.getOperand(0);
18739 EVT MaskVT = Mask.getValueType();
18741 // Validate that the Mask operand is a vector sra node.
18742 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
18743 // there is no psrai.b
18744 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
18745 unsigned SraAmt = ~0;
18746 if (Mask.getOpcode() == ISD::SRA) {
18747 SDValue Amt = Mask.getOperand(1);
18748 if (isSplatVector(Amt.getNode())) {
18749 SDValue SclrAmt = Amt->getOperand(0);
18750 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
18751 SraAmt = C->getZExtValue();
18753 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
18754 SDValue SraC = Mask.getOperand(1);
18755 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
18757 if ((SraAmt + 1) != EltBits)
18762 // Now we know we at least have a plendvb with the mask val. See if
18763 // we can form a psignb/w/d.
18764 // psign = x.type == y.type == mask.type && y = sub(0, x);
18765 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
18766 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
18767 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
18768 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
18769 "Unsupported VT for PSIGN");
18770 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
18771 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18773 // PBLENDVB only available on SSE 4.1
18774 if (!Subtarget->hasSSE41())
18777 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
18779 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
18780 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
18781 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
18782 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
18783 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18787 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
18790 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
18791 MachineFunction &MF = DAG.getMachineFunction();
18792 bool OptForSize = MF.getFunction()->getAttributes().
18793 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
18795 // SHLD/SHRD instructions have lower register pressure, but on some
18796 // platforms they have higher latency than the equivalent
18797 // series of shifts/or that would otherwise be generated.
18798 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
18799 // have higher latencies and we are not optimizing for size.
18800 if (!OptForSize && Subtarget->isSHLDSlow())
18803 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
18805 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
18807 if (!N0.hasOneUse() || !N1.hasOneUse())
18810 SDValue ShAmt0 = N0.getOperand(1);
18811 if (ShAmt0.getValueType() != MVT::i8)
18813 SDValue ShAmt1 = N1.getOperand(1);
18814 if (ShAmt1.getValueType() != MVT::i8)
18816 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
18817 ShAmt0 = ShAmt0.getOperand(0);
18818 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
18819 ShAmt1 = ShAmt1.getOperand(0);
18822 unsigned Opc = X86ISD::SHLD;
18823 SDValue Op0 = N0.getOperand(0);
18824 SDValue Op1 = N1.getOperand(0);
18825 if (ShAmt0.getOpcode() == ISD::SUB) {
18826 Opc = X86ISD::SHRD;
18827 std::swap(Op0, Op1);
18828 std::swap(ShAmt0, ShAmt1);
18831 unsigned Bits = VT.getSizeInBits();
18832 if (ShAmt1.getOpcode() == ISD::SUB) {
18833 SDValue Sum = ShAmt1.getOperand(0);
18834 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
18835 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
18836 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
18837 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
18838 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
18839 return DAG.getNode(Opc, DL, VT,
18841 DAG.getNode(ISD::TRUNCATE, DL,
18844 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
18845 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
18847 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
18848 return DAG.getNode(Opc, DL, VT,
18849 N0.getOperand(0), N1.getOperand(0),
18850 DAG.getNode(ISD::TRUNCATE, DL,
18857 // Generate NEG and CMOV for integer abs.
18858 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
18859 EVT VT = N->getValueType(0);
18861 // Since X86 does not have CMOV for 8-bit integer, we don't convert
18862 // 8-bit integer abs to NEG and CMOV.
18863 if (VT.isInteger() && VT.getSizeInBits() == 8)
18866 SDValue N0 = N->getOperand(0);
18867 SDValue N1 = N->getOperand(1);
18870 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
18871 // and change it to SUB and CMOV.
18872 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
18873 N0.getOpcode() == ISD::ADD &&
18874 N0.getOperand(1) == N1 &&
18875 N1.getOpcode() == ISD::SRA &&
18876 N1.getOperand(0) == N0.getOperand(0))
18877 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
18878 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
18879 // Generate SUB & CMOV.
18880 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
18881 DAG.getConstant(0, VT), N0.getOperand(0));
18883 SDValue Ops[] = { N0.getOperand(0), Neg,
18884 DAG.getConstant(X86::COND_GE, MVT::i8),
18885 SDValue(Neg.getNode(), 1) };
18886 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
18887 Ops, array_lengthof(Ops));
18892 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
18893 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
18894 TargetLowering::DAGCombinerInfo &DCI,
18895 const X86Subtarget *Subtarget) {
18896 if (DCI.isBeforeLegalizeOps())
18899 if (Subtarget->hasCMov()) {
18900 SDValue RV = performIntegerAbsCombine(N, DAG);
18908 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
18909 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
18910 TargetLowering::DAGCombinerInfo &DCI,
18911 const X86Subtarget *Subtarget) {
18912 LoadSDNode *Ld = cast<LoadSDNode>(N);
18913 EVT RegVT = Ld->getValueType(0);
18914 EVT MemVT = Ld->getMemoryVT();
18916 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18917 unsigned RegSz = RegVT.getSizeInBits();
18919 // On Sandybridge unaligned 256bit loads are inefficient.
18920 ISD::LoadExtType Ext = Ld->getExtensionType();
18921 unsigned Alignment = Ld->getAlignment();
18922 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
18923 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
18924 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
18925 unsigned NumElems = RegVT.getVectorNumElements();
18929 SDValue Ptr = Ld->getBasePtr();
18930 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
18932 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18934 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18935 Ld->getPointerInfo(), Ld->isVolatile(),
18936 Ld->isNonTemporal(), Ld->isInvariant(),
18938 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18939 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18940 Ld->getPointerInfo(), Ld->isVolatile(),
18941 Ld->isNonTemporal(), Ld->isInvariant(),
18942 std::min(16U, Alignment));
18943 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18945 Load2.getValue(1));
18947 SDValue NewVec = DAG.getUNDEF(RegVT);
18948 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
18949 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
18950 return DCI.CombineTo(N, NewVec, TF, true);
18953 // If this is a vector EXT Load then attempt to optimize it using a
18954 // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
18955 // expansion is still better than scalar code.
18956 // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
18957 // emit a shuffle and a arithmetic shift.
18958 // TODO: It is possible to support ZExt by zeroing the undef values
18959 // during the shuffle phase or after the shuffle.
18960 if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
18961 (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
18962 assert(MemVT != RegVT && "Cannot extend to the same type");
18963 assert(MemVT.isVector() && "Must load a vector from memory");
18965 unsigned NumElems = RegVT.getVectorNumElements();
18966 unsigned MemSz = MemVT.getSizeInBits();
18967 assert(RegSz > MemSz && "Register size must be greater than the mem size");
18969 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
18972 // All sizes must be a power of two.
18973 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
18976 // Attempt to load the original value using scalar loads.
18977 // Find the largest scalar type that divides the total loaded size.
18978 MVT SclrLoadTy = MVT::i8;
18979 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
18980 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
18981 MVT Tp = (MVT::SimpleValueType)tp;
18982 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
18987 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
18988 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
18990 SclrLoadTy = MVT::f64;
18992 // Calculate the number of scalar loads that we need to perform
18993 // in order to load our vector from memory.
18994 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
18995 if (Ext == ISD::SEXTLOAD && NumLoads > 1)
18998 unsigned loadRegZize = RegSz;
18999 if (Ext == ISD::SEXTLOAD && RegSz == 256)
19002 // Represent our vector as a sequence of elements which are the
19003 // largest scalar that we can load.
19004 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
19005 loadRegZize/SclrLoadTy.getSizeInBits());
19007 // Represent the data using the same element type that is stored in
19008 // memory. In practice, we ''widen'' MemVT.
19010 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19011 loadRegZize/MemVT.getScalarType().getSizeInBits());
19013 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
19014 "Invalid vector type");
19016 // We can't shuffle using an illegal type.
19017 if (!TLI.isTypeLegal(WideVecVT))
19020 SmallVector<SDValue, 8> Chains;
19021 SDValue Ptr = Ld->getBasePtr();
19022 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
19023 TLI.getPointerTy());
19024 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
19026 for (unsigned i = 0; i < NumLoads; ++i) {
19027 // Perform a single load.
19028 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
19029 Ptr, Ld->getPointerInfo(),
19030 Ld->isVolatile(), Ld->isNonTemporal(),
19031 Ld->isInvariant(), Ld->getAlignment());
19032 Chains.push_back(ScalarLoad.getValue(1));
19033 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
19034 // another round of DAGCombining.
19036 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
19038 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
19039 ScalarLoad, DAG.getIntPtrConstant(i));
19041 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19044 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
19047 // Bitcast the loaded value to a vector of the original element type, in
19048 // the size of the target vector type.
19049 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
19050 unsigned SizeRatio = RegSz/MemSz;
19052 if (Ext == ISD::SEXTLOAD) {
19053 // If we have SSE4.1 we can directly emit a VSEXT node.
19054 if (Subtarget->hasSSE41()) {
19055 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
19056 return DCI.CombineTo(N, Sext, TF, true);
19059 // Otherwise we'll shuffle the small elements in the high bits of the
19060 // larger type and perform an arithmetic shift. If the shift is not legal
19061 // it's better to scalarize.
19062 if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
19065 // Redistribute the loaded elements into the different locations.
19066 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19067 for (unsigned i = 0; i != NumElems; ++i)
19068 ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
19070 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19071 DAG.getUNDEF(WideVecVT),
19074 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19076 // Build the arithmetic shift.
19077 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
19078 MemVT.getVectorElementType().getSizeInBits();
19079 Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
19080 DAG.getConstant(Amt, RegVT));
19082 return DCI.CombineTo(N, Shuff, TF, true);
19085 // Redistribute the loaded elements into the different locations.
19086 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19087 for (unsigned i = 0; i != NumElems; ++i)
19088 ShuffleVec[i*SizeRatio] = i;
19090 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19091 DAG.getUNDEF(WideVecVT),
19094 // Bitcast to the requested type.
19095 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19096 // Replace the original load with the new sequence
19097 // and return the new chain.
19098 return DCI.CombineTo(N, Shuff, TF, true);
19104 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
19105 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
19106 const X86Subtarget *Subtarget) {
19107 StoreSDNode *St = cast<StoreSDNode>(N);
19108 EVT VT = St->getValue().getValueType();
19109 EVT StVT = St->getMemoryVT();
19111 SDValue StoredVal = St->getOperand(1);
19112 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19114 // If we are saving a concatenation of two XMM registers, perform two stores.
19115 // On Sandy Bridge, 256-bit memory operations are executed by two
19116 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
19117 // memory operation.
19118 unsigned Alignment = St->getAlignment();
19119 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
19120 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
19121 StVT == VT && !IsAligned) {
19122 unsigned NumElems = VT.getVectorNumElements();
19126 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
19127 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
19129 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
19130 SDValue Ptr0 = St->getBasePtr();
19131 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
19133 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
19134 St->getPointerInfo(), St->isVolatile(),
19135 St->isNonTemporal(), Alignment);
19136 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
19137 St->getPointerInfo(), St->isVolatile(),
19138 St->isNonTemporal(),
19139 std::min(16U, Alignment));
19140 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
19143 // Optimize trunc store (of multiple scalars) to shuffle and store.
19144 // First, pack all of the elements in one place. Next, store to memory
19145 // in fewer chunks.
19146 if (St->isTruncatingStore() && VT.isVector()) {
19147 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19148 unsigned NumElems = VT.getVectorNumElements();
19149 assert(StVT != VT && "Cannot truncate to the same type");
19150 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
19151 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
19153 // From, To sizes and ElemCount must be pow of two
19154 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
19155 // We are going to use the original vector elt for storing.
19156 // Accumulated smaller vector elements must be a multiple of the store size.
19157 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
19159 unsigned SizeRatio = FromSz / ToSz;
19161 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
19163 // Create a type on which we perform the shuffle
19164 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
19165 StVT.getScalarType(), NumElems*SizeRatio);
19167 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
19169 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
19170 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19171 for (unsigned i = 0; i != NumElems; ++i)
19172 ShuffleVec[i] = i * SizeRatio;
19174 // Can't shuffle using an illegal type.
19175 if (!TLI.isTypeLegal(WideVecVT))
19178 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
19179 DAG.getUNDEF(WideVecVT),
19181 // At this point all of the data is stored at the bottom of the
19182 // register. We now need to save it to mem.
19184 // Find the largest store unit
19185 MVT StoreType = MVT::i8;
19186 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19187 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19188 MVT Tp = (MVT::SimpleValueType)tp;
19189 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
19193 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19194 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
19195 (64 <= NumElems * ToSz))
19196 StoreType = MVT::f64;
19198 // Bitcast the original vector into a vector of store-size units
19199 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
19200 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
19201 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
19202 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
19203 SmallVector<SDValue, 8> Chains;
19204 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
19205 TLI.getPointerTy());
19206 SDValue Ptr = St->getBasePtr();
19208 // Perform one or more big stores into memory.
19209 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
19210 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
19211 StoreType, ShuffWide,
19212 DAG.getIntPtrConstant(i));
19213 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
19214 St->getPointerInfo(), St->isVolatile(),
19215 St->isNonTemporal(), St->getAlignment());
19216 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19217 Chains.push_back(Ch);
19220 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
19224 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
19225 // the FP state in cases where an emms may be missing.
19226 // A preferable solution to the general problem is to figure out the right
19227 // places to insert EMMS. This qualifies as a quick hack.
19229 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
19230 if (VT.getSizeInBits() != 64)
19233 const Function *F = DAG.getMachineFunction().getFunction();
19234 bool NoImplicitFloatOps = F->getAttributes().
19235 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
19236 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
19237 && Subtarget->hasSSE2();
19238 if ((VT.isVector() ||
19239 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
19240 isa<LoadSDNode>(St->getValue()) &&
19241 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
19242 St->getChain().hasOneUse() && !St->isVolatile()) {
19243 SDNode* LdVal = St->getValue().getNode();
19244 LoadSDNode *Ld = nullptr;
19245 int TokenFactorIndex = -1;
19246 SmallVector<SDValue, 8> Ops;
19247 SDNode* ChainVal = St->getChain().getNode();
19248 // Must be a store of a load. We currently handle two cases: the load
19249 // is a direct child, and it's under an intervening TokenFactor. It is
19250 // possible to dig deeper under nested TokenFactors.
19251 if (ChainVal == LdVal)
19252 Ld = cast<LoadSDNode>(St->getChain());
19253 else if (St->getValue().hasOneUse() &&
19254 ChainVal->getOpcode() == ISD::TokenFactor) {
19255 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
19256 if (ChainVal->getOperand(i).getNode() == LdVal) {
19257 TokenFactorIndex = i;
19258 Ld = cast<LoadSDNode>(St->getValue());
19260 Ops.push_back(ChainVal->getOperand(i));
19264 if (!Ld || !ISD::isNormalLoad(Ld))
19267 // If this is not the MMX case, i.e. we are just turning i64 load/store
19268 // into f64 load/store, avoid the transformation if there are multiple
19269 // uses of the loaded value.
19270 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
19275 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
19276 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
19278 if (Subtarget->is64Bit() || F64IsLegal) {
19279 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
19280 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
19281 Ld->getPointerInfo(), Ld->isVolatile(),
19282 Ld->isNonTemporal(), Ld->isInvariant(),
19283 Ld->getAlignment());
19284 SDValue NewChain = NewLd.getValue(1);
19285 if (TokenFactorIndex != -1) {
19286 Ops.push_back(NewChain);
19287 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
19290 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
19291 St->getPointerInfo(),
19292 St->isVolatile(), St->isNonTemporal(),
19293 St->getAlignment());
19296 // Otherwise, lower to two pairs of 32-bit loads / stores.
19297 SDValue LoAddr = Ld->getBasePtr();
19298 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
19299 DAG.getConstant(4, MVT::i32));
19301 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
19302 Ld->getPointerInfo(),
19303 Ld->isVolatile(), Ld->isNonTemporal(),
19304 Ld->isInvariant(), Ld->getAlignment());
19305 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
19306 Ld->getPointerInfo().getWithOffset(4),
19307 Ld->isVolatile(), Ld->isNonTemporal(),
19309 MinAlign(Ld->getAlignment(), 4));
19311 SDValue NewChain = LoLd.getValue(1);
19312 if (TokenFactorIndex != -1) {
19313 Ops.push_back(LoLd);
19314 Ops.push_back(HiLd);
19315 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
19319 LoAddr = St->getBasePtr();
19320 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
19321 DAG.getConstant(4, MVT::i32));
19323 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
19324 St->getPointerInfo(),
19325 St->isVolatile(), St->isNonTemporal(),
19326 St->getAlignment());
19327 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
19328 St->getPointerInfo().getWithOffset(4),
19330 St->isNonTemporal(),
19331 MinAlign(St->getAlignment(), 4));
19332 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
19337 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
19338 /// and return the operands for the horizontal operation in LHS and RHS. A
19339 /// horizontal operation performs the binary operation on successive elements
19340 /// of its first operand, then on successive elements of its second operand,
19341 /// returning the resulting values in a vector. For example, if
19342 /// A = < float a0, float a1, float a2, float a3 >
19344 /// B = < float b0, float b1, float b2, float b3 >
19345 /// then the result of doing a horizontal operation on A and B is
19346 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
19347 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
19348 /// A horizontal-op B, for some already available A and B, and if so then LHS is
19349 /// set to A, RHS to B, and the routine returns 'true'.
19350 /// Note that the binary operation should have the property that if one of the
19351 /// operands is UNDEF then the result is UNDEF.
19352 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
19353 // Look for the following pattern: if
19354 // A = < float a0, float a1, float a2, float a3 >
19355 // B = < float b0, float b1, float b2, float b3 >
19357 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
19358 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
19359 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
19360 // which is A horizontal-op B.
19362 // At least one of the operands should be a vector shuffle.
19363 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
19364 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
19367 MVT VT = LHS.getSimpleValueType();
19369 assert((VT.is128BitVector() || VT.is256BitVector()) &&
19370 "Unsupported vector type for horizontal add/sub");
19372 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
19373 // operate independently on 128-bit lanes.
19374 unsigned NumElts = VT.getVectorNumElements();
19375 unsigned NumLanes = VT.getSizeInBits()/128;
19376 unsigned NumLaneElts = NumElts / NumLanes;
19377 assert((NumLaneElts % 2 == 0) &&
19378 "Vector type should have an even number of elements in each lane");
19379 unsigned HalfLaneElts = NumLaneElts/2;
19381 // View LHS in the form
19382 // LHS = VECTOR_SHUFFLE A, B, LMask
19383 // If LHS is not a shuffle then pretend it is the shuffle
19384 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
19385 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
19388 SmallVector<int, 16> LMask(NumElts);
19389 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19390 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
19391 A = LHS.getOperand(0);
19392 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
19393 B = LHS.getOperand(1);
19394 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
19395 std::copy(Mask.begin(), Mask.end(), LMask.begin());
19397 if (LHS.getOpcode() != ISD::UNDEF)
19399 for (unsigned i = 0; i != NumElts; ++i)
19403 // Likewise, view RHS in the form
19404 // RHS = VECTOR_SHUFFLE C, D, RMask
19406 SmallVector<int, 16> RMask(NumElts);
19407 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19408 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
19409 C = RHS.getOperand(0);
19410 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
19411 D = RHS.getOperand(1);
19412 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
19413 std::copy(Mask.begin(), Mask.end(), RMask.begin());
19415 if (RHS.getOpcode() != ISD::UNDEF)
19417 for (unsigned i = 0; i != NumElts; ++i)
19421 // Check that the shuffles are both shuffling the same vectors.
19422 if (!(A == C && B == D) && !(A == D && B == C))
19425 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
19426 if (!A.getNode() && !B.getNode())
19429 // If A and B occur in reverse order in RHS, then "swap" them (which means
19430 // rewriting the mask).
19432 CommuteVectorShuffleMask(RMask, NumElts);
19434 // At this point LHS and RHS are equivalent to
19435 // LHS = VECTOR_SHUFFLE A, B, LMask
19436 // RHS = VECTOR_SHUFFLE A, B, RMask
19437 // Check that the masks correspond to performing a horizontal operation.
19438 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
19439 for (unsigned i = 0; i != NumLaneElts; ++i) {
19440 int LIdx = LMask[i+l], RIdx = RMask[i+l];
19442 // Ignore any UNDEF components.
19443 if (LIdx < 0 || RIdx < 0 ||
19444 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
19445 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
19448 // Check that successive elements are being operated on. If not, this is
19449 // not a horizontal operation.
19450 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
19451 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
19452 if (!(LIdx == Index && RIdx == Index + 1) &&
19453 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
19458 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
19459 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
19463 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
19464 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
19465 const X86Subtarget *Subtarget) {
19466 EVT VT = N->getValueType(0);
19467 SDValue LHS = N->getOperand(0);
19468 SDValue RHS = N->getOperand(1);
19470 // Try to synthesize horizontal adds from adds of shuffles.
19471 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19472 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19473 isHorizontalBinOp(LHS, RHS, true))
19474 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
19478 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
19479 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
19480 const X86Subtarget *Subtarget) {
19481 EVT VT = N->getValueType(0);
19482 SDValue LHS = N->getOperand(0);
19483 SDValue RHS = N->getOperand(1);
19485 // Try to synthesize horizontal subs from subs of shuffles.
19486 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19487 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19488 isHorizontalBinOp(LHS, RHS, false))
19489 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
19493 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
19494 /// X86ISD::FXOR nodes.
19495 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
19496 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
19497 // F[X]OR(0.0, x) -> x
19498 // F[X]OR(x, 0.0) -> x
19499 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19500 if (C->getValueAPF().isPosZero())
19501 return N->getOperand(1);
19502 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19503 if (C->getValueAPF().isPosZero())
19504 return N->getOperand(0);
19508 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
19509 /// X86ISD::FMAX nodes.
19510 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
19511 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
19513 // Only perform optimizations if UnsafeMath is used.
19514 if (!DAG.getTarget().Options.UnsafeFPMath)
19517 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
19518 // into FMINC and FMAXC, which are Commutative operations.
19519 unsigned NewOp = 0;
19520 switch (N->getOpcode()) {
19521 default: llvm_unreachable("unknown opcode");
19522 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
19523 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
19526 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
19527 N->getOperand(0), N->getOperand(1));
19530 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
19531 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
19532 // FAND(0.0, x) -> 0.0
19533 // FAND(x, 0.0) -> 0.0
19534 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19535 if (C->getValueAPF().isPosZero())
19536 return N->getOperand(0);
19537 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19538 if (C->getValueAPF().isPosZero())
19539 return N->getOperand(1);
19543 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
19544 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
19545 // FANDN(x, 0.0) -> 0.0
19546 // FANDN(0.0, x) -> x
19547 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19548 if (C->getValueAPF().isPosZero())
19549 return N->getOperand(1);
19550 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19551 if (C->getValueAPF().isPosZero())
19552 return N->getOperand(1);
19556 static SDValue PerformBTCombine(SDNode *N,
19558 TargetLowering::DAGCombinerInfo &DCI) {
19559 // BT ignores high bits in the bit index operand.
19560 SDValue Op1 = N->getOperand(1);
19561 if (Op1.hasOneUse()) {
19562 unsigned BitWidth = Op1.getValueSizeInBits();
19563 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
19564 APInt KnownZero, KnownOne;
19565 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
19566 !DCI.isBeforeLegalizeOps());
19567 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19568 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
19569 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
19570 DCI.CommitTargetLoweringOpt(TLO);
19575 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
19576 SDValue Op = N->getOperand(0);
19577 if (Op.getOpcode() == ISD::BITCAST)
19578 Op = Op.getOperand(0);
19579 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
19580 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
19581 VT.getVectorElementType().getSizeInBits() ==
19582 OpVT.getVectorElementType().getSizeInBits()) {
19583 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
19588 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
19589 const X86Subtarget *Subtarget) {
19590 EVT VT = N->getValueType(0);
19591 if (!VT.isVector())
19594 SDValue N0 = N->getOperand(0);
19595 SDValue N1 = N->getOperand(1);
19596 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
19599 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
19600 // both SSE and AVX2 since there is no sign-extended shift right
19601 // operation on a vector with 64-bit elements.
19602 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
19603 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
19604 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
19605 N0.getOpcode() == ISD::SIGN_EXTEND)) {
19606 SDValue N00 = N0.getOperand(0);
19608 // EXTLOAD has a better solution on AVX2,
19609 // it may be replaced with X86ISD::VSEXT node.
19610 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
19611 if (!ISD::isNormalLoad(N00.getNode()))
19614 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
19615 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
19617 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
19623 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
19624 TargetLowering::DAGCombinerInfo &DCI,
19625 const X86Subtarget *Subtarget) {
19626 if (!DCI.isBeforeLegalizeOps())
19629 if (!Subtarget->hasFp256())
19632 EVT VT = N->getValueType(0);
19633 if (VT.isVector() && VT.getSizeInBits() == 256) {
19634 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19642 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
19643 const X86Subtarget* Subtarget) {
19645 EVT VT = N->getValueType(0);
19647 // Let legalize expand this if it isn't a legal type yet.
19648 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19651 EVT ScalarVT = VT.getScalarType();
19652 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
19653 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
19656 SDValue A = N->getOperand(0);
19657 SDValue B = N->getOperand(1);
19658 SDValue C = N->getOperand(2);
19660 bool NegA = (A.getOpcode() == ISD::FNEG);
19661 bool NegB = (B.getOpcode() == ISD::FNEG);
19662 bool NegC = (C.getOpcode() == ISD::FNEG);
19664 // Negative multiplication when NegA xor NegB
19665 bool NegMul = (NegA != NegB);
19667 A = A.getOperand(0);
19669 B = B.getOperand(0);
19671 C = C.getOperand(0);
19675 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
19677 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
19679 return DAG.getNode(Opcode, dl, VT, A, B, C);
19682 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
19683 TargetLowering::DAGCombinerInfo &DCI,
19684 const X86Subtarget *Subtarget) {
19685 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
19686 // (and (i32 x86isd::setcc_carry), 1)
19687 // This eliminates the zext. This transformation is necessary because
19688 // ISD::SETCC is always legalized to i8.
19690 SDValue N0 = N->getOperand(0);
19691 EVT VT = N->getValueType(0);
19693 if (N0.getOpcode() == ISD::AND &&
19695 N0.getOperand(0).hasOneUse()) {
19696 SDValue N00 = N0.getOperand(0);
19697 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19698 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19699 if (!C || C->getZExtValue() != 1)
19701 return DAG.getNode(ISD::AND, dl, VT,
19702 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19703 N00.getOperand(0), N00.getOperand(1)),
19704 DAG.getConstant(1, VT));
19708 if (N0.getOpcode() == ISD::TRUNCATE &&
19710 N0.getOperand(0).hasOneUse()) {
19711 SDValue N00 = N0.getOperand(0);
19712 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19713 return DAG.getNode(ISD::AND, dl, VT,
19714 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19715 N00.getOperand(0), N00.getOperand(1)),
19716 DAG.getConstant(1, VT));
19719 if (VT.is256BitVector()) {
19720 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19728 // Optimize x == -y --> x+y == 0
19729 // x != -y --> x+y != 0
19730 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
19731 const X86Subtarget* Subtarget) {
19732 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
19733 SDValue LHS = N->getOperand(0);
19734 SDValue RHS = N->getOperand(1);
19735 EVT VT = N->getValueType(0);
19738 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
19739 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
19740 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
19741 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19742 LHS.getValueType(), RHS, LHS.getOperand(1));
19743 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19744 addV, DAG.getConstant(0, addV.getValueType()), CC);
19746 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
19747 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
19748 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
19749 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19750 RHS.getValueType(), LHS, RHS.getOperand(1));
19751 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19752 addV, DAG.getConstant(0, addV.getValueType()), CC);
19755 if (VT.getScalarType() == MVT::i1) {
19756 bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
19757 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
19758 bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
19759 if (!IsSEXT0 && !IsVZero0)
19761 bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
19762 (RHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
19763 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
19765 if (!IsSEXT1 && !IsVZero1)
19768 if (IsSEXT0 && IsVZero1) {
19769 assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
19770 if (CC == ISD::SETEQ)
19771 return DAG.getNOT(DL, LHS.getOperand(0), VT);
19772 return LHS.getOperand(0);
19774 if (IsSEXT1 && IsVZero0) {
19775 assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
19776 if (CC == ISD::SETEQ)
19777 return DAG.getNOT(DL, RHS.getOperand(0), VT);
19778 return RHS.getOperand(0);
19785 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
19786 // as "sbb reg,reg", since it can be extended without zext and produces
19787 // an all-ones bit which is more useful than 0/1 in some cases.
19788 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
19791 return DAG.getNode(ISD::AND, DL, VT,
19792 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19793 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
19794 DAG.getConstant(1, VT));
19795 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
19796 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
19797 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19798 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
19801 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
19802 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
19803 TargetLowering::DAGCombinerInfo &DCI,
19804 const X86Subtarget *Subtarget) {
19806 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
19807 SDValue EFLAGS = N->getOperand(1);
19809 if (CC == X86::COND_A) {
19810 // Try to convert COND_A into COND_B in an attempt to facilitate
19811 // materializing "setb reg".
19813 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
19814 // cannot take an immediate as its first operand.
19816 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
19817 EFLAGS.getValueType().isInteger() &&
19818 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
19819 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
19820 EFLAGS.getNode()->getVTList(),
19821 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
19822 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
19823 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
19827 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
19828 // a zext and produces an all-ones bit which is more useful than 0/1 in some
19830 if (CC == X86::COND_B)
19831 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
19835 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19836 if (Flags.getNode()) {
19837 SDValue Cond = DAG.getConstant(CC, MVT::i8);
19838 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
19844 // Optimize branch condition evaluation.
19846 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
19847 TargetLowering::DAGCombinerInfo &DCI,
19848 const X86Subtarget *Subtarget) {
19850 SDValue Chain = N->getOperand(0);
19851 SDValue Dest = N->getOperand(1);
19852 SDValue EFLAGS = N->getOperand(3);
19853 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
19857 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19858 if (Flags.getNode()) {
19859 SDValue Cond = DAG.getConstant(CC, MVT::i8);
19860 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
19867 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
19868 const X86TargetLowering *XTLI) {
19869 SDValue Op0 = N->getOperand(0);
19870 EVT InVT = Op0->getValueType(0);
19872 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
19873 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
19875 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
19876 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
19877 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
19880 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
19881 // a 32-bit target where SSE doesn't support i64->FP operations.
19882 if (Op0.getOpcode() == ISD::LOAD) {
19883 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
19884 EVT VT = Ld->getValueType(0);
19885 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
19886 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
19887 !XTLI->getSubtarget()->is64Bit() &&
19889 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
19890 Ld->getChain(), Op0, DAG);
19891 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
19898 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
19899 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
19900 X86TargetLowering::DAGCombinerInfo &DCI) {
19901 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
19902 // the result is either zero or one (depending on the input carry bit).
19903 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
19904 if (X86::isZeroNode(N->getOperand(0)) &&
19905 X86::isZeroNode(N->getOperand(1)) &&
19906 // We don't have a good way to replace an EFLAGS use, so only do this when
19908 SDValue(N, 1).use_empty()) {
19910 EVT VT = N->getValueType(0);
19911 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
19912 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
19913 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
19914 DAG.getConstant(X86::COND_B,MVT::i8),
19916 DAG.getConstant(1, VT));
19917 return DCI.CombineTo(N, Res1, CarryOut);
19923 // fold (add Y, (sete X, 0)) -> adc 0, Y
19924 // (add Y, (setne X, 0)) -> sbb -1, Y
19925 // (sub (sete X, 0), Y) -> sbb 0, Y
19926 // (sub (setne X, 0), Y) -> adc -1, Y
19927 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
19930 // Look through ZExts.
19931 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
19932 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
19935 SDValue SetCC = Ext.getOperand(0);
19936 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
19939 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
19940 if (CC != X86::COND_E && CC != X86::COND_NE)
19943 SDValue Cmp = SetCC.getOperand(1);
19944 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
19945 !X86::isZeroNode(Cmp.getOperand(1)) ||
19946 !Cmp.getOperand(0).getValueType().isInteger())
19949 SDValue CmpOp0 = Cmp.getOperand(0);
19950 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
19951 DAG.getConstant(1, CmpOp0.getValueType()));
19953 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
19954 if (CC == X86::COND_NE)
19955 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
19956 DL, OtherVal.getValueType(), OtherVal,
19957 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
19958 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
19959 DL, OtherVal.getValueType(), OtherVal,
19960 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
19963 /// PerformADDCombine - Do target-specific dag combines on integer adds.
19964 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
19965 const X86Subtarget *Subtarget) {
19966 EVT VT = N->getValueType(0);
19967 SDValue Op0 = N->getOperand(0);
19968 SDValue Op1 = N->getOperand(1);
19970 // Try to synthesize horizontal adds from adds of shuffles.
19971 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19972 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19973 isHorizontalBinOp(Op0, Op1, true))
19974 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
19976 return OptimizeConditionalInDecrement(N, DAG);
19979 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
19980 const X86Subtarget *Subtarget) {
19981 SDValue Op0 = N->getOperand(0);
19982 SDValue Op1 = N->getOperand(1);
19984 // X86 can't encode an immediate LHS of a sub. See if we can push the
19985 // negation into a preceding instruction.
19986 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
19987 // If the RHS of the sub is a XOR with one use and a constant, invert the
19988 // immediate. Then add one to the LHS of the sub so we can turn
19989 // X-Y -> X+~Y+1, saving one register.
19990 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
19991 isa<ConstantSDNode>(Op1.getOperand(1))) {
19992 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
19993 EVT VT = Op0.getValueType();
19994 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
19996 DAG.getConstant(~XorC, VT));
19997 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
19998 DAG.getConstant(C->getAPIntValue()+1, VT));
20002 // Try to synthesize horizontal adds from adds of shuffles.
20003 EVT VT = N->getValueType(0);
20004 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20005 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20006 isHorizontalBinOp(Op0, Op1, true))
20007 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
20009 return OptimizeConditionalInDecrement(N, DAG);
20012 /// performVZEXTCombine - Performs build vector combines
20013 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
20014 TargetLowering::DAGCombinerInfo &DCI,
20015 const X86Subtarget *Subtarget) {
20016 // (vzext (bitcast (vzext (x)) -> (vzext x)
20017 SDValue In = N->getOperand(0);
20018 while (In.getOpcode() == ISD::BITCAST)
20019 In = In.getOperand(0);
20021 if (In.getOpcode() != X86ISD::VZEXT)
20024 return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
20028 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
20029 DAGCombinerInfo &DCI) const {
20030 SelectionDAG &DAG = DCI.DAG;
20031 switch (N->getOpcode()) {
20033 case ISD::EXTRACT_VECTOR_ELT:
20034 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
20036 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
20037 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
20038 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
20039 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
20040 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
20041 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
20044 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
20045 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
20046 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
20047 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
20048 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
20049 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
20050 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
20051 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
20052 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
20054 case X86ISD::FOR: return PerformFORCombine(N, DAG);
20056 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
20057 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
20058 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
20059 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
20060 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
20061 case ISD::ANY_EXTEND:
20062 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
20063 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
20064 case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
20065 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
20066 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
20067 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
20068 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
20069 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
20070 case X86ISD::SHUFP: // Handle all target specific shuffles
20071 case X86ISD::PALIGNR:
20072 case X86ISD::UNPCKH:
20073 case X86ISD::UNPCKL:
20074 case X86ISD::MOVHLPS:
20075 case X86ISD::MOVLHPS:
20076 case X86ISD::PSHUFD:
20077 case X86ISD::PSHUFHW:
20078 case X86ISD::PSHUFLW:
20079 case X86ISD::MOVSS:
20080 case X86ISD::MOVSD:
20081 case X86ISD::VPERMILP:
20082 case X86ISD::VPERM2X128:
20083 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
20084 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
20090 /// isTypeDesirableForOp - Return true if the target has native support for
20091 /// the specified value type and it is 'desirable' to use the type for the
20092 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
20093 /// instruction encodings are longer and some i16 instructions are slow.
20094 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
20095 if (!isTypeLegal(VT))
20097 if (VT != MVT::i16)
20104 case ISD::SIGN_EXTEND:
20105 case ISD::ZERO_EXTEND:
20106 case ISD::ANY_EXTEND:
20119 /// IsDesirableToPromoteOp - This method query the target whether it is
20120 /// beneficial for dag combiner to promote the specified node. If true, it
20121 /// should return the desired promotion type by reference.
20122 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
20123 EVT VT = Op.getValueType();
20124 if (VT != MVT::i16)
20127 bool Promote = false;
20128 bool Commute = false;
20129 switch (Op.getOpcode()) {
20132 LoadSDNode *LD = cast<LoadSDNode>(Op);
20133 // If the non-extending load has a single use and it's not live out, then it
20134 // might be folded.
20135 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
20136 Op.hasOneUse()*/) {
20137 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
20138 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
20139 // The only case where we'd want to promote LOAD (rather then it being
20140 // promoted as an operand is when it's only use is liveout.
20141 if (UI->getOpcode() != ISD::CopyToReg)
20148 case ISD::SIGN_EXTEND:
20149 case ISD::ZERO_EXTEND:
20150 case ISD::ANY_EXTEND:
20155 SDValue N0 = Op.getOperand(0);
20156 // Look out for (store (shl (load), x)).
20157 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
20170 SDValue N0 = Op.getOperand(0);
20171 SDValue N1 = Op.getOperand(1);
20172 if (!Commute && MayFoldLoad(N1))
20174 // Avoid disabling potential load folding opportunities.
20175 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
20177 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
20187 //===----------------------------------------------------------------------===//
20188 // X86 Inline Assembly Support
20189 //===----------------------------------------------------------------------===//
20192 // Helper to match a string separated by whitespace.
20193 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
20194 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
20196 for (unsigned i = 0, e = args.size(); i != e; ++i) {
20197 StringRef piece(*args[i]);
20198 if (!s.startswith(piece)) // Check if the piece matches.
20201 s = s.substr(piece.size());
20202 StringRef::size_type pos = s.find_first_not_of(" \t");
20203 if (pos == 0) // We matched a prefix.
20211 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
20214 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
20216 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
20217 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
20218 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
20219 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
20221 if (AsmPieces.size() == 3)
20223 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
20230 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
20231 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
20233 std::string AsmStr = IA->getAsmString();
20235 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
20236 if (!Ty || Ty->getBitWidth() % 16 != 0)
20239 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
20240 SmallVector<StringRef, 4> AsmPieces;
20241 SplitString(AsmStr, AsmPieces, ";\n");
20243 switch (AsmPieces.size()) {
20244 default: return false;
20246 // FIXME: this should verify that we are targeting a 486 or better. If not,
20247 // we will turn this bswap into something that will be lowered to logical
20248 // ops instead of emitting the bswap asm. For now, we don't support 486 or
20249 // lower so don't worry about this.
20251 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
20252 matchAsm(AsmPieces[0], "bswapl", "$0") ||
20253 matchAsm(AsmPieces[0], "bswapq", "$0") ||
20254 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
20255 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
20256 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
20257 // No need to check constraints, nothing other than the equivalent of
20258 // "=r,0" would be valid here.
20259 return IntrinsicLowering::LowerToByteSwap(CI);
20262 // rorw $$8, ${0:w} --> llvm.bswap.i16
20263 if (CI->getType()->isIntegerTy(16) &&
20264 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20265 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
20266 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
20268 const std::string &ConstraintsStr = IA->getConstraintString();
20269 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20270 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20271 if (clobbersFlagRegisters(AsmPieces))
20272 return IntrinsicLowering::LowerToByteSwap(CI);
20276 if (CI->getType()->isIntegerTy(32) &&
20277 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20278 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
20279 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
20280 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
20282 const std::string &ConstraintsStr = IA->getConstraintString();
20283 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20284 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20285 if (clobbersFlagRegisters(AsmPieces))
20286 return IntrinsicLowering::LowerToByteSwap(CI);
20289 if (CI->getType()->isIntegerTy(64)) {
20290 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
20291 if (Constraints.size() >= 2 &&
20292 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
20293 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
20294 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
20295 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
20296 matchAsm(AsmPieces[1], "bswap", "%edx") &&
20297 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
20298 return IntrinsicLowering::LowerToByteSwap(CI);
20306 /// getConstraintType - Given a constraint letter, return the type of
20307 /// constraint it is for this target.
20308 X86TargetLowering::ConstraintType
20309 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
20310 if (Constraint.size() == 1) {
20311 switch (Constraint[0]) {
20322 return C_RegisterClass;
20346 return TargetLowering::getConstraintType(Constraint);
20349 /// Examine constraint type and operand type and determine a weight value.
20350 /// This object must already have been set up with the operand type
20351 /// and the current alternative constraint selected.
20352 TargetLowering::ConstraintWeight
20353 X86TargetLowering::getSingleConstraintMatchWeight(
20354 AsmOperandInfo &info, const char *constraint) const {
20355 ConstraintWeight weight = CW_Invalid;
20356 Value *CallOperandVal = info.CallOperandVal;
20357 // If we don't have a value, we can't do a match,
20358 // but allow it at the lowest weight.
20359 if (!CallOperandVal)
20361 Type *type = CallOperandVal->getType();
20362 // Look at the constraint type.
20363 switch (*constraint) {
20365 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
20376 if (CallOperandVal->getType()->isIntegerTy())
20377 weight = CW_SpecificReg;
20382 if (type->isFloatingPointTy())
20383 weight = CW_SpecificReg;
20386 if (type->isX86_MMXTy() && Subtarget->hasMMX())
20387 weight = CW_SpecificReg;
20391 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
20392 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
20393 weight = CW_Register;
20396 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
20397 if (C->getZExtValue() <= 31)
20398 weight = CW_Constant;
20402 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20403 if (C->getZExtValue() <= 63)
20404 weight = CW_Constant;
20408 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20409 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
20410 weight = CW_Constant;
20414 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20415 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
20416 weight = CW_Constant;
20420 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20421 if (C->getZExtValue() <= 3)
20422 weight = CW_Constant;
20426 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20427 if (C->getZExtValue() <= 0xff)
20428 weight = CW_Constant;
20433 if (dyn_cast<ConstantFP>(CallOperandVal)) {
20434 weight = CW_Constant;
20438 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20439 if ((C->getSExtValue() >= -0x80000000LL) &&
20440 (C->getSExtValue() <= 0x7fffffffLL))
20441 weight = CW_Constant;
20445 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20446 if (C->getZExtValue() <= 0xffffffff)
20447 weight = CW_Constant;
20454 /// LowerXConstraint - try to replace an X constraint, which matches anything,
20455 /// with another that has more specific requirements based on the type of the
20456 /// corresponding operand.
20457 const char *X86TargetLowering::
20458 LowerXConstraint(EVT ConstraintVT) const {
20459 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
20460 // 'f' like normal targets.
20461 if (ConstraintVT.isFloatingPoint()) {
20462 if (Subtarget->hasSSE2())
20464 if (Subtarget->hasSSE1())
20468 return TargetLowering::LowerXConstraint(ConstraintVT);
20471 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
20472 /// vector. If it is invalid, don't add anything to Ops.
20473 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
20474 std::string &Constraint,
20475 std::vector<SDValue>&Ops,
20476 SelectionDAG &DAG) const {
20479 // Only support length 1 constraints for now.
20480 if (Constraint.length() > 1) return;
20482 char ConstraintLetter = Constraint[0];
20483 switch (ConstraintLetter) {
20486 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20487 if (C->getZExtValue() <= 31) {
20488 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20494 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20495 if (C->getZExtValue() <= 63) {
20496 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20502 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20503 if (isInt<8>(C->getSExtValue())) {
20504 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20510 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20511 if (C->getZExtValue() <= 255) {
20512 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20518 // 32-bit signed value
20519 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20520 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20521 C->getSExtValue())) {
20522 // Widen to 64 bits here to get it sign extended.
20523 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
20526 // FIXME gcc accepts some relocatable values here too, but only in certain
20527 // memory models; it's complicated.
20532 // 32-bit unsigned value
20533 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20534 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20535 C->getZExtValue())) {
20536 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20540 // FIXME gcc accepts some relocatable values here too, but only in certain
20541 // memory models; it's complicated.
20545 // Literal immediates are always ok.
20546 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
20547 // Widen to 64 bits here to get it sign extended.
20548 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
20552 // In any sort of PIC mode addresses need to be computed at runtime by
20553 // adding in a register or some sort of table lookup. These can't
20554 // be used as immediates.
20555 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
20558 // If we are in non-pic codegen mode, we allow the address of a global (with
20559 // an optional displacement) to be used with 'i'.
20560 GlobalAddressSDNode *GA = nullptr;
20561 int64_t Offset = 0;
20563 // Match either (GA), (GA+C), (GA+C1+C2), etc.
20565 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
20566 Offset += GA->getOffset();
20568 } else if (Op.getOpcode() == ISD::ADD) {
20569 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20570 Offset += C->getZExtValue();
20571 Op = Op.getOperand(0);
20574 } else if (Op.getOpcode() == ISD::SUB) {
20575 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20576 Offset += -C->getZExtValue();
20577 Op = Op.getOperand(0);
20582 // Otherwise, this isn't something we can handle, reject it.
20586 const GlobalValue *GV = GA->getGlobal();
20587 // If we require an extra load to get this address, as in PIC mode, we
20588 // can't accept it.
20589 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
20590 getTargetMachine())))
20593 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
20594 GA->getValueType(0), Offset);
20599 if (Result.getNode()) {
20600 Ops.push_back(Result);
20603 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
20606 std::pair<unsigned, const TargetRegisterClass*>
20607 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
20609 // First, see if this is a constraint that directly corresponds to an LLVM
20611 if (Constraint.size() == 1) {
20612 // GCC Constraint Letters
20613 switch (Constraint[0]) {
20615 // TODO: Slight differences here in allocation order and leaving
20616 // RIP in the class. Do they matter any more here than they do
20617 // in the normal allocation?
20618 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
20619 if (Subtarget->is64Bit()) {
20620 if (VT == MVT::i32 || VT == MVT::f32)
20621 return std::make_pair(0U, &X86::GR32RegClass);
20622 if (VT == MVT::i16)
20623 return std::make_pair(0U, &X86::GR16RegClass);
20624 if (VT == MVT::i8 || VT == MVT::i1)
20625 return std::make_pair(0U, &X86::GR8RegClass);
20626 if (VT == MVT::i64 || VT == MVT::f64)
20627 return std::make_pair(0U, &X86::GR64RegClass);
20630 // 32-bit fallthrough
20631 case 'Q': // Q_REGS
20632 if (VT == MVT::i32 || VT == MVT::f32)
20633 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
20634 if (VT == MVT::i16)
20635 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
20636 if (VT == MVT::i8 || VT == MVT::i1)
20637 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
20638 if (VT == MVT::i64)
20639 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
20641 case 'r': // GENERAL_REGS
20642 case 'l': // INDEX_REGS
20643 if (VT == MVT::i8 || VT == MVT::i1)
20644 return std::make_pair(0U, &X86::GR8RegClass);
20645 if (VT == MVT::i16)
20646 return std::make_pair(0U, &X86::GR16RegClass);
20647 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
20648 return std::make_pair(0U, &X86::GR32RegClass);
20649 return std::make_pair(0U, &X86::GR64RegClass);
20650 case 'R': // LEGACY_REGS
20651 if (VT == MVT::i8 || VT == MVT::i1)
20652 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
20653 if (VT == MVT::i16)
20654 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
20655 if (VT == MVT::i32 || !Subtarget->is64Bit())
20656 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
20657 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
20658 case 'f': // FP Stack registers.
20659 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
20660 // value to the correct fpstack register class.
20661 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
20662 return std::make_pair(0U, &X86::RFP32RegClass);
20663 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
20664 return std::make_pair(0U, &X86::RFP64RegClass);
20665 return std::make_pair(0U, &X86::RFP80RegClass);
20666 case 'y': // MMX_REGS if MMX allowed.
20667 if (!Subtarget->hasMMX()) break;
20668 return std::make_pair(0U, &X86::VR64RegClass);
20669 case 'Y': // SSE_REGS if SSE2 allowed
20670 if (!Subtarget->hasSSE2()) break;
20672 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
20673 if (!Subtarget->hasSSE1()) break;
20675 switch (VT.SimpleTy) {
20677 // Scalar SSE types.
20680 return std::make_pair(0U, &X86::FR32RegClass);
20683 return std::make_pair(0U, &X86::FR64RegClass);
20691 return std::make_pair(0U, &X86::VR128RegClass);
20699 return std::make_pair(0U, &X86::VR256RegClass);
20704 return std::make_pair(0U, &X86::VR512RegClass);
20710 // Use the default implementation in TargetLowering to convert the register
20711 // constraint into a member of a register class.
20712 std::pair<unsigned, const TargetRegisterClass*> Res;
20713 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
20715 // Not found as a standard register?
20717 // Map st(0) -> st(7) -> ST0
20718 if (Constraint.size() == 7 && Constraint[0] == '{' &&
20719 tolower(Constraint[1]) == 's' &&
20720 tolower(Constraint[2]) == 't' &&
20721 Constraint[3] == '(' &&
20722 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
20723 Constraint[5] == ')' &&
20724 Constraint[6] == '}') {
20726 Res.first = X86::ST0+Constraint[4]-'0';
20727 Res.second = &X86::RFP80RegClass;
20731 // GCC allows "st(0)" to be called just plain "st".
20732 if (StringRef("{st}").equals_lower(Constraint)) {
20733 Res.first = X86::ST0;
20734 Res.second = &X86::RFP80RegClass;
20739 if (StringRef("{flags}").equals_lower(Constraint)) {
20740 Res.first = X86::EFLAGS;
20741 Res.second = &X86::CCRRegClass;
20745 // 'A' means EAX + EDX.
20746 if (Constraint == "A") {
20747 Res.first = X86::EAX;
20748 Res.second = &X86::GR32_ADRegClass;
20754 // Otherwise, check to see if this is a register class of the wrong value
20755 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
20756 // turn into {ax},{dx}.
20757 if (Res.second->hasType(VT))
20758 return Res; // Correct type already, nothing to do.
20760 // All of the single-register GCC register classes map their values onto
20761 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
20762 // really want an 8-bit or 32-bit register, map to the appropriate register
20763 // class and return the appropriate register.
20764 if (Res.second == &X86::GR16RegClass) {
20765 if (VT == MVT::i8 || VT == MVT::i1) {
20766 unsigned DestReg = 0;
20767 switch (Res.first) {
20769 case X86::AX: DestReg = X86::AL; break;
20770 case X86::DX: DestReg = X86::DL; break;
20771 case X86::CX: DestReg = X86::CL; break;
20772 case X86::BX: DestReg = X86::BL; break;
20775 Res.first = DestReg;
20776 Res.second = &X86::GR8RegClass;
20778 } else if (VT == MVT::i32 || VT == MVT::f32) {
20779 unsigned DestReg = 0;
20780 switch (Res.first) {
20782 case X86::AX: DestReg = X86::EAX; break;
20783 case X86::DX: DestReg = X86::EDX; break;
20784 case X86::CX: DestReg = X86::ECX; break;
20785 case X86::BX: DestReg = X86::EBX; break;
20786 case X86::SI: DestReg = X86::ESI; break;
20787 case X86::DI: DestReg = X86::EDI; break;
20788 case X86::BP: DestReg = X86::EBP; break;
20789 case X86::SP: DestReg = X86::ESP; break;
20792 Res.first = DestReg;
20793 Res.second = &X86::GR32RegClass;
20795 } else if (VT == MVT::i64 || VT == MVT::f64) {
20796 unsigned DestReg = 0;
20797 switch (Res.first) {
20799 case X86::AX: DestReg = X86::RAX; break;
20800 case X86::DX: DestReg = X86::RDX; break;
20801 case X86::CX: DestReg = X86::RCX; break;
20802 case X86::BX: DestReg = X86::RBX; break;
20803 case X86::SI: DestReg = X86::RSI; break;
20804 case X86::DI: DestReg = X86::RDI; break;
20805 case X86::BP: DestReg = X86::RBP; break;
20806 case X86::SP: DestReg = X86::RSP; break;
20809 Res.first = DestReg;
20810 Res.second = &X86::GR64RegClass;
20813 } else if (Res.second == &X86::FR32RegClass ||
20814 Res.second == &X86::FR64RegClass ||
20815 Res.second == &X86::VR128RegClass ||
20816 Res.second == &X86::VR256RegClass ||
20817 Res.second == &X86::FR32XRegClass ||
20818 Res.second == &X86::FR64XRegClass ||
20819 Res.second == &X86::VR128XRegClass ||
20820 Res.second == &X86::VR256XRegClass ||
20821 Res.second == &X86::VR512RegClass) {
20822 // Handle references to XMM physical registers that got mapped into the
20823 // wrong class. This can happen with constraints like {xmm0} where the
20824 // target independent register mapper will just pick the first match it can
20825 // find, ignoring the required type.
20827 if (VT == MVT::f32 || VT == MVT::i32)
20828 Res.second = &X86::FR32RegClass;
20829 else if (VT == MVT::f64 || VT == MVT::i64)
20830 Res.second = &X86::FR64RegClass;
20831 else if (X86::VR128RegClass.hasType(VT))
20832 Res.second = &X86::VR128RegClass;
20833 else if (X86::VR256RegClass.hasType(VT))
20834 Res.second = &X86::VR256RegClass;
20835 else if (X86::VR512RegClass.hasType(VT))
20836 Res.second = &X86::VR512RegClass;
20842 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
20844 // Scaling factors are not free at all.
20845 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
20846 // will take 2 allocations instead of 1 for plain addressing mode,
20847 // i.e. inst (reg1).
20848 if (isLegalAddressingMode(AM, Ty))
20849 // Scale represents reg2 * scale, thus account for 1
20850 // as soon as we use a second register.
20851 return AM.Scale != 0;