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::UMUL_LOHI, VT, Expand);
830 setOperationAction(ISD::SDIVREM, VT, Expand);
831 setOperationAction(ISD::UDIVREM, VT, Expand);
832 setOperationAction(ISD::FPOW, VT, Expand);
833 setOperationAction(ISD::CTPOP, VT, Expand);
834 setOperationAction(ISD::CTTZ, VT, Expand);
835 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
836 setOperationAction(ISD::CTLZ, VT, Expand);
837 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
838 setOperationAction(ISD::SHL, VT, Expand);
839 setOperationAction(ISD::SRA, VT, Expand);
840 setOperationAction(ISD::SRL, VT, Expand);
841 setOperationAction(ISD::ROTL, VT, Expand);
842 setOperationAction(ISD::ROTR, VT, Expand);
843 setOperationAction(ISD::BSWAP, VT, Expand);
844 setOperationAction(ISD::SETCC, VT, Expand);
845 setOperationAction(ISD::FLOG, VT, Expand);
846 setOperationAction(ISD::FLOG2, VT, Expand);
847 setOperationAction(ISD::FLOG10, VT, Expand);
848 setOperationAction(ISD::FEXP, VT, Expand);
849 setOperationAction(ISD::FEXP2, VT, Expand);
850 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
851 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
852 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
853 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
854 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
855 setOperationAction(ISD::TRUNCATE, VT, Expand);
856 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
857 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
858 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
859 setOperationAction(ISD::VSELECT, VT, Expand);
860 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
861 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
862 setTruncStoreAction(VT,
863 (MVT::SimpleValueType)InnerVT, Expand);
864 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
865 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
866 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
869 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
870 // with -msoft-float, disable use of MMX as well.
871 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
872 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
873 // No operations on x86mmx supported, everything uses intrinsics.
876 // MMX-sized vectors (other than x86mmx) are expected to be expanded
877 // into smaller operations.
878 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
879 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
880 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
881 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
882 setOperationAction(ISD::AND, MVT::v8i8, Expand);
883 setOperationAction(ISD::AND, MVT::v4i16, Expand);
884 setOperationAction(ISD::AND, MVT::v2i32, Expand);
885 setOperationAction(ISD::AND, MVT::v1i64, Expand);
886 setOperationAction(ISD::OR, MVT::v8i8, Expand);
887 setOperationAction(ISD::OR, MVT::v4i16, Expand);
888 setOperationAction(ISD::OR, MVT::v2i32, Expand);
889 setOperationAction(ISD::OR, MVT::v1i64, Expand);
890 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
891 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
892 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
893 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
894 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
895 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
896 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
897 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
898 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
899 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
900 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
901 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
902 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
903 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
904 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
905 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
906 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
908 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
909 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
911 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
912 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
913 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
914 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
915 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
916 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
917 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
918 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
919 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
920 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
921 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
922 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
925 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
926 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
928 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
929 // registers cannot be used even for integer operations.
930 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
931 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
932 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
933 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
935 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
936 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
937 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
938 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
939 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
940 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
941 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
942 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
943 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
944 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
945 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
946 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
947 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
948 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
949 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
950 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
951 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
952 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
954 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
955 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
956 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
957 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
959 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
960 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
961 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
962 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
963 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
965 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
966 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
967 MVT VT = (MVT::SimpleValueType)i;
968 // Do not attempt to custom lower non-power-of-2 vectors
969 if (!isPowerOf2_32(VT.getVectorNumElements()))
971 // Do not attempt to custom lower non-128-bit vectors
972 if (!VT.is128BitVector())
974 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
975 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
976 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
979 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
980 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
981 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
982 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
983 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
984 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
986 if (Subtarget->is64Bit()) {
987 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
988 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
991 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
992 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
993 MVT VT = (MVT::SimpleValueType)i;
995 // Do not attempt to promote non-128-bit vectors
996 if (!VT.is128BitVector())
999 setOperationAction(ISD::AND, VT, Promote);
1000 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
1001 setOperationAction(ISD::OR, VT, Promote);
1002 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
1003 setOperationAction(ISD::XOR, VT, Promote);
1004 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
1005 setOperationAction(ISD::LOAD, VT, Promote);
1006 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
1007 setOperationAction(ISD::SELECT, VT, Promote);
1008 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1011 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1013 // Custom lower v2i64 and v2f64 selects.
1014 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
1015 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
1016 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
1017 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
1019 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1020 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1022 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1023 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1024 // As there is no 64-bit GPR available, we need build a special custom
1025 // sequence to convert from v2i32 to v2f32.
1026 if (!Subtarget->is64Bit())
1027 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
1029 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1030 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
1032 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
1035 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1036 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1037 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1038 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1039 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1040 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1041 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1042 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1043 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1044 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1045 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1047 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1048 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
1049 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1050 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
1051 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
1052 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
1053 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
1054 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
1055 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
1056 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
1058 // FIXME: Do we need to handle scalar-to-vector here?
1059 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1061 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
1062 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal);
1063 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
1064 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
1065 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
1067 // i8 and i16 vectors are custom , because the source register and source
1068 // source memory operand types are not the same width. f32 vectors are
1069 // custom since the immediate controlling the insert encodes additional
1071 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1072 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1073 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1074 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1076 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1077 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1078 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1079 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1081 // FIXME: these should be Legal but thats only for the case where
1082 // the index is constant. For now custom expand to deal with that.
1083 if (Subtarget->is64Bit()) {
1084 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1085 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1089 if (Subtarget->hasSSE2()) {
1090 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1091 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1093 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1094 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1096 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1097 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1099 // In the customized shift lowering, the legal cases in AVX2 will be
1101 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1102 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1104 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1105 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1107 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1109 setOperationAction(ISD::SDIV, MVT::v8i16, Custom);
1110 setOperationAction(ISD::SDIV, MVT::v4i32, Custom);
1113 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1114 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1115 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1116 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1117 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1118 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1119 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1121 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1122 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1123 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1125 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1126 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1127 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1128 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1129 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1130 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1131 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1132 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1133 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1134 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1135 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1136 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1138 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1139 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1140 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1141 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1142 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1143 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1144 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1145 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1146 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1147 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1148 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1149 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1151 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1152 // even though v8i16 is a legal type.
1153 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1154 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1155 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1157 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1158 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1159 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1161 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1162 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1164 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1166 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1167 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1169 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1170 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1172 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1173 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1175 setOperationAction(ISD::SDIV, MVT::v16i16, 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::VSELECT, MVT::v32i8, Legal);
1231 setOperationAction(ISD::SDIV, MVT::v8i32, Custom);
1233 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1234 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1235 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1236 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1238 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1239 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1240 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1241 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1243 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1244 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1245 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1246 // Don't lower v32i8 because there is no 128-bit byte mul
1249 // In the customized shift lowering, the legal cases in AVX2 will be
1251 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1252 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1254 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1255 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1257 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1259 // Custom lower several nodes for 256-bit types.
1260 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1261 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1262 MVT VT = (MVT::SimpleValueType)i;
1264 // Extract subvector is special because the value type
1265 // (result) is 128-bit but the source is 256-bit wide.
1266 if (VT.is128BitVector())
1267 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1269 // Do not attempt to custom lower other non-256-bit vectors
1270 if (!VT.is256BitVector())
1273 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1274 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1275 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1276 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1277 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1278 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1279 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1282 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1283 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1284 MVT VT = (MVT::SimpleValueType)i;
1286 // Do not attempt to promote non-256-bit vectors
1287 if (!VT.is256BitVector())
1290 setOperationAction(ISD::AND, VT, Promote);
1291 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1292 setOperationAction(ISD::OR, VT, Promote);
1293 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1294 setOperationAction(ISD::XOR, VT, Promote);
1295 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1296 setOperationAction(ISD::LOAD, VT, Promote);
1297 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1298 setOperationAction(ISD::SELECT, VT, Promote);
1299 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1303 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1304 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1305 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1306 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1307 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1309 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1310 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1311 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1313 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1314 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1315 setOperationAction(ISD::XOR, MVT::i1, Legal);
1316 setOperationAction(ISD::OR, MVT::i1, Legal);
1317 setOperationAction(ISD::AND, MVT::i1, Legal);
1318 setLoadExtAction(ISD::EXTLOAD, MVT::v8f32, Legal);
1319 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1320 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1321 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1322 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1323 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1325 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1326 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1327 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1328 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1329 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1330 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1332 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1333 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1334 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1335 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1336 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1337 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1338 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1339 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1340 setOperationAction(ISD::SDIV, MVT::v16i32, Custom);
1342 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1343 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1344 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1345 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1346 if (Subtarget->is64Bit()) {
1347 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1348 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1349 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1350 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1352 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1353 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1354 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1355 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1356 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1357 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1358 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1359 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1360 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1361 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1363 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1364 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1365 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1366 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1367 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1368 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1369 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1370 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1371 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1372 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1373 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1374 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1375 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1377 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1378 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1379 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1380 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1381 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1382 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1384 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1385 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1387 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1389 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1390 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1391 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1392 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1393 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1394 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1395 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1396 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1397 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1399 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1400 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1402 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1403 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1405 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1407 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1408 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1410 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1411 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1413 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1414 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1416 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1417 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1418 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1419 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1420 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1421 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1423 // Custom lower several nodes.
1424 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1425 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1426 MVT VT = (MVT::SimpleValueType)i;
1428 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1429 // Extract subvector is special because the value type
1430 // (result) is 256/128-bit but the source is 512-bit wide.
1431 if (VT.is128BitVector() || VT.is256BitVector())
1432 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1434 if (VT.getVectorElementType() == MVT::i1)
1435 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1437 // Do not attempt to custom lower other non-512-bit vectors
1438 if (!VT.is512BitVector())
1441 if ( EltSize >= 32) {
1442 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1443 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1444 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1445 setOperationAction(ISD::VSELECT, VT, Legal);
1446 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1447 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1448 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1451 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1452 MVT VT = (MVT::SimpleValueType)i;
1454 // Do not attempt to promote non-256-bit vectors
1455 if (!VT.is512BitVector())
1458 setOperationAction(ISD::SELECT, VT, Promote);
1459 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1463 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1464 // of this type with custom code.
1465 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1466 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1467 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1471 // We want to custom lower some of our intrinsics.
1472 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1473 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1474 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1475 if (!Subtarget->is64Bit())
1476 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1478 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1479 // handle type legalization for these operations here.
1481 // FIXME: We really should do custom legalization for addition and
1482 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1483 // than generic legalization for 64-bit multiplication-with-overflow, though.
1484 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1485 // Add/Sub/Mul with overflow operations are custom lowered.
1487 setOperationAction(ISD::SADDO, VT, Custom);
1488 setOperationAction(ISD::UADDO, VT, Custom);
1489 setOperationAction(ISD::SSUBO, VT, Custom);
1490 setOperationAction(ISD::USUBO, VT, Custom);
1491 setOperationAction(ISD::SMULO, VT, Custom);
1492 setOperationAction(ISD::UMULO, VT, Custom);
1495 // There are no 8-bit 3-address imul/mul instructions
1496 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1497 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1499 if (!Subtarget->is64Bit()) {
1500 // These libcalls are not available in 32-bit.
1501 setLibcallName(RTLIB::SHL_I128, nullptr);
1502 setLibcallName(RTLIB::SRL_I128, nullptr);
1503 setLibcallName(RTLIB::SRA_I128, nullptr);
1506 // Combine sin / cos into one node or libcall if possible.
1507 if (Subtarget->hasSinCos()) {
1508 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1509 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1510 if (Subtarget->isTargetDarwin()) {
1511 // For MacOSX, we don't want to the normal expansion of a libcall to
1512 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1514 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1515 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1519 // We have target-specific dag combine patterns for the following nodes:
1520 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1521 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1522 setTargetDAGCombine(ISD::VSELECT);
1523 setTargetDAGCombine(ISD::SELECT);
1524 setTargetDAGCombine(ISD::SHL);
1525 setTargetDAGCombine(ISD::SRA);
1526 setTargetDAGCombine(ISD::SRL);
1527 setTargetDAGCombine(ISD::OR);
1528 setTargetDAGCombine(ISD::AND);
1529 setTargetDAGCombine(ISD::ADD);
1530 setTargetDAGCombine(ISD::FADD);
1531 setTargetDAGCombine(ISD::FSUB);
1532 setTargetDAGCombine(ISD::FMA);
1533 setTargetDAGCombine(ISD::SUB);
1534 setTargetDAGCombine(ISD::LOAD);
1535 setTargetDAGCombine(ISD::STORE);
1536 setTargetDAGCombine(ISD::ZERO_EXTEND);
1537 setTargetDAGCombine(ISD::ANY_EXTEND);
1538 setTargetDAGCombine(ISD::SIGN_EXTEND);
1539 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1540 setTargetDAGCombine(ISD::TRUNCATE);
1541 setTargetDAGCombine(ISD::SINT_TO_FP);
1542 setTargetDAGCombine(ISD::SETCC);
1543 if (Subtarget->is64Bit())
1544 setTargetDAGCombine(ISD::MUL);
1545 setTargetDAGCombine(ISD::XOR);
1547 computeRegisterProperties();
1549 // On Darwin, -Os means optimize for size without hurting performance,
1550 // do not reduce the limit.
1551 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1552 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1553 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1554 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1555 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1556 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1557 setPrefLoopAlignment(4); // 2^4 bytes.
1559 // Predictable cmov don't hurt on atom because it's in-order.
1560 PredictableSelectIsExpensive = !Subtarget->isAtom();
1562 setPrefFunctionAlignment(4); // 2^4 bytes.
1565 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1567 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1569 if (Subtarget->hasAVX512())
1570 switch(VT.getVectorNumElements()) {
1571 case 8: return MVT::v8i1;
1572 case 16: return MVT::v16i1;
1575 return VT.changeVectorElementTypeToInteger();
1578 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1579 /// the desired ByVal argument alignment.
1580 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1583 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1584 if (VTy->getBitWidth() == 128)
1586 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1587 unsigned EltAlign = 0;
1588 getMaxByValAlign(ATy->getElementType(), EltAlign);
1589 if (EltAlign > MaxAlign)
1590 MaxAlign = EltAlign;
1591 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1592 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1593 unsigned EltAlign = 0;
1594 getMaxByValAlign(STy->getElementType(i), EltAlign);
1595 if (EltAlign > MaxAlign)
1596 MaxAlign = EltAlign;
1603 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1604 /// function arguments in the caller parameter area. For X86, aggregates
1605 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1606 /// are at 4-byte boundaries.
1607 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1608 if (Subtarget->is64Bit()) {
1609 // Max of 8 and alignment of type.
1610 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1617 if (Subtarget->hasSSE1())
1618 getMaxByValAlign(Ty, Align);
1622 /// getOptimalMemOpType - Returns the target specific optimal type for load
1623 /// and store operations as a result of memset, memcpy, and memmove
1624 /// lowering. If DstAlign is zero that means it's safe to destination
1625 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1626 /// means there isn't a need to check it against alignment requirement,
1627 /// probably because the source does not need to be loaded. If 'IsMemset' is
1628 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1629 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1630 /// source is constant so it does not need to be loaded.
1631 /// It returns EVT::Other if the type should be determined using generic
1632 /// target-independent logic.
1634 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1635 unsigned DstAlign, unsigned SrcAlign,
1636 bool IsMemset, bool ZeroMemset,
1638 MachineFunction &MF) const {
1639 const Function *F = MF.getFunction();
1640 if ((!IsMemset || ZeroMemset) &&
1641 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1642 Attribute::NoImplicitFloat)) {
1644 (Subtarget->isUnalignedMemAccessFast() ||
1645 ((DstAlign == 0 || DstAlign >= 16) &&
1646 (SrcAlign == 0 || SrcAlign >= 16)))) {
1648 if (Subtarget->hasInt256())
1650 if (Subtarget->hasFp256())
1653 if (Subtarget->hasSSE2())
1655 if (Subtarget->hasSSE1())
1657 } else if (!MemcpyStrSrc && Size >= 8 &&
1658 !Subtarget->is64Bit() &&
1659 Subtarget->hasSSE2()) {
1660 // Do not use f64 to lower memcpy if source is string constant. It's
1661 // better to use i32 to avoid the loads.
1665 if (Subtarget->is64Bit() && Size >= 8)
1670 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1672 return X86ScalarSSEf32;
1673 else if (VT == MVT::f64)
1674 return X86ScalarSSEf64;
1679 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1683 *Fast = Subtarget->isUnalignedMemAccessFast();
1687 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1688 /// current function. The returned value is a member of the
1689 /// MachineJumpTableInfo::JTEntryKind enum.
1690 unsigned X86TargetLowering::getJumpTableEncoding() const {
1691 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1693 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1694 Subtarget->isPICStyleGOT())
1695 return MachineJumpTableInfo::EK_Custom32;
1697 // Otherwise, use the normal jump table encoding heuristics.
1698 return TargetLowering::getJumpTableEncoding();
1702 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1703 const MachineBasicBlock *MBB,
1704 unsigned uid,MCContext &Ctx) const{
1705 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1706 Subtarget->isPICStyleGOT());
1707 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1709 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1710 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1713 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1715 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1716 SelectionDAG &DAG) const {
1717 if (!Subtarget->is64Bit())
1718 // This doesn't have SDLoc associated with it, but is not really the
1719 // same as a Register.
1720 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1724 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1725 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1727 const MCExpr *X86TargetLowering::
1728 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1729 MCContext &Ctx) const {
1730 // X86-64 uses RIP relative addressing based on the jump table label.
1731 if (Subtarget->isPICStyleRIPRel())
1732 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1734 // Otherwise, the reference is relative to the PIC base.
1735 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1738 // FIXME: Why this routine is here? Move to RegInfo!
1739 std::pair<const TargetRegisterClass*, uint8_t>
1740 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1741 const TargetRegisterClass *RRC = nullptr;
1743 switch (VT.SimpleTy) {
1745 return TargetLowering::findRepresentativeClass(VT);
1746 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1747 RRC = Subtarget->is64Bit() ?
1748 (const TargetRegisterClass*)&X86::GR64RegClass :
1749 (const TargetRegisterClass*)&X86::GR32RegClass;
1752 RRC = &X86::VR64RegClass;
1754 case MVT::f32: case MVT::f64:
1755 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1756 case MVT::v4f32: case MVT::v2f64:
1757 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1759 RRC = &X86::VR128RegClass;
1762 return std::make_pair(RRC, Cost);
1765 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1766 unsigned &Offset) const {
1767 if (!Subtarget->isTargetLinux())
1770 if (Subtarget->is64Bit()) {
1771 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1773 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1785 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1786 unsigned DestAS) const {
1787 assert(SrcAS != DestAS && "Expected different address spaces!");
1789 return SrcAS < 256 && DestAS < 256;
1792 //===----------------------------------------------------------------------===//
1793 // Return Value Calling Convention Implementation
1794 //===----------------------------------------------------------------------===//
1796 #include "X86GenCallingConv.inc"
1799 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1800 MachineFunction &MF, bool isVarArg,
1801 const SmallVectorImpl<ISD::OutputArg> &Outs,
1802 LLVMContext &Context) const {
1803 SmallVector<CCValAssign, 16> RVLocs;
1804 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1806 return CCInfo.CheckReturn(Outs, RetCC_X86);
1809 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1810 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1815 X86TargetLowering::LowerReturn(SDValue Chain,
1816 CallingConv::ID CallConv, bool isVarArg,
1817 const SmallVectorImpl<ISD::OutputArg> &Outs,
1818 const SmallVectorImpl<SDValue> &OutVals,
1819 SDLoc dl, SelectionDAG &DAG) const {
1820 MachineFunction &MF = DAG.getMachineFunction();
1821 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1823 SmallVector<CCValAssign, 16> RVLocs;
1824 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1825 RVLocs, *DAG.getContext());
1826 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1829 SmallVector<SDValue, 6> RetOps;
1830 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1831 // Operand #1 = Bytes To Pop
1832 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1835 // Copy the result values into the output registers.
1836 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1837 CCValAssign &VA = RVLocs[i];
1838 assert(VA.isRegLoc() && "Can only return in registers!");
1839 SDValue ValToCopy = OutVals[i];
1840 EVT ValVT = ValToCopy.getValueType();
1842 // Promote values to the appropriate types
1843 if (VA.getLocInfo() == CCValAssign::SExt)
1844 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1845 else if (VA.getLocInfo() == CCValAssign::ZExt)
1846 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1847 else if (VA.getLocInfo() == CCValAssign::AExt)
1848 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1849 else if (VA.getLocInfo() == CCValAssign::BCvt)
1850 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1852 assert(VA.getLocInfo() != CCValAssign::FPExt &&
1853 "Unexpected FP-extend for return value.");
1855 // If this is x86-64, and we disabled SSE, we can't return FP values,
1856 // or SSE or MMX vectors.
1857 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1858 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1859 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1860 report_fatal_error("SSE register return with SSE disabled");
1862 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1863 // llvm-gcc has never done it right and no one has noticed, so this
1864 // should be OK for now.
1865 if (ValVT == MVT::f64 &&
1866 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1867 report_fatal_error("SSE2 register return with SSE2 disabled");
1869 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1870 // the RET instruction and handled by the FP Stackifier.
1871 if (VA.getLocReg() == X86::ST0 ||
1872 VA.getLocReg() == X86::ST1) {
1873 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1874 // change the value to the FP stack register class.
1875 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1876 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1877 RetOps.push_back(ValToCopy);
1878 // Don't emit a copytoreg.
1882 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1883 // which is returned in RAX / RDX.
1884 if (Subtarget->is64Bit()) {
1885 if (ValVT == MVT::x86mmx) {
1886 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1887 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1888 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1890 // If we don't have SSE2 available, convert to v4f32 so the generated
1891 // register is legal.
1892 if (!Subtarget->hasSSE2())
1893 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1898 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1899 Flag = Chain.getValue(1);
1900 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1903 // The x86-64 ABIs require that for returning structs by value we copy
1904 // the sret argument into %rax/%eax (depending on ABI) for the return.
1905 // Win32 requires us to put the sret argument to %eax as well.
1906 // We saved the argument into a virtual register in the entry block,
1907 // so now we copy the value out and into %rax/%eax.
1908 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1909 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1910 MachineFunction &MF = DAG.getMachineFunction();
1911 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1912 unsigned Reg = FuncInfo->getSRetReturnReg();
1914 "SRetReturnReg should have been set in LowerFormalArguments().");
1915 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1918 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1919 X86::RAX : X86::EAX;
1920 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1921 Flag = Chain.getValue(1);
1923 // RAX/EAX now acts like a return value.
1924 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1927 RetOps[0] = Chain; // Update chain.
1929 // Add the flag if we have it.
1931 RetOps.push_back(Flag);
1933 return DAG.getNode(X86ISD::RET_FLAG, dl,
1934 MVT::Other, &RetOps[0], RetOps.size());
1937 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1938 if (N->getNumValues() != 1)
1940 if (!N->hasNUsesOfValue(1, 0))
1943 SDValue TCChain = Chain;
1944 SDNode *Copy = *N->use_begin();
1945 if (Copy->getOpcode() == ISD::CopyToReg) {
1946 // If the copy has a glue operand, we conservatively assume it isn't safe to
1947 // perform a tail call.
1948 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1950 TCChain = Copy->getOperand(0);
1951 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1954 bool HasRet = false;
1955 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1957 if (UI->getOpcode() != X86ISD::RET_FLAG)
1970 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1971 ISD::NodeType ExtendKind) const {
1973 // TODO: Is this also valid on 32-bit?
1974 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1975 ReturnMVT = MVT::i8;
1977 ReturnMVT = MVT::i32;
1979 MVT MinVT = getRegisterType(ReturnMVT);
1980 return VT.bitsLT(MinVT) ? MinVT : VT;
1983 /// LowerCallResult - Lower the result values of a call into the
1984 /// appropriate copies out of appropriate physical registers.
1987 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1988 CallingConv::ID CallConv, bool isVarArg,
1989 const SmallVectorImpl<ISD::InputArg> &Ins,
1990 SDLoc dl, SelectionDAG &DAG,
1991 SmallVectorImpl<SDValue> &InVals) const {
1993 // Assign locations to each value returned by this call.
1994 SmallVector<CCValAssign, 16> RVLocs;
1995 bool Is64Bit = Subtarget->is64Bit();
1996 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1997 getTargetMachine(), RVLocs, *DAG.getContext());
1998 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2000 // Copy all of the result registers out of their specified physreg.
2001 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2002 CCValAssign &VA = RVLocs[i];
2003 EVT CopyVT = VA.getValVT();
2005 // If this is x86-64, and we disabled SSE, we can't return FP values
2006 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2007 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2008 report_fatal_error("SSE register return with SSE disabled");
2013 // If this is a call to a function that returns an fp value on the floating
2014 // point stack, we must guarantee the value is popped from the stack, so
2015 // a CopyFromReg is not good enough - the copy instruction may be eliminated
2016 // if the return value is not used. We use the FpPOP_RETVAL instruction
2018 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2019 // If we prefer to use the value in xmm registers, copy it out as f80 and
2020 // use a truncate to move it from fp stack reg to xmm reg.
2021 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2022 SDValue Ops[] = { Chain, InFlag };
2023 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2024 MVT::Other, MVT::Glue, Ops), 1);
2025 Val = Chain.getValue(0);
2027 // Round the f80 to the right size, which also moves it to the appropriate
2029 if (CopyVT != VA.getValVT())
2030 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2031 // This truncation won't change the value.
2032 DAG.getIntPtrConstant(1));
2034 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2035 CopyVT, InFlag).getValue(1);
2036 Val = Chain.getValue(0);
2038 InFlag = Chain.getValue(2);
2039 InVals.push_back(Val);
2045 //===----------------------------------------------------------------------===//
2046 // C & StdCall & Fast Calling Convention implementation
2047 //===----------------------------------------------------------------------===//
2048 // StdCall calling convention seems to be standard for many Windows' API
2049 // routines and around. It differs from C calling convention just a little:
2050 // callee should clean up the stack, not caller. Symbols should be also
2051 // decorated in some fancy way :) It doesn't support any vector arguments.
2052 // For info on fast calling convention see Fast Calling Convention (tail call)
2053 // implementation LowerX86_32FastCCCallTo.
2055 /// CallIsStructReturn - Determines whether a call uses struct return
2057 enum StructReturnType {
2062 static StructReturnType
2063 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2065 return NotStructReturn;
2067 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2068 if (!Flags.isSRet())
2069 return NotStructReturn;
2070 if (Flags.isInReg())
2071 return RegStructReturn;
2072 return StackStructReturn;
2075 /// ArgsAreStructReturn - Determines whether a function uses struct
2076 /// return semantics.
2077 static StructReturnType
2078 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2080 return NotStructReturn;
2082 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2083 if (!Flags.isSRet())
2084 return NotStructReturn;
2085 if (Flags.isInReg())
2086 return RegStructReturn;
2087 return StackStructReturn;
2090 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2091 /// by "Src" to address "Dst" with size and alignment information specified by
2092 /// the specific parameter attribute. The copy will be passed as a byval
2093 /// function parameter.
2095 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2096 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2098 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2100 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2101 /*isVolatile*/false, /*AlwaysInline=*/true,
2102 MachinePointerInfo(), MachinePointerInfo());
2105 /// IsTailCallConvention - Return true if the calling convention is one that
2106 /// supports tail call optimization.
2107 static bool IsTailCallConvention(CallingConv::ID CC) {
2108 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2109 CC == CallingConv::HiPE);
2112 /// \brief Return true if the calling convention is a C calling convention.
2113 static bool IsCCallConvention(CallingConv::ID CC) {
2114 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2115 CC == CallingConv::X86_64_SysV);
2118 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2119 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2123 CallingConv::ID CalleeCC = CS.getCallingConv();
2124 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2130 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2131 /// a tailcall target by changing its ABI.
2132 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2133 bool GuaranteedTailCallOpt) {
2134 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2138 X86TargetLowering::LowerMemArgument(SDValue Chain,
2139 CallingConv::ID CallConv,
2140 const SmallVectorImpl<ISD::InputArg> &Ins,
2141 SDLoc dl, SelectionDAG &DAG,
2142 const CCValAssign &VA,
2143 MachineFrameInfo *MFI,
2145 // Create the nodes corresponding to a load from this parameter slot.
2146 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2147 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2148 getTargetMachine().Options.GuaranteedTailCallOpt);
2149 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2152 // If value is passed by pointer we have address passed instead of the value
2154 if (VA.getLocInfo() == CCValAssign::Indirect)
2155 ValVT = VA.getLocVT();
2157 ValVT = VA.getValVT();
2159 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2160 // changed with more analysis.
2161 // In case of tail call optimization mark all arguments mutable. Since they
2162 // could be overwritten by lowering of arguments in case of a tail call.
2163 if (Flags.isByVal()) {
2164 unsigned Bytes = Flags.getByValSize();
2165 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2166 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2167 return DAG.getFrameIndex(FI, getPointerTy());
2169 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2170 VA.getLocMemOffset(), isImmutable);
2171 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2172 return DAG.getLoad(ValVT, dl, Chain, FIN,
2173 MachinePointerInfo::getFixedStack(FI),
2174 false, false, false, 0);
2179 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2180 CallingConv::ID CallConv,
2182 const SmallVectorImpl<ISD::InputArg> &Ins,
2185 SmallVectorImpl<SDValue> &InVals)
2187 MachineFunction &MF = DAG.getMachineFunction();
2188 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2190 const Function* Fn = MF.getFunction();
2191 if (Fn->hasExternalLinkage() &&
2192 Subtarget->isTargetCygMing() &&
2193 Fn->getName() == "main")
2194 FuncInfo->setForceFramePointer(true);
2196 MachineFrameInfo *MFI = MF.getFrameInfo();
2197 bool Is64Bit = Subtarget->is64Bit();
2198 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2200 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2201 "Var args not supported with calling convention fastcc, ghc or hipe");
2203 // Assign locations to all of the incoming arguments.
2204 SmallVector<CCValAssign, 16> ArgLocs;
2205 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2206 ArgLocs, *DAG.getContext());
2208 // Allocate shadow area for Win64
2210 CCInfo.AllocateStack(32, 8);
2212 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2214 unsigned LastVal = ~0U;
2216 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2217 CCValAssign &VA = ArgLocs[i];
2218 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2220 assert(VA.getValNo() != LastVal &&
2221 "Don't support value assigned to multiple locs yet");
2223 LastVal = VA.getValNo();
2225 if (VA.isRegLoc()) {
2226 EVT RegVT = VA.getLocVT();
2227 const TargetRegisterClass *RC;
2228 if (RegVT == MVT::i32)
2229 RC = &X86::GR32RegClass;
2230 else if (Is64Bit && RegVT == MVT::i64)
2231 RC = &X86::GR64RegClass;
2232 else if (RegVT == MVT::f32)
2233 RC = &X86::FR32RegClass;
2234 else if (RegVT == MVT::f64)
2235 RC = &X86::FR64RegClass;
2236 else if (RegVT.is512BitVector())
2237 RC = &X86::VR512RegClass;
2238 else if (RegVT.is256BitVector())
2239 RC = &X86::VR256RegClass;
2240 else if (RegVT.is128BitVector())
2241 RC = &X86::VR128RegClass;
2242 else if (RegVT == MVT::x86mmx)
2243 RC = &X86::VR64RegClass;
2244 else if (RegVT == MVT::i1)
2245 RC = &X86::VK1RegClass;
2246 else if (RegVT == MVT::v8i1)
2247 RC = &X86::VK8RegClass;
2248 else if (RegVT == MVT::v16i1)
2249 RC = &X86::VK16RegClass;
2251 llvm_unreachable("Unknown argument type!");
2253 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2254 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2256 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2257 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2259 if (VA.getLocInfo() == CCValAssign::SExt)
2260 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2261 DAG.getValueType(VA.getValVT()));
2262 else if (VA.getLocInfo() == CCValAssign::ZExt)
2263 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2264 DAG.getValueType(VA.getValVT()));
2265 else if (VA.getLocInfo() == CCValAssign::BCvt)
2266 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2268 if (VA.isExtInLoc()) {
2269 // Handle MMX values passed in XMM regs.
2270 if (RegVT.isVector())
2271 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2273 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2276 assert(VA.isMemLoc());
2277 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2280 // If value is passed via pointer - do a load.
2281 if (VA.getLocInfo() == CCValAssign::Indirect)
2282 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2283 MachinePointerInfo(), false, false, false, 0);
2285 InVals.push_back(ArgValue);
2288 // The x86-64 ABIs require that for returning structs by value we copy
2289 // the sret argument into %rax/%eax (depending on ABI) for the return.
2290 // Win32 requires us to put the sret argument to %eax as well.
2291 // Save the argument into a virtual register so that we can access it
2292 // from the return points.
2293 if (MF.getFunction()->hasStructRetAttr() &&
2294 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2295 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2296 unsigned Reg = FuncInfo->getSRetReturnReg();
2298 MVT PtrTy = getPointerTy();
2299 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2300 FuncInfo->setSRetReturnReg(Reg);
2302 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2303 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2306 unsigned StackSize = CCInfo.getNextStackOffset();
2307 // Align stack specially for tail calls.
2308 if (FuncIsMadeTailCallSafe(CallConv,
2309 MF.getTarget().Options.GuaranteedTailCallOpt))
2310 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2312 // If the function takes variable number of arguments, make a frame index for
2313 // the start of the first vararg value... for expansion of llvm.va_start.
2315 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2316 CallConv != CallingConv::X86_ThisCall)) {
2317 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2320 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2322 // FIXME: We should really autogenerate these arrays
2323 static const MCPhysReg GPR64ArgRegsWin64[] = {
2324 X86::RCX, X86::RDX, X86::R8, X86::R9
2326 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2327 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2329 static const MCPhysReg XMMArgRegs64Bit[] = {
2330 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2331 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2333 const MCPhysReg *GPR64ArgRegs;
2334 unsigned NumXMMRegs = 0;
2337 // The XMM registers which might contain var arg parameters are shadowed
2338 // in their paired GPR. So we only need to save the GPR to their home
2340 TotalNumIntRegs = 4;
2341 GPR64ArgRegs = GPR64ArgRegsWin64;
2343 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2344 GPR64ArgRegs = GPR64ArgRegs64Bit;
2346 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2349 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2352 bool NoImplicitFloatOps = Fn->getAttributes().
2353 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2354 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2355 "SSE register cannot be used when SSE is disabled!");
2356 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2357 NoImplicitFloatOps) &&
2358 "SSE register cannot be used when SSE is disabled!");
2359 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2360 !Subtarget->hasSSE1())
2361 // Kernel mode asks for SSE to be disabled, so don't push them
2363 TotalNumXMMRegs = 0;
2366 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2367 // Get to the caller-allocated home save location. Add 8 to account
2368 // for the return address.
2369 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2370 FuncInfo->setRegSaveFrameIndex(
2371 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2372 // Fixup to set vararg frame on shadow area (4 x i64).
2374 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2376 // For X86-64, if there are vararg parameters that are passed via
2377 // registers, then we must store them to their spots on the stack so
2378 // they may be loaded by deferencing the result of va_next.
2379 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2380 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2381 FuncInfo->setRegSaveFrameIndex(
2382 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2386 // Store the integer parameter registers.
2387 SmallVector<SDValue, 8> MemOps;
2388 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2390 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2391 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2392 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2393 DAG.getIntPtrConstant(Offset));
2394 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2395 &X86::GR64RegClass);
2396 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2398 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2399 MachinePointerInfo::getFixedStack(
2400 FuncInfo->getRegSaveFrameIndex(), Offset),
2402 MemOps.push_back(Store);
2406 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2407 // Now store the XMM (fp + vector) parameter registers.
2408 SmallVector<SDValue, 11> SaveXMMOps;
2409 SaveXMMOps.push_back(Chain);
2411 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2412 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2413 SaveXMMOps.push_back(ALVal);
2415 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2416 FuncInfo->getRegSaveFrameIndex()));
2417 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2418 FuncInfo->getVarArgsFPOffset()));
2420 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2421 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2422 &X86::VR128RegClass);
2423 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2424 SaveXMMOps.push_back(Val);
2426 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2428 &SaveXMMOps[0], SaveXMMOps.size()));
2431 if (!MemOps.empty())
2432 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2433 &MemOps[0], MemOps.size());
2437 // Some CCs need callee pop.
2438 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2439 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2440 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2442 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2443 // If this is an sret function, the return should pop the hidden pointer.
2444 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2445 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2446 argsAreStructReturn(Ins) == StackStructReturn)
2447 FuncInfo->setBytesToPopOnReturn(4);
2451 // RegSaveFrameIndex is X86-64 only.
2452 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2453 if (CallConv == CallingConv::X86_FastCall ||
2454 CallConv == CallingConv::X86_ThisCall)
2455 // fastcc functions can't have varargs.
2456 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2459 FuncInfo->setArgumentStackSize(StackSize);
2465 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2466 SDValue StackPtr, SDValue Arg,
2467 SDLoc dl, SelectionDAG &DAG,
2468 const CCValAssign &VA,
2469 ISD::ArgFlagsTy Flags) const {
2470 unsigned LocMemOffset = VA.getLocMemOffset();
2471 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2472 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2473 if (Flags.isByVal())
2474 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2476 return DAG.getStore(Chain, dl, Arg, PtrOff,
2477 MachinePointerInfo::getStack(LocMemOffset),
2481 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2482 /// optimization is performed and it is required.
2484 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2485 SDValue &OutRetAddr, SDValue Chain,
2486 bool IsTailCall, bool Is64Bit,
2487 int FPDiff, SDLoc dl) const {
2488 // Adjust the Return address stack slot.
2489 EVT VT = getPointerTy();
2490 OutRetAddr = getReturnAddressFrameIndex(DAG);
2492 // Load the "old" Return address.
2493 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2494 false, false, false, 0);
2495 return SDValue(OutRetAddr.getNode(), 1);
2498 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2499 /// optimization is performed and it is required (FPDiff!=0).
2501 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2502 SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2503 unsigned SlotSize, int FPDiff, SDLoc dl) {
2504 // Store the return address to the appropriate stack slot.
2505 if (!FPDiff) return Chain;
2506 // Calculate the new stack slot for the return address.
2507 int NewReturnAddrFI =
2508 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2510 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2511 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2512 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2518 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2519 SmallVectorImpl<SDValue> &InVals) const {
2520 SelectionDAG &DAG = CLI.DAG;
2522 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2523 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2524 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2525 SDValue Chain = CLI.Chain;
2526 SDValue Callee = CLI.Callee;
2527 CallingConv::ID CallConv = CLI.CallConv;
2528 bool &isTailCall = CLI.IsTailCall;
2529 bool isVarArg = CLI.IsVarArg;
2531 MachineFunction &MF = DAG.getMachineFunction();
2532 bool Is64Bit = Subtarget->is64Bit();
2533 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2534 StructReturnType SR = callIsStructReturn(Outs);
2535 bool IsSibcall = false;
2537 if (MF.getTarget().Options.DisableTailCalls)
2541 // Check if it's really possible to do a tail call.
2542 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2543 isVarArg, SR != NotStructReturn,
2544 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2545 Outs, OutVals, Ins, DAG);
2547 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
2548 report_fatal_error("failed to perform tail call elimination on a call "
2549 "site marked musttail");
2551 // Sibcalls are automatically detected tailcalls which do not require
2553 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2560 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2561 "Var args not supported with calling convention fastcc, ghc or hipe");
2563 // Analyze operands of the call, assigning locations to each operand.
2564 SmallVector<CCValAssign, 16> ArgLocs;
2565 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2566 ArgLocs, *DAG.getContext());
2568 // Allocate shadow area for Win64
2570 CCInfo.AllocateStack(32, 8);
2572 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2574 // Get a count of how many bytes are to be pushed on the stack.
2575 unsigned NumBytes = CCInfo.getNextStackOffset();
2577 // This is a sibcall. The memory operands are available in caller's
2578 // own caller's stack.
2580 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2581 IsTailCallConvention(CallConv))
2582 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2585 if (isTailCall && !IsSibcall) {
2586 // Lower arguments at fp - stackoffset + fpdiff.
2587 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2588 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2590 FPDiff = NumBytesCallerPushed - NumBytes;
2592 // Set the delta of movement of the returnaddr stackslot.
2593 // But only set if delta is greater than previous delta.
2594 if (FPDiff < X86Info->getTCReturnAddrDelta())
2595 X86Info->setTCReturnAddrDelta(FPDiff);
2598 unsigned NumBytesToPush = NumBytes;
2599 unsigned NumBytesToPop = NumBytes;
2601 // If we have an inalloca argument, all stack space has already been allocated
2602 // for us and be right at the top of the stack. We don't support multiple
2603 // arguments passed in memory when using inalloca.
2604 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2606 assert(ArgLocs.back().getLocMemOffset() == 0 &&
2607 "an inalloca argument must be the only memory argument");
2611 Chain = DAG.getCALLSEQ_START(
2612 Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2614 SDValue RetAddrFrIdx;
2615 // Load return address for tail calls.
2616 if (isTailCall && FPDiff)
2617 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2618 Is64Bit, FPDiff, dl);
2620 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2621 SmallVector<SDValue, 8> MemOpChains;
2624 // Walk the register/memloc assignments, inserting copies/loads. In the case
2625 // of tail call optimization arguments are handle later.
2626 const X86RegisterInfo *RegInfo =
2627 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2628 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2629 // Skip inalloca arguments, they have already been written.
2630 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2631 if (Flags.isInAlloca())
2634 CCValAssign &VA = ArgLocs[i];
2635 EVT RegVT = VA.getLocVT();
2636 SDValue Arg = OutVals[i];
2637 bool isByVal = Flags.isByVal();
2639 // Promote the value if needed.
2640 switch (VA.getLocInfo()) {
2641 default: llvm_unreachable("Unknown loc info!");
2642 case CCValAssign::Full: break;
2643 case CCValAssign::SExt:
2644 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2646 case CCValAssign::ZExt:
2647 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2649 case CCValAssign::AExt:
2650 if (RegVT.is128BitVector()) {
2651 // Special case: passing MMX values in XMM registers.
2652 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2653 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2654 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2656 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2658 case CCValAssign::BCvt:
2659 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2661 case CCValAssign::Indirect: {
2662 // Store the argument.
2663 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2664 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2665 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2666 MachinePointerInfo::getFixedStack(FI),
2673 if (VA.isRegLoc()) {
2674 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2675 if (isVarArg && IsWin64) {
2676 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2677 // shadow reg if callee is a varargs function.
2678 unsigned ShadowReg = 0;
2679 switch (VA.getLocReg()) {
2680 case X86::XMM0: ShadowReg = X86::RCX; break;
2681 case X86::XMM1: ShadowReg = X86::RDX; break;
2682 case X86::XMM2: ShadowReg = X86::R8; break;
2683 case X86::XMM3: ShadowReg = X86::R9; break;
2686 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2688 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2689 assert(VA.isMemLoc());
2690 if (!StackPtr.getNode())
2691 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2693 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2694 dl, DAG, VA, Flags));
2698 if (!MemOpChains.empty())
2699 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2700 &MemOpChains[0], MemOpChains.size());
2702 if (Subtarget->isPICStyleGOT()) {
2703 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2706 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2707 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2709 // If we are tail calling and generating PIC/GOT style code load the
2710 // address of the callee into ECX. The value in ecx is used as target of
2711 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2712 // for tail calls on PIC/GOT architectures. Normally we would just put the
2713 // address of GOT into ebx and then call target@PLT. But for tail calls
2714 // ebx would be restored (since ebx is callee saved) before jumping to the
2717 // Note: The actual moving to ECX is done further down.
2718 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2719 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2720 !G->getGlobal()->hasProtectedVisibility())
2721 Callee = LowerGlobalAddress(Callee, DAG);
2722 else if (isa<ExternalSymbolSDNode>(Callee))
2723 Callee = LowerExternalSymbol(Callee, DAG);
2727 if (Is64Bit && isVarArg && !IsWin64) {
2728 // From AMD64 ABI document:
2729 // For calls that may call functions that use varargs or stdargs
2730 // (prototype-less calls or calls to functions containing ellipsis (...) in
2731 // the declaration) %al is used as hidden argument to specify the number
2732 // of SSE registers used. The contents of %al do not need to match exactly
2733 // the number of registers, but must be an ubound on the number of SSE
2734 // registers used and is in the range 0 - 8 inclusive.
2736 // Count the number of XMM registers allocated.
2737 static const MCPhysReg XMMArgRegs[] = {
2738 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2739 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2741 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2742 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2743 && "SSE registers cannot be used when SSE is disabled");
2745 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2746 DAG.getConstant(NumXMMRegs, MVT::i8)));
2749 // For tail calls lower the arguments to the 'real' stack slot.
2751 // Force all the incoming stack arguments to be loaded from the stack
2752 // before any new outgoing arguments are stored to the stack, because the
2753 // outgoing stack slots may alias the incoming argument stack slots, and
2754 // the alias isn't otherwise explicit. This is slightly more conservative
2755 // than necessary, because it means that each store effectively depends
2756 // on every argument instead of just those arguments it would clobber.
2757 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2759 SmallVector<SDValue, 8> MemOpChains2;
2762 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2763 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2764 CCValAssign &VA = ArgLocs[i];
2767 assert(VA.isMemLoc());
2768 SDValue Arg = OutVals[i];
2769 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2770 // Create frame index.
2771 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2772 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2773 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2774 FIN = DAG.getFrameIndex(FI, getPointerTy());
2776 if (Flags.isByVal()) {
2777 // Copy relative to framepointer.
2778 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2779 if (!StackPtr.getNode())
2780 StackPtr = DAG.getCopyFromReg(Chain, dl,
2781 RegInfo->getStackRegister(),
2783 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2785 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2789 // Store relative to framepointer.
2790 MemOpChains2.push_back(
2791 DAG.getStore(ArgChain, dl, Arg, FIN,
2792 MachinePointerInfo::getFixedStack(FI),
2798 if (!MemOpChains2.empty())
2799 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2800 &MemOpChains2[0], MemOpChains2.size());
2802 // Store the return address to the appropriate stack slot.
2803 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2804 getPointerTy(), RegInfo->getSlotSize(),
2808 // Build a sequence of copy-to-reg nodes chained together with token chain
2809 // and flag operands which copy the outgoing args into registers.
2811 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2812 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2813 RegsToPass[i].second, InFlag);
2814 InFlag = Chain.getValue(1);
2817 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2818 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2819 // In the 64-bit large code model, we have to make all calls
2820 // through a register, since the call instruction's 32-bit
2821 // pc-relative offset may not be large enough to hold the whole
2823 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2824 // If the callee is a GlobalAddress node (quite common, every direct call
2825 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2828 // We should use extra load for direct calls to dllimported functions in
2830 const GlobalValue *GV = G->getGlobal();
2831 if (!GV->hasDLLImportStorageClass()) {
2832 unsigned char OpFlags = 0;
2833 bool ExtraLoad = false;
2834 unsigned WrapperKind = ISD::DELETED_NODE;
2836 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2837 // external symbols most go through the PLT in PIC mode. If the symbol
2838 // has hidden or protected visibility, or if it is static or local, then
2839 // we don't need to use the PLT - we can directly call it.
2840 if (Subtarget->isTargetELF() &&
2841 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2842 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2843 OpFlags = X86II::MO_PLT;
2844 } else if (Subtarget->isPICStyleStubAny() &&
2845 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2846 (!Subtarget->getTargetTriple().isMacOSX() ||
2847 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2848 // PC-relative references to external symbols should go through $stub,
2849 // unless we're building with the leopard linker or later, which
2850 // automatically synthesizes these stubs.
2851 OpFlags = X86II::MO_DARWIN_STUB;
2852 } else if (Subtarget->isPICStyleRIPRel() &&
2853 isa<Function>(GV) &&
2854 cast<Function>(GV)->getAttributes().
2855 hasAttribute(AttributeSet::FunctionIndex,
2856 Attribute::NonLazyBind)) {
2857 // If the function is marked as non-lazy, generate an indirect call
2858 // which loads from the GOT directly. This avoids runtime overhead
2859 // at the cost of eager binding (and one extra byte of encoding).
2860 OpFlags = X86II::MO_GOTPCREL;
2861 WrapperKind = X86ISD::WrapperRIP;
2865 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2866 G->getOffset(), OpFlags);
2868 // Add a wrapper if needed.
2869 if (WrapperKind != ISD::DELETED_NODE)
2870 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2871 // Add extra indirection if needed.
2873 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2874 MachinePointerInfo::getGOT(),
2875 false, false, false, 0);
2877 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2878 unsigned char OpFlags = 0;
2880 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2881 // external symbols should go through the PLT.
2882 if (Subtarget->isTargetELF() &&
2883 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2884 OpFlags = X86II::MO_PLT;
2885 } else if (Subtarget->isPICStyleStubAny() &&
2886 (!Subtarget->getTargetTriple().isMacOSX() ||
2887 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2888 // PC-relative references to external symbols should go through $stub,
2889 // unless we're building with the leopard linker or later, which
2890 // automatically synthesizes these stubs.
2891 OpFlags = X86II::MO_DARWIN_STUB;
2894 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2898 // Returns a chain & a flag for retval copy to use.
2899 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2900 SmallVector<SDValue, 8> Ops;
2902 if (!IsSibcall && isTailCall) {
2903 Chain = DAG.getCALLSEQ_END(Chain,
2904 DAG.getIntPtrConstant(NumBytesToPop, true),
2905 DAG.getIntPtrConstant(0, true), InFlag, dl);
2906 InFlag = Chain.getValue(1);
2909 Ops.push_back(Chain);
2910 Ops.push_back(Callee);
2913 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2915 // Add argument registers to the end of the list so that they are known live
2917 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2918 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2919 RegsToPass[i].second.getValueType()));
2921 // Add a register mask operand representing the call-preserved registers.
2922 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2923 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2924 assert(Mask && "Missing call preserved mask for calling convention");
2925 Ops.push_back(DAG.getRegisterMask(Mask));
2927 if (InFlag.getNode())
2928 Ops.push_back(InFlag);
2932 //// If this is the first return lowered for this function, add the regs
2933 //// to the liveout set for the function.
2934 // This isn't right, although it's probably harmless on x86; liveouts
2935 // should be computed from returns not tail calls. Consider a void
2936 // function making a tail call to a function returning int.
2937 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
2940 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2941 InFlag = Chain.getValue(1);
2943 // Create the CALLSEQ_END node.
2944 unsigned NumBytesForCalleeToPop;
2945 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2946 getTargetMachine().Options.GuaranteedTailCallOpt))
2947 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
2948 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2949 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2950 SR == StackStructReturn)
2951 // If this is a call to a struct-return function, the callee
2952 // pops the hidden struct pointer, so we have to push it back.
2953 // This is common for Darwin/X86, Linux & Mingw32 targets.
2954 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2955 NumBytesForCalleeToPop = 4;
2957 NumBytesForCalleeToPop = 0; // Callee pops nothing.
2959 // Returns a flag for retval copy to use.
2961 Chain = DAG.getCALLSEQ_END(Chain,
2962 DAG.getIntPtrConstant(NumBytesToPop, true),
2963 DAG.getIntPtrConstant(NumBytesForCalleeToPop,
2966 InFlag = Chain.getValue(1);
2969 // Handle result values, copying them out of physregs into vregs that we
2971 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2972 Ins, dl, DAG, InVals);
2975 //===----------------------------------------------------------------------===//
2976 // Fast Calling Convention (tail call) implementation
2977 //===----------------------------------------------------------------------===//
2979 // Like std call, callee cleans arguments, convention except that ECX is
2980 // reserved for storing the tail called function address. Only 2 registers are
2981 // free for argument passing (inreg). Tail call optimization is performed
2983 // * tailcallopt is enabled
2984 // * caller/callee are fastcc
2985 // On X86_64 architecture with GOT-style position independent code only local
2986 // (within module) calls are supported at the moment.
2987 // To keep the stack aligned according to platform abi the function
2988 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2989 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2990 // If a tail called function callee has more arguments than the caller the
2991 // caller needs to make sure that there is room to move the RETADDR to. This is
2992 // achieved by reserving an area the size of the argument delta right after the
2993 // original REtADDR, but before the saved framepointer or the spilled registers
2994 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3006 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3007 /// for a 16 byte align requirement.
3009 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3010 SelectionDAG& DAG) const {
3011 MachineFunction &MF = DAG.getMachineFunction();
3012 const TargetMachine &TM = MF.getTarget();
3013 const X86RegisterInfo *RegInfo =
3014 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3015 const TargetFrameLowering &TFI = *TM.getFrameLowering();
3016 unsigned StackAlignment = TFI.getStackAlignment();
3017 uint64_t AlignMask = StackAlignment - 1;
3018 int64_t Offset = StackSize;
3019 unsigned SlotSize = RegInfo->getSlotSize();
3020 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3021 // Number smaller than 12 so just add the difference.
3022 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3024 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3025 Offset = ((~AlignMask) & Offset) + StackAlignment +
3026 (StackAlignment-SlotSize);
3031 /// MatchingStackOffset - Return true if the given stack call argument is
3032 /// already available in the same position (relatively) of the caller's
3033 /// incoming argument stack.
3035 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3036 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3037 const X86InstrInfo *TII) {
3038 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3040 if (Arg.getOpcode() == ISD::CopyFromReg) {
3041 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3042 if (!TargetRegisterInfo::isVirtualRegister(VR))
3044 MachineInstr *Def = MRI->getVRegDef(VR);
3047 if (!Flags.isByVal()) {
3048 if (!TII->isLoadFromStackSlot(Def, FI))
3051 unsigned Opcode = Def->getOpcode();
3052 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3053 Def->getOperand(1).isFI()) {
3054 FI = Def->getOperand(1).getIndex();
3055 Bytes = Flags.getByValSize();
3059 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3060 if (Flags.isByVal())
3061 // ByVal argument is passed in as a pointer but it's now being
3062 // dereferenced. e.g.
3063 // define @foo(%struct.X* %A) {
3064 // tail call @bar(%struct.X* byval %A)
3067 SDValue Ptr = Ld->getBasePtr();
3068 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3071 FI = FINode->getIndex();
3072 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3073 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3074 FI = FINode->getIndex();
3075 Bytes = Flags.getByValSize();
3079 assert(FI != INT_MAX);
3080 if (!MFI->isFixedObjectIndex(FI))
3082 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3085 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3086 /// for tail call optimization. Targets which want to do tail call
3087 /// optimization should implement this function.
3089 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3090 CallingConv::ID CalleeCC,
3092 bool isCalleeStructRet,
3093 bool isCallerStructRet,
3095 const SmallVectorImpl<ISD::OutputArg> &Outs,
3096 const SmallVectorImpl<SDValue> &OutVals,
3097 const SmallVectorImpl<ISD::InputArg> &Ins,
3098 SelectionDAG &DAG) const {
3099 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3102 // If -tailcallopt is specified, make fastcc functions tail-callable.
3103 const MachineFunction &MF = DAG.getMachineFunction();
3104 const Function *CallerF = MF.getFunction();
3106 // If the function return type is x86_fp80 and the callee return type is not,
3107 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3108 // perform a tailcall optimization here.
3109 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3112 CallingConv::ID CallerCC = CallerF->getCallingConv();
3113 bool CCMatch = CallerCC == CalleeCC;
3114 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3115 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3117 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3118 if (IsTailCallConvention(CalleeCC) && CCMatch)
3123 // Look for obvious safe cases to perform tail call optimization that do not
3124 // require ABI changes. This is what gcc calls sibcall.
3126 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3127 // emit a special epilogue.
3128 const X86RegisterInfo *RegInfo =
3129 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3130 if (RegInfo->needsStackRealignment(MF))
3133 // Also avoid sibcall optimization if either caller or callee uses struct
3134 // return semantics.
3135 if (isCalleeStructRet || isCallerStructRet)
3138 // An stdcall/thiscall caller is expected to clean up its arguments; the
3139 // callee isn't going to do that.
3140 // FIXME: this is more restrictive than needed. We could produce a tailcall
3141 // when the stack adjustment matches. For example, with a thiscall that takes
3142 // only one argument.
3143 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3144 CallerCC == CallingConv::X86_ThisCall))
3147 // Do not sibcall optimize vararg calls unless all arguments are passed via
3149 if (isVarArg && !Outs.empty()) {
3151 // Optimizing for varargs on Win64 is unlikely to be safe without
3152 // additional testing.
3153 if (IsCalleeWin64 || IsCallerWin64)
3156 SmallVector<CCValAssign, 16> ArgLocs;
3157 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3158 getTargetMachine(), ArgLocs, *DAG.getContext());
3160 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3161 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3162 if (!ArgLocs[i].isRegLoc())
3166 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3167 // stack. Therefore, if it's not used by the call it is not safe to optimize
3168 // this into a sibcall.
3169 bool Unused = false;
3170 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3177 SmallVector<CCValAssign, 16> RVLocs;
3178 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3179 getTargetMachine(), RVLocs, *DAG.getContext());
3180 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3181 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3182 CCValAssign &VA = RVLocs[i];
3183 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3188 // If the calling conventions do not match, then we'd better make sure the
3189 // results are returned in the same way as what the caller expects.
3191 SmallVector<CCValAssign, 16> RVLocs1;
3192 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3193 getTargetMachine(), RVLocs1, *DAG.getContext());
3194 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3196 SmallVector<CCValAssign, 16> RVLocs2;
3197 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3198 getTargetMachine(), RVLocs2, *DAG.getContext());
3199 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3201 if (RVLocs1.size() != RVLocs2.size())
3203 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3204 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3206 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3208 if (RVLocs1[i].isRegLoc()) {
3209 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3212 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3218 // If the callee takes no arguments then go on to check the results of the
3220 if (!Outs.empty()) {
3221 // Check if stack adjustment is needed. For now, do not do this if any
3222 // argument is passed on the stack.
3223 SmallVector<CCValAssign, 16> ArgLocs;
3224 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3225 getTargetMachine(), ArgLocs, *DAG.getContext());
3227 // Allocate shadow area for Win64
3229 CCInfo.AllocateStack(32, 8);
3231 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3232 if (CCInfo.getNextStackOffset()) {
3233 MachineFunction &MF = DAG.getMachineFunction();
3234 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3237 // Check if the arguments are already laid out in the right way as
3238 // the caller's fixed stack objects.
3239 MachineFrameInfo *MFI = MF.getFrameInfo();
3240 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3241 const X86InstrInfo *TII =
3242 ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3243 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3244 CCValAssign &VA = ArgLocs[i];
3245 SDValue Arg = OutVals[i];
3246 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3247 if (VA.getLocInfo() == CCValAssign::Indirect)
3249 if (!VA.isRegLoc()) {
3250 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3257 // If the tailcall address may be in a register, then make sure it's
3258 // possible to register allocate for it. In 32-bit, the call address can
3259 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3260 // callee-saved registers are restored. These happen to be the same
3261 // registers used to pass 'inreg' arguments so watch out for those.
3262 if (!Subtarget->is64Bit() &&
3263 ((!isa<GlobalAddressSDNode>(Callee) &&
3264 !isa<ExternalSymbolSDNode>(Callee)) ||
3265 getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3266 unsigned NumInRegs = 0;
3267 // In PIC we need an extra register to formulate the address computation
3269 unsigned MaxInRegs =
3270 (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3272 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3273 CCValAssign &VA = ArgLocs[i];
3276 unsigned Reg = VA.getLocReg();
3279 case X86::EAX: case X86::EDX: case X86::ECX:
3280 if (++NumInRegs == MaxInRegs)
3292 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3293 const TargetLibraryInfo *libInfo) const {
3294 return X86::createFastISel(funcInfo, libInfo);
3297 //===----------------------------------------------------------------------===//
3298 // Other Lowering Hooks
3299 //===----------------------------------------------------------------------===//
3301 static bool MayFoldLoad(SDValue Op) {
3302 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3305 static bool MayFoldIntoStore(SDValue Op) {
3306 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3309 static bool isTargetShuffle(unsigned Opcode) {
3311 default: return false;
3312 case X86ISD::PSHUFD:
3313 case X86ISD::PSHUFHW:
3314 case X86ISD::PSHUFLW:
3316 case X86ISD::PALIGNR:
3317 case X86ISD::MOVLHPS:
3318 case X86ISD::MOVLHPD:
3319 case X86ISD::MOVHLPS:
3320 case X86ISD::MOVLPS:
3321 case X86ISD::MOVLPD:
3322 case X86ISD::MOVSHDUP:
3323 case X86ISD::MOVSLDUP:
3324 case X86ISD::MOVDDUP:
3327 case X86ISD::UNPCKL:
3328 case X86ISD::UNPCKH:
3329 case X86ISD::VPERMILP:
3330 case X86ISD::VPERM2X128:
3331 case X86ISD::VPERMI:
3336 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3337 SDValue V1, SelectionDAG &DAG) {
3339 default: llvm_unreachable("Unknown x86 shuffle node");
3340 case X86ISD::MOVSHDUP:
3341 case X86ISD::MOVSLDUP:
3342 case X86ISD::MOVDDUP:
3343 return DAG.getNode(Opc, dl, VT, V1);
3347 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3348 SDValue V1, unsigned TargetMask,
3349 SelectionDAG &DAG) {
3351 default: llvm_unreachable("Unknown x86 shuffle node");
3352 case X86ISD::PSHUFD:
3353 case X86ISD::PSHUFHW:
3354 case X86ISD::PSHUFLW:
3355 case X86ISD::VPERMILP:
3356 case X86ISD::VPERMI:
3357 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3361 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3362 SDValue V1, SDValue V2, unsigned TargetMask,
3363 SelectionDAG &DAG) {
3365 default: llvm_unreachable("Unknown x86 shuffle node");
3366 case X86ISD::PALIGNR:
3368 case X86ISD::VPERM2X128:
3369 return DAG.getNode(Opc, dl, VT, V1, V2,
3370 DAG.getConstant(TargetMask, MVT::i8));
3374 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3375 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3377 default: llvm_unreachable("Unknown x86 shuffle node");
3378 case X86ISD::MOVLHPS:
3379 case X86ISD::MOVLHPD:
3380 case X86ISD::MOVHLPS:
3381 case X86ISD::MOVLPS:
3382 case X86ISD::MOVLPD:
3385 case X86ISD::UNPCKL:
3386 case X86ISD::UNPCKH:
3387 return DAG.getNode(Opc, dl, VT, V1, V2);
3391 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3392 MachineFunction &MF = DAG.getMachineFunction();
3393 const X86RegisterInfo *RegInfo =
3394 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3395 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3396 int ReturnAddrIndex = FuncInfo->getRAIndex();
3398 if (ReturnAddrIndex == 0) {
3399 // Set up a frame object for the return address.
3400 unsigned SlotSize = RegInfo->getSlotSize();
3401 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3404 FuncInfo->setRAIndex(ReturnAddrIndex);
3407 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3410 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3411 bool hasSymbolicDisplacement) {
3412 // Offset should fit into 32 bit immediate field.
3413 if (!isInt<32>(Offset))
3416 // If we don't have a symbolic displacement - we don't have any extra
3418 if (!hasSymbolicDisplacement)
3421 // FIXME: Some tweaks might be needed for medium code model.
3422 if (M != CodeModel::Small && M != CodeModel::Kernel)
3425 // For small code model we assume that latest object is 16MB before end of 31
3426 // bits boundary. We may also accept pretty large negative constants knowing
3427 // that all objects are in the positive half of address space.
3428 if (M == CodeModel::Small && Offset < 16*1024*1024)
3431 // For kernel code model we know that all object resist in the negative half
3432 // of 32bits address space. We may not accept negative offsets, since they may
3433 // be just off and we may accept pretty large positive ones.
3434 if (M == CodeModel::Kernel && Offset > 0)
3440 /// isCalleePop - Determines whether the callee is required to pop its
3441 /// own arguments. Callee pop is necessary to support tail calls.
3442 bool X86::isCalleePop(CallingConv::ID CallingConv,
3443 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3447 switch (CallingConv) {
3450 case CallingConv::X86_StdCall:
3452 case CallingConv::X86_FastCall:
3454 case CallingConv::X86_ThisCall:
3456 case CallingConv::Fast:
3458 case CallingConv::GHC:
3460 case CallingConv::HiPE:
3465 /// \brief Return true if the condition is an unsigned comparison operation.
3466 static bool isX86CCUnsigned(unsigned X86CC) {
3468 default: llvm_unreachable("Invalid integer condition!");
3469 case X86::COND_E: return true;
3470 case X86::COND_G: return false;
3471 case X86::COND_GE: return false;
3472 case X86::COND_L: return false;
3473 case X86::COND_LE: return false;
3474 case X86::COND_NE: return true;
3475 case X86::COND_B: return true;
3476 case X86::COND_A: return true;
3477 case X86::COND_BE: return true;
3478 case X86::COND_AE: return true;
3480 llvm_unreachable("covered switch fell through?!");
3483 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3484 /// specific condition code, returning the condition code and the LHS/RHS of the
3485 /// comparison to make.
3486 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3487 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3489 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3490 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3491 // X > -1 -> X == 0, jump !sign.
3492 RHS = DAG.getConstant(0, RHS.getValueType());
3493 return X86::COND_NS;
3495 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3496 // X < 0 -> X == 0, jump on sign.
3499 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3501 RHS = DAG.getConstant(0, RHS.getValueType());
3502 return X86::COND_LE;
3506 switch (SetCCOpcode) {
3507 default: llvm_unreachable("Invalid integer condition!");
3508 case ISD::SETEQ: return X86::COND_E;
3509 case ISD::SETGT: return X86::COND_G;
3510 case ISD::SETGE: return X86::COND_GE;
3511 case ISD::SETLT: return X86::COND_L;
3512 case ISD::SETLE: return X86::COND_LE;
3513 case ISD::SETNE: return X86::COND_NE;
3514 case ISD::SETULT: return X86::COND_B;
3515 case ISD::SETUGT: return X86::COND_A;
3516 case ISD::SETULE: return X86::COND_BE;
3517 case ISD::SETUGE: return X86::COND_AE;
3521 // First determine if it is required or is profitable to flip the operands.
3523 // If LHS is a foldable load, but RHS is not, flip the condition.
3524 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3525 !ISD::isNON_EXTLoad(RHS.getNode())) {
3526 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3527 std::swap(LHS, RHS);
3530 switch (SetCCOpcode) {
3536 std::swap(LHS, RHS);
3540 // On a floating point condition, the flags are set as follows:
3542 // 0 | 0 | 0 | X > Y
3543 // 0 | 0 | 1 | X < Y
3544 // 1 | 0 | 0 | X == Y
3545 // 1 | 1 | 1 | unordered
3546 switch (SetCCOpcode) {
3547 default: llvm_unreachable("Condcode should be pre-legalized away");
3549 case ISD::SETEQ: return X86::COND_E;
3550 case ISD::SETOLT: // flipped
3552 case ISD::SETGT: return X86::COND_A;
3553 case ISD::SETOLE: // flipped
3555 case ISD::SETGE: return X86::COND_AE;
3556 case ISD::SETUGT: // flipped
3558 case ISD::SETLT: return X86::COND_B;
3559 case ISD::SETUGE: // flipped
3561 case ISD::SETLE: return X86::COND_BE;
3563 case ISD::SETNE: return X86::COND_NE;
3564 case ISD::SETUO: return X86::COND_P;
3565 case ISD::SETO: return X86::COND_NP;
3567 case ISD::SETUNE: return X86::COND_INVALID;
3571 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3572 /// code. Current x86 isa includes the following FP cmov instructions:
3573 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3574 static bool hasFPCMov(unsigned X86CC) {
3590 /// isFPImmLegal - Returns true if the target can instruction select the
3591 /// specified FP immediate natively. If false, the legalizer will
3592 /// materialize the FP immediate as a load from a constant pool.
3593 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3594 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3595 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3601 /// \brief Returns true if it is beneficial to convert a load of a constant
3602 /// to just the constant itself.
3603 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3605 assert(Ty->isIntegerTy());
3607 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3608 if (BitSize == 0 || BitSize > 64)
3613 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3614 /// the specified range (L, H].
3615 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3616 return (Val < 0) || (Val >= Low && Val < Hi);
3619 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3620 /// specified value.
3621 static bool isUndefOrEqual(int Val, int CmpVal) {
3622 return (Val < 0 || Val == CmpVal);
3625 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3626 /// from position Pos and ending in Pos+Size, falls within the specified
3627 /// sequential range (L, L+Pos]. or is undef.
3628 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3629 unsigned Pos, unsigned Size, int Low) {
3630 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3631 if (!isUndefOrEqual(Mask[i], Low))
3636 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3637 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3638 /// the second operand.
3639 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3640 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3641 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3642 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3643 return (Mask[0] < 2 && Mask[1] < 2);
3647 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3648 /// is suitable for input to PSHUFHW.
3649 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3650 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3653 // Lower quadword copied in order or undef.
3654 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3657 // Upper quadword shuffled.
3658 for (unsigned i = 4; i != 8; ++i)
3659 if (!isUndefOrInRange(Mask[i], 4, 8))
3662 if (VT == MVT::v16i16) {
3663 // Lower quadword copied in order or undef.
3664 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3667 // Upper quadword shuffled.
3668 for (unsigned i = 12; i != 16; ++i)
3669 if (!isUndefOrInRange(Mask[i], 12, 16))
3676 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3677 /// is suitable for input to PSHUFLW.
3678 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3679 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3682 // Upper quadword copied in order.
3683 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3686 // Lower quadword shuffled.
3687 for (unsigned i = 0; i != 4; ++i)
3688 if (!isUndefOrInRange(Mask[i], 0, 4))
3691 if (VT == MVT::v16i16) {
3692 // Upper quadword copied in order.
3693 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3696 // Lower quadword shuffled.
3697 for (unsigned i = 8; i != 12; ++i)
3698 if (!isUndefOrInRange(Mask[i], 8, 12))
3705 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3706 /// is suitable for input to PALIGNR.
3707 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3708 const X86Subtarget *Subtarget) {
3709 if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3710 (VT.is256BitVector() && !Subtarget->hasInt256()))
3713 unsigned NumElts = VT.getVectorNumElements();
3714 unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3715 unsigned NumLaneElts = NumElts/NumLanes;
3717 // Do not handle 64-bit element shuffles with palignr.
3718 if (NumLaneElts == 2)
3721 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3723 for (i = 0; i != NumLaneElts; ++i) {
3728 // Lane is all undef, go to next lane
3729 if (i == NumLaneElts)
3732 int Start = Mask[i+l];
3734 // Make sure its in this lane in one of the sources
3735 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3736 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3739 // If not lane 0, then we must match lane 0
3740 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3743 // Correct second source to be contiguous with first source
3744 if (Start >= (int)NumElts)
3745 Start -= NumElts - NumLaneElts;
3747 // Make sure we're shifting in the right direction.
3748 if (Start <= (int)(i+l))
3753 // Check the rest of the elements to see if they are consecutive.
3754 for (++i; i != NumLaneElts; ++i) {
3755 int Idx = Mask[i+l];
3757 // Make sure its in this lane
3758 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3759 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3762 // If not lane 0, then we must match lane 0
3763 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3766 if (Idx >= (int)NumElts)
3767 Idx -= NumElts - NumLaneElts;
3769 if (!isUndefOrEqual(Idx, Start+i))
3778 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3779 /// the two vector operands have swapped position.
3780 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3781 unsigned NumElems) {
3782 for (unsigned i = 0; i != NumElems; ++i) {
3786 else if (idx < (int)NumElems)
3787 Mask[i] = idx + NumElems;
3789 Mask[i] = idx - NumElems;
3793 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3794 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3795 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3796 /// reverse of what x86 shuffles want.
3797 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3799 unsigned NumElems = VT.getVectorNumElements();
3800 unsigned NumLanes = VT.getSizeInBits()/128;
3801 unsigned NumLaneElems = NumElems/NumLanes;
3803 if (NumLaneElems != 2 && NumLaneElems != 4)
3806 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3807 bool symetricMaskRequired =
3808 (VT.getSizeInBits() >= 256) && (EltSize == 32);
3810 // VSHUFPSY divides the resulting vector into 4 chunks.
3811 // The sources are also splitted into 4 chunks, and each destination
3812 // chunk must come from a different source chunk.
3814 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3815 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3817 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3818 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3820 // VSHUFPDY divides the resulting vector into 4 chunks.
3821 // The sources are also splitted into 4 chunks, and each destination
3822 // chunk must come from a different source chunk.
3824 // SRC1 => X3 X2 X1 X0
3825 // SRC2 => Y3 Y2 Y1 Y0
3827 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3829 SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3830 unsigned HalfLaneElems = NumLaneElems/2;
3831 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3832 for (unsigned i = 0; i != NumLaneElems; ++i) {
3833 int Idx = Mask[i+l];
3834 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3835 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3837 // For VSHUFPSY, the mask of the second half must be the same as the
3838 // first but with the appropriate offsets. This works in the same way as
3839 // VPERMILPS works with masks.
3840 if (!symetricMaskRequired || Idx < 0)
3842 if (MaskVal[i] < 0) {
3843 MaskVal[i] = Idx - l;
3846 if ((signed)(Idx - l) != MaskVal[i])
3854 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3855 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3856 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3857 if (!VT.is128BitVector())
3860 unsigned NumElems = VT.getVectorNumElements();
3865 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3866 return isUndefOrEqual(Mask[0], 6) &&
3867 isUndefOrEqual(Mask[1], 7) &&
3868 isUndefOrEqual(Mask[2], 2) &&
3869 isUndefOrEqual(Mask[3], 3);
3872 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3873 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3875 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3876 if (!VT.is128BitVector())
3879 unsigned NumElems = VT.getVectorNumElements();
3884 return isUndefOrEqual(Mask[0], 2) &&
3885 isUndefOrEqual(Mask[1], 3) &&
3886 isUndefOrEqual(Mask[2], 2) &&
3887 isUndefOrEqual(Mask[3], 3);
3890 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3891 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3892 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3893 if (!VT.is128BitVector())
3896 unsigned NumElems = VT.getVectorNumElements();
3898 if (NumElems != 2 && NumElems != 4)
3901 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3902 if (!isUndefOrEqual(Mask[i], i + NumElems))
3905 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3906 if (!isUndefOrEqual(Mask[i], i))
3912 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3913 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3914 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3915 if (!VT.is128BitVector())
3918 unsigned NumElems = VT.getVectorNumElements();
3920 if (NumElems != 2 && NumElems != 4)
3923 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3924 if (!isUndefOrEqual(Mask[i], i))
3927 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3928 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3934 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
3935 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
3936 /// i. e: If all but one element come from the same vector.
3937 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
3938 // TODO: Deal with AVX's VINSERTPS
3939 if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
3942 unsigned CorrectPosV1 = 0;
3943 unsigned CorrectPosV2 = 0;
3944 for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i)
3947 else if (Mask[i] == i + 4)
3950 if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
3951 // We have 3 elements from one vector, and one from another.
3958 // Some special combinations that can be optimized.
3961 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3962 SelectionDAG &DAG) {
3963 MVT VT = SVOp->getSimpleValueType(0);
3966 if (VT != MVT::v8i32 && VT != MVT::v8f32)
3969 ArrayRef<int> Mask = SVOp->getMask();
3971 // These are the special masks that may be optimized.
3972 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3973 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
3974 bool MatchEvenMask = true;
3975 bool MatchOddMask = true;
3976 for (int i=0; i<8; ++i) {
3977 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3978 MatchEvenMask = false;
3979 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3980 MatchOddMask = false;
3983 if (!MatchEvenMask && !MatchOddMask)
3986 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3988 SDValue Op0 = SVOp->getOperand(0);
3989 SDValue Op1 = SVOp->getOperand(1);
3991 if (MatchEvenMask) {
3992 // Shift the second operand right to 32 bits.
3993 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3994 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3996 // Shift the first operand left to 32 bits.
3997 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3998 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4000 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4001 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4004 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4005 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4006 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4007 bool HasInt256, bool V2IsSplat = false) {
4009 assert(VT.getSizeInBits() >= 128 &&
4010 "Unsupported vector type for unpckl");
4012 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4014 unsigned NumOf256BitLanes;
4015 unsigned NumElts = VT.getVectorNumElements();
4016 if (VT.is256BitVector()) {
4017 if (NumElts != 4 && NumElts != 8 &&
4018 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4021 NumOf256BitLanes = 1;
4022 } else if (VT.is512BitVector()) {
4023 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4024 "Unsupported vector type for unpckh");
4026 NumOf256BitLanes = 2;
4029 NumOf256BitLanes = 1;
4032 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4033 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4035 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4036 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4037 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4038 int BitI = Mask[l256*NumEltsInStride+l+i];
4039 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4040 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4042 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4044 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4052 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4053 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4054 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4055 bool HasInt256, bool V2IsSplat = false) {
4056 assert(VT.getSizeInBits() >= 128 &&
4057 "Unsupported vector type for unpckh");
4059 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4061 unsigned NumOf256BitLanes;
4062 unsigned NumElts = VT.getVectorNumElements();
4063 if (VT.is256BitVector()) {
4064 if (NumElts != 4 && NumElts != 8 &&
4065 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4068 NumOf256BitLanes = 1;
4069 } else if (VT.is512BitVector()) {
4070 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4071 "Unsupported vector type for unpckh");
4073 NumOf256BitLanes = 2;
4076 NumOf256BitLanes = 1;
4079 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4080 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4082 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4083 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4084 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4085 int BitI = Mask[l256*NumEltsInStride+l+i];
4086 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4087 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4089 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4091 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4099 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4100 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4102 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4103 unsigned NumElts = VT.getVectorNumElements();
4104 bool Is256BitVec = VT.is256BitVector();
4106 if (VT.is512BitVector())
4108 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4109 "Unsupported vector type for unpckh");
4111 if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4112 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4115 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4116 // FIXME: Need a better way to get rid of this, there's no latency difference
4117 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4118 // the former later. We should also remove the "_undef" special mask.
4119 if (NumElts == 4 && Is256BitVec)
4122 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4123 // independently on 128-bit lanes.
4124 unsigned NumLanes = VT.getSizeInBits()/128;
4125 unsigned NumLaneElts = NumElts/NumLanes;
4127 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4128 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4129 int BitI = Mask[l+i];
4130 int BitI1 = Mask[l+i+1];
4132 if (!isUndefOrEqual(BitI, j))
4134 if (!isUndefOrEqual(BitI1, j))
4142 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4143 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4145 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4146 unsigned NumElts = VT.getVectorNumElements();
4148 if (VT.is512BitVector())
4151 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4152 "Unsupported vector type for unpckh");
4154 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4155 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4158 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4159 // independently on 128-bit lanes.
4160 unsigned NumLanes = VT.getSizeInBits()/128;
4161 unsigned NumLaneElts = NumElts/NumLanes;
4163 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4164 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4165 int BitI = Mask[l+i];
4166 int BitI1 = Mask[l+i+1];
4167 if (!isUndefOrEqual(BitI, j))
4169 if (!isUndefOrEqual(BitI1, j))
4176 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4177 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4178 /// MOVSD, and MOVD, i.e. setting the lowest element.
4179 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4180 if (VT.getVectorElementType().getSizeInBits() < 32)
4182 if (!VT.is128BitVector())
4185 unsigned NumElts = VT.getVectorNumElements();
4187 if (!isUndefOrEqual(Mask[0], NumElts))
4190 for (unsigned i = 1; i != NumElts; ++i)
4191 if (!isUndefOrEqual(Mask[i], i))
4197 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4198 /// as permutations between 128-bit chunks or halves. As an example: this
4200 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4201 /// The first half comes from the second half of V1 and the second half from the
4202 /// the second half of V2.
4203 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4204 if (!HasFp256 || !VT.is256BitVector())
4207 // The shuffle result is divided into half A and half B. In total the two
4208 // sources have 4 halves, namely: C, D, E, F. The final values of A and
4209 // B must come from C, D, E or F.
4210 unsigned HalfSize = VT.getVectorNumElements()/2;
4211 bool MatchA = false, MatchB = false;
4213 // Check if A comes from one of C, D, E, F.
4214 for (unsigned Half = 0; Half != 4; ++Half) {
4215 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4221 // Check if B comes from one of C, D, E, F.
4222 for (unsigned Half = 0; Half != 4; ++Half) {
4223 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4229 return MatchA && MatchB;
4232 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4233 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4234 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4235 MVT VT = SVOp->getSimpleValueType(0);
4237 unsigned HalfSize = VT.getVectorNumElements()/2;
4239 unsigned FstHalf = 0, SndHalf = 0;
4240 for (unsigned i = 0; i < HalfSize; ++i) {
4241 if (SVOp->getMaskElt(i) > 0) {
4242 FstHalf = SVOp->getMaskElt(i)/HalfSize;
4246 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4247 if (SVOp->getMaskElt(i) > 0) {
4248 SndHalf = SVOp->getMaskElt(i)/HalfSize;
4253 return (FstHalf | (SndHalf << 4));
4256 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4257 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4258 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4262 unsigned NumElts = VT.getVectorNumElements();
4264 if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4265 for (unsigned i = 0; i != NumElts; ++i) {
4268 Imm8 |= Mask[i] << (i*2);
4273 unsigned LaneSize = 4;
4274 SmallVector<int, 4> MaskVal(LaneSize, -1);
4276 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4277 for (unsigned i = 0; i != LaneSize; ++i) {
4278 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4282 if (MaskVal[i] < 0) {
4283 MaskVal[i] = Mask[i+l] - l;
4284 Imm8 |= MaskVal[i] << (i*2);
4287 if (Mask[i+l] != (signed)(MaskVal[i]+l))
4294 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4295 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4296 /// Note that VPERMIL mask matching is different depending whether theunderlying
4297 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4298 /// to the same elements of the low, but to the higher half of the source.
4299 /// In VPERMILPD the two lanes could be shuffled independently of each other
4300 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4301 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4302 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4303 if (VT.getSizeInBits() < 256 || EltSize < 32)
4305 bool symetricMaskRequired = (EltSize == 32);
4306 unsigned NumElts = VT.getVectorNumElements();
4308 unsigned NumLanes = VT.getSizeInBits()/128;
4309 unsigned LaneSize = NumElts/NumLanes;
4310 // 2 or 4 elements in one lane
4312 SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4313 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4314 for (unsigned i = 0; i != LaneSize; ++i) {
4315 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4317 if (symetricMaskRequired) {
4318 if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4319 ExpectedMaskVal[i] = Mask[i+l] - l;
4322 if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4330 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4331 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
4332 /// element of vector 2 and the other elements to come from vector 1 in order.
4333 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4334 bool V2IsSplat = false, bool V2IsUndef = false) {
4335 if (!VT.is128BitVector())
4338 unsigned NumOps = VT.getVectorNumElements();
4339 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4342 if (!isUndefOrEqual(Mask[0], 0))
4345 for (unsigned i = 1; i != NumOps; ++i)
4346 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4347 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4348 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4354 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4355 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4356 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4357 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4358 const X86Subtarget *Subtarget) {
4359 if (!Subtarget->hasSSE3())
4362 unsigned NumElems = VT.getVectorNumElements();
4364 if ((VT.is128BitVector() && NumElems != 4) ||
4365 (VT.is256BitVector() && NumElems != 8) ||
4366 (VT.is512BitVector() && NumElems != 16))
4369 // "i+1" is the value the indexed mask element must have
4370 for (unsigned i = 0; i != NumElems; i += 2)
4371 if (!isUndefOrEqual(Mask[i], i+1) ||
4372 !isUndefOrEqual(Mask[i+1], i+1))
4378 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4379 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4380 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4381 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4382 const X86Subtarget *Subtarget) {
4383 if (!Subtarget->hasSSE3())
4386 unsigned NumElems = VT.getVectorNumElements();
4388 if ((VT.is128BitVector() && NumElems != 4) ||
4389 (VT.is256BitVector() && NumElems != 8) ||
4390 (VT.is512BitVector() && NumElems != 16))
4393 // "i" is the value the indexed mask element must have
4394 for (unsigned i = 0; i != NumElems; i += 2)
4395 if (!isUndefOrEqual(Mask[i], i) ||
4396 !isUndefOrEqual(Mask[i+1], i))
4402 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4403 /// specifies a shuffle of elements that is suitable for input to 256-bit
4404 /// version of MOVDDUP.
4405 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4406 if (!HasFp256 || !VT.is256BitVector())
4409 unsigned NumElts = VT.getVectorNumElements();
4413 for (unsigned i = 0; i != NumElts/2; ++i)
4414 if (!isUndefOrEqual(Mask[i], 0))
4416 for (unsigned i = NumElts/2; i != NumElts; ++i)
4417 if (!isUndefOrEqual(Mask[i], NumElts/2))
4422 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4423 /// specifies a shuffle of elements that is suitable for input to 128-bit
4424 /// version of MOVDDUP.
4425 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4426 if (!VT.is128BitVector())
4429 unsigned e = VT.getVectorNumElements() / 2;
4430 for (unsigned i = 0; i != e; ++i)
4431 if (!isUndefOrEqual(Mask[i], i))
4433 for (unsigned i = 0; i != e; ++i)
4434 if (!isUndefOrEqual(Mask[e+i], i))
4439 /// isVEXTRACTIndex - Return true if the specified
4440 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4441 /// suitable for instruction that extract 128 or 256 bit vectors
4442 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4443 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4444 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4447 // The index should be aligned on a vecWidth-bit boundary.
4449 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4451 MVT VT = N->getSimpleValueType(0);
4452 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4453 bool Result = (Index * ElSize) % vecWidth == 0;
4458 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4459 /// operand specifies a subvector insert that is suitable for input to
4460 /// insertion of 128 or 256-bit subvectors
4461 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4462 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4463 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4465 // The index should be aligned on a vecWidth-bit boundary.
4467 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4469 MVT VT = N->getSimpleValueType(0);
4470 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4471 bool Result = (Index * ElSize) % vecWidth == 0;
4476 bool X86::isVINSERT128Index(SDNode *N) {
4477 return isVINSERTIndex(N, 128);
4480 bool X86::isVINSERT256Index(SDNode *N) {
4481 return isVINSERTIndex(N, 256);
4484 bool X86::isVEXTRACT128Index(SDNode *N) {
4485 return isVEXTRACTIndex(N, 128);
4488 bool X86::isVEXTRACT256Index(SDNode *N) {
4489 return isVEXTRACTIndex(N, 256);
4492 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4493 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4494 /// Handles 128-bit and 256-bit.
4495 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4496 MVT VT = N->getSimpleValueType(0);
4498 assert((VT.getSizeInBits() >= 128) &&
4499 "Unsupported vector type for PSHUF/SHUFP");
4501 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4502 // independently on 128-bit lanes.
4503 unsigned NumElts = VT.getVectorNumElements();
4504 unsigned NumLanes = VT.getSizeInBits()/128;
4505 unsigned NumLaneElts = NumElts/NumLanes;
4507 assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4508 "Only supports 2, 4 or 8 elements per lane");
4510 unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4512 for (unsigned i = 0; i != NumElts; ++i) {
4513 int Elt = N->getMaskElt(i);
4514 if (Elt < 0) continue;
4515 Elt &= NumLaneElts - 1;
4516 unsigned ShAmt = (i << Shift) % 8;
4517 Mask |= Elt << ShAmt;
4523 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4524 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4525 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4526 MVT VT = N->getSimpleValueType(0);
4528 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4529 "Unsupported vector type for PSHUFHW");
4531 unsigned NumElts = VT.getVectorNumElements();
4534 for (unsigned l = 0; l != NumElts; l += 8) {
4535 // 8 nodes per lane, but we only care about the last 4.
4536 for (unsigned i = 0; i < 4; ++i) {
4537 int Elt = N->getMaskElt(l+i+4);
4538 if (Elt < 0) continue;
4539 Elt &= 0x3; // only 2-bits.
4540 Mask |= Elt << (i * 2);
4547 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4548 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4549 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4550 MVT VT = N->getSimpleValueType(0);
4552 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4553 "Unsupported vector type for PSHUFHW");
4555 unsigned NumElts = VT.getVectorNumElements();
4558 for (unsigned l = 0; l != NumElts; l += 8) {
4559 // 8 nodes per lane, but we only care about the first 4.
4560 for (unsigned i = 0; i < 4; ++i) {
4561 int Elt = N->getMaskElt(l+i);
4562 if (Elt < 0) continue;
4563 Elt &= 0x3; // only 2-bits
4564 Mask |= Elt << (i * 2);
4571 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4572 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4573 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4574 MVT VT = SVOp->getSimpleValueType(0);
4575 unsigned EltSize = VT.is512BitVector() ? 1 :
4576 VT.getVectorElementType().getSizeInBits() >> 3;
4578 unsigned NumElts = VT.getVectorNumElements();
4579 unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4580 unsigned NumLaneElts = NumElts/NumLanes;
4584 for (i = 0; i != NumElts; ++i) {
4585 Val = SVOp->getMaskElt(i);
4589 if (Val >= (int)NumElts)
4590 Val -= NumElts - NumLaneElts;
4592 assert(Val - i > 0 && "PALIGNR imm should be positive");
4593 return (Val - i) * EltSize;
4596 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4597 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4598 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4599 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4602 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4604 MVT VecVT = N->getOperand(0).getSimpleValueType();
4605 MVT ElVT = VecVT.getVectorElementType();
4607 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4608 return Index / NumElemsPerChunk;
4611 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4612 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4613 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4614 llvm_unreachable("Illegal insert subvector for VINSERT");
4617 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4619 MVT VecVT = N->getSimpleValueType(0);
4620 MVT ElVT = VecVT.getVectorElementType();
4622 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4623 return Index / NumElemsPerChunk;
4626 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4627 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4628 /// and VINSERTI128 instructions.
4629 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4630 return getExtractVEXTRACTImmediate(N, 128);
4633 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4634 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4635 /// and VINSERTI64x4 instructions.
4636 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4637 return getExtractVEXTRACTImmediate(N, 256);
4640 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4641 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4642 /// and VINSERTI128 instructions.
4643 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4644 return getInsertVINSERTImmediate(N, 128);
4647 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4648 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4649 /// and VINSERTI64x4 instructions.
4650 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4651 return getInsertVINSERTImmediate(N, 256);
4654 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4656 bool X86::isZeroNode(SDValue Elt) {
4657 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4658 return CN->isNullValue();
4659 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4660 return CFP->getValueAPF().isPosZero();
4664 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4665 /// their permute mask.
4666 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4667 SelectionDAG &DAG) {
4668 MVT VT = SVOp->getSimpleValueType(0);
4669 unsigned NumElems = VT.getVectorNumElements();
4670 SmallVector<int, 8> MaskVec;
4672 for (unsigned i = 0; i != NumElems; ++i) {
4673 int Idx = SVOp->getMaskElt(i);
4675 if (Idx < (int)NumElems)
4680 MaskVec.push_back(Idx);
4682 return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4683 SVOp->getOperand(0), &MaskVec[0]);
4686 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4687 /// match movhlps. The lower half elements should come from upper half of
4688 /// V1 (and in order), and the upper half elements should come from the upper
4689 /// half of V2 (and in order).
4690 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4691 if (!VT.is128BitVector())
4693 if (VT.getVectorNumElements() != 4)
4695 for (unsigned i = 0, e = 2; i != e; ++i)
4696 if (!isUndefOrEqual(Mask[i], i+2))
4698 for (unsigned i = 2; i != 4; ++i)
4699 if (!isUndefOrEqual(Mask[i], i+4))
4704 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4705 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4707 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4708 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4710 N = N->getOperand(0).getNode();
4711 if (!ISD::isNON_EXTLoad(N))
4714 *LD = cast<LoadSDNode>(N);
4718 // Test whether the given value is a vector value which will be legalized
4720 static bool WillBeConstantPoolLoad(SDNode *N) {
4721 if (N->getOpcode() != ISD::BUILD_VECTOR)
4724 // Check for any non-constant elements.
4725 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4726 switch (N->getOperand(i).getNode()->getOpcode()) {
4728 case ISD::ConstantFP:
4735 // Vectors of all-zeros and all-ones are materialized with special
4736 // instructions rather than being loaded.
4737 return !ISD::isBuildVectorAllZeros(N) &&
4738 !ISD::isBuildVectorAllOnes(N);
4741 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4742 /// match movlp{s|d}. The lower half elements should come from lower half of
4743 /// V1 (and in order), and the upper half elements should come from the upper
4744 /// half of V2 (and in order). And since V1 will become the source of the
4745 /// MOVLP, it must be either a vector load or a scalar load to vector.
4746 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4747 ArrayRef<int> Mask, MVT VT) {
4748 if (!VT.is128BitVector())
4751 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4753 // Is V2 is a vector load, don't do this transformation. We will try to use
4754 // load folding shufps op.
4755 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4758 unsigned NumElems = VT.getVectorNumElements();
4760 if (NumElems != 2 && NumElems != 4)
4762 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4763 if (!isUndefOrEqual(Mask[i], i))
4765 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4766 if (!isUndefOrEqual(Mask[i], i+NumElems))
4771 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4773 static bool isSplatVector(SDNode *N) {
4774 if (N->getOpcode() != ISD::BUILD_VECTOR)
4777 SDValue SplatValue = N->getOperand(0);
4778 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4779 if (N->getOperand(i) != SplatValue)
4784 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4785 /// to an zero vector.
4786 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4787 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4788 SDValue V1 = N->getOperand(0);
4789 SDValue V2 = N->getOperand(1);
4790 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4791 for (unsigned i = 0; i != NumElems; ++i) {
4792 int Idx = N->getMaskElt(i);
4793 if (Idx >= (int)NumElems) {
4794 unsigned Opc = V2.getOpcode();
4795 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4797 if (Opc != ISD::BUILD_VECTOR ||
4798 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4800 } else if (Idx >= 0) {
4801 unsigned Opc = V1.getOpcode();
4802 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4804 if (Opc != ISD::BUILD_VECTOR ||
4805 !X86::isZeroNode(V1.getOperand(Idx)))
4812 /// getZeroVector - Returns a vector of specified type with all zero elements.
4814 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4815 SelectionDAG &DAG, SDLoc dl) {
4816 assert(VT.isVector() && "Expected a vector type");
4818 // Always build SSE zero vectors as <4 x i32> bitcasted
4819 // to their dest type. This ensures they get CSE'd.
4821 if (VT.is128BitVector()) { // SSE
4822 if (Subtarget->hasSSE2()) { // SSE2
4823 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4824 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4826 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4827 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4829 } else if (VT.is256BitVector()) { // AVX
4830 if (Subtarget->hasInt256()) { // AVX2
4831 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4832 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4833 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4834 array_lengthof(Ops));
4836 // 256-bit logic and arithmetic instructions in AVX are all
4837 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4838 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4839 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4840 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops,
4841 array_lengthof(Ops));
4843 } else if (VT.is512BitVector()) { // AVX-512
4844 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4845 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4846 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4847 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops, 16);
4848 } else if (VT.getScalarType() == MVT::i1) {
4849 assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4850 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4851 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4852 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4853 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
4854 Ops, VT.getVectorNumElements());
4856 llvm_unreachable("Unexpected vector type");
4858 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4861 /// getOnesVector - Returns a vector of specified type with all bits set.
4862 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4863 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4864 /// Then bitcast to their original type, ensuring they get CSE'd.
4865 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4867 assert(VT.isVector() && "Expected a vector type");
4869 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4871 if (VT.is256BitVector()) {
4872 if (HasInt256) { // AVX2
4873 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4874 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4875 array_lengthof(Ops));
4877 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4878 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4880 } else if (VT.is128BitVector()) {
4881 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4883 llvm_unreachable("Unexpected vector type");
4885 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4888 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4889 /// that point to V2 points to its first element.
4890 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4891 for (unsigned i = 0; i != NumElems; ++i) {
4892 if (Mask[i] > (int)NumElems) {
4898 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4899 /// operation of specified width.
4900 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4902 unsigned NumElems = VT.getVectorNumElements();
4903 SmallVector<int, 8> Mask;
4904 Mask.push_back(NumElems);
4905 for (unsigned i = 1; i != NumElems; ++i)
4907 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4910 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4911 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4913 unsigned NumElems = VT.getVectorNumElements();
4914 SmallVector<int, 8> Mask;
4915 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4917 Mask.push_back(i + NumElems);
4919 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4922 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4923 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4925 unsigned NumElems = VT.getVectorNumElements();
4926 SmallVector<int, 8> Mask;
4927 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4928 Mask.push_back(i + Half);
4929 Mask.push_back(i + NumElems + Half);
4931 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4934 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4935 // a generic shuffle instruction because the target has no such instructions.
4936 // Generate shuffles which repeat i16 and i8 several times until they can be
4937 // represented by v4f32 and then be manipulated by target suported shuffles.
4938 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4939 MVT VT = V.getSimpleValueType();
4940 int NumElems = VT.getVectorNumElements();
4943 while (NumElems > 4) {
4944 if (EltNo < NumElems/2) {
4945 V = getUnpackl(DAG, dl, VT, V, V);
4947 V = getUnpackh(DAG, dl, VT, V, V);
4948 EltNo -= NumElems/2;
4955 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4956 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4957 MVT VT = V.getSimpleValueType();
4960 if (VT.is128BitVector()) {
4961 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4962 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4963 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4965 } else if (VT.is256BitVector()) {
4966 // To use VPERMILPS to splat scalars, the second half of indicies must
4967 // refer to the higher part, which is a duplication of the lower one,
4968 // because VPERMILPS can only handle in-lane permutations.
4969 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4970 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4972 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4973 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4976 llvm_unreachable("Vector size not supported");
4978 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4981 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4982 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4983 MVT SrcVT = SV->getSimpleValueType(0);
4984 SDValue V1 = SV->getOperand(0);
4987 int EltNo = SV->getSplatIndex();
4988 int NumElems = SrcVT.getVectorNumElements();
4989 bool Is256BitVec = SrcVT.is256BitVector();
4991 assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4992 "Unknown how to promote splat for type");
4994 // Extract the 128-bit part containing the splat element and update
4995 // the splat element index when it refers to the higher register.
4997 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4998 if (EltNo >= NumElems/2)
4999 EltNo -= NumElems/2;
5002 // All i16 and i8 vector types can't be used directly by a generic shuffle
5003 // instruction because the target has no such instruction. Generate shuffles
5004 // which repeat i16 and i8 several times until they fit in i32, and then can
5005 // be manipulated by target suported shuffles.
5006 MVT EltVT = SrcVT.getVectorElementType();
5007 if (EltVT == MVT::i8 || EltVT == MVT::i16)
5008 V1 = PromoteSplati8i16(V1, DAG, EltNo);
5010 // Recreate the 256-bit vector and place the same 128-bit vector
5011 // into the low and high part. This is necessary because we want
5012 // to use VPERM* to shuffle the vectors
5014 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5017 return getLegalSplat(DAG, V1, EltNo);
5020 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5021 /// vector of zero or undef vector. This produces a shuffle where the low
5022 /// element of V2 is swizzled into the zero/undef vector, landing at element
5023 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
5024 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5026 const X86Subtarget *Subtarget,
5027 SelectionDAG &DAG) {
5028 MVT VT = V2.getSimpleValueType();
5030 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5031 unsigned NumElems = VT.getVectorNumElements();
5032 SmallVector<int, 16> MaskVec;
5033 for (unsigned i = 0; i != NumElems; ++i)
5034 // If this is the insertion idx, put the low elt of V2 here.
5035 MaskVec.push_back(i == Idx ? NumElems : i);
5036 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5039 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5040 /// target specific opcode. Returns true if the Mask could be calculated.
5041 /// Sets IsUnary to true if only uses one source.
5042 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5043 SmallVectorImpl<int> &Mask, bool &IsUnary) {
5044 unsigned NumElems = VT.getVectorNumElements();
5048 switch(N->getOpcode()) {
5050 ImmN = N->getOperand(N->getNumOperands()-1);
5051 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5053 case X86ISD::UNPCKH:
5054 DecodeUNPCKHMask(VT, Mask);
5056 case X86ISD::UNPCKL:
5057 DecodeUNPCKLMask(VT, Mask);
5059 case X86ISD::MOVHLPS:
5060 DecodeMOVHLPSMask(NumElems, Mask);
5062 case X86ISD::MOVLHPS:
5063 DecodeMOVLHPSMask(NumElems, Mask);
5065 case X86ISD::PALIGNR:
5066 ImmN = N->getOperand(N->getNumOperands()-1);
5067 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5069 case X86ISD::PSHUFD:
5070 case X86ISD::VPERMILP:
5071 ImmN = N->getOperand(N->getNumOperands()-1);
5072 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5075 case X86ISD::PSHUFHW:
5076 ImmN = N->getOperand(N->getNumOperands()-1);
5077 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5080 case X86ISD::PSHUFLW:
5081 ImmN = N->getOperand(N->getNumOperands()-1);
5082 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5085 case X86ISD::VPERMI:
5086 ImmN = N->getOperand(N->getNumOperands()-1);
5087 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5091 case X86ISD::MOVSD: {
5092 // The index 0 always comes from the first element of the second source,
5093 // this is why MOVSS and MOVSD are used in the first place. The other
5094 // elements come from the other positions of the first source vector
5095 Mask.push_back(NumElems);
5096 for (unsigned i = 1; i != NumElems; ++i) {
5101 case X86ISD::VPERM2X128:
5102 ImmN = N->getOperand(N->getNumOperands()-1);
5103 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5104 if (Mask.empty()) return false;
5106 case X86ISD::MOVDDUP:
5107 case X86ISD::MOVLHPD:
5108 case X86ISD::MOVLPD:
5109 case X86ISD::MOVLPS:
5110 case X86ISD::MOVSHDUP:
5111 case X86ISD::MOVSLDUP:
5112 // Not yet implemented
5114 default: llvm_unreachable("unknown target shuffle node");
5120 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5121 /// element of the result of the vector shuffle.
5122 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5125 return SDValue(); // Limit search depth.
5127 SDValue V = SDValue(N, 0);
5128 EVT VT = V.getValueType();
5129 unsigned Opcode = V.getOpcode();
5131 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5132 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5133 int Elt = SV->getMaskElt(Index);
5136 return DAG.getUNDEF(VT.getVectorElementType());
5138 unsigned NumElems = VT.getVectorNumElements();
5139 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5140 : SV->getOperand(1);
5141 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5144 // Recurse into target specific vector shuffles to find scalars.
5145 if (isTargetShuffle(Opcode)) {
5146 MVT ShufVT = V.getSimpleValueType();
5147 unsigned NumElems = ShufVT.getVectorNumElements();
5148 SmallVector<int, 16> ShuffleMask;
5151 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5154 int Elt = ShuffleMask[Index];
5156 return DAG.getUNDEF(ShufVT.getVectorElementType());
5158 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5160 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5164 // Actual nodes that may contain scalar elements
5165 if (Opcode == ISD::BITCAST) {
5166 V = V.getOperand(0);
5167 EVT SrcVT = V.getValueType();
5168 unsigned NumElems = VT.getVectorNumElements();
5170 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5174 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5175 return (Index == 0) ? V.getOperand(0)
5176 : DAG.getUNDEF(VT.getVectorElementType());
5178 if (V.getOpcode() == ISD::BUILD_VECTOR)
5179 return V.getOperand(Index);
5184 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5185 /// shuffle operation which come from a consecutively from a zero. The
5186 /// search can start in two different directions, from left or right.
5187 /// We count undefs as zeros until PreferredNum is reached.
5188 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5189 unsigned NumElems, bool ZerosFromLeft,
5191 unsigned PreferredNum = -1U) {
5192 unsigned NumZeros = 0;
5193 for (unsigned i = 0; i != NumElems; ++i) {
5194 unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5195 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5199 if (X86::isZeroNode(Elt))
5201 else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5202 NumZeros = std::min(NumZeros + 1, PreferredNum);
5210 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5211 /// correspond consecutively to elements from one of the vector operands,
5212 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5214 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5215 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5216 unsigned NumElems, unsigned &OpNum) {
5217 bool SeenV1 = false;
5218 bool SeenV2 = false;
5220 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5221 int Idx = SVOp->getMaskElt(i);
5222 // Ignore undef indicies
5226 if (Idx < (int)NumElems)
5231 // Only accept consecutive elements from the same vector
5232 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5236 OpNum = SeenV1 ? 0 : 1;
5240 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5241 /// logical left shift of a vector.
5242 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5243 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5245 SVOp->getSimpleValueType(0).getVectorNumElements();
5246 unsigned NumZeros = getNumOfConsecutiveZeros(
5247 SVOp, NumElems, false /* check zeros from right */, DAG,
5248 SVOp->getMaskElt(0));
5254 // Considering the elements in the mask that are not consecutive zeros,
5255 // check if they consecutively come from only one of the source vectors.
5257 // V1 = {X, A, B, C} 0
5259 // vector_shuffle V1, V2 <1, 2, 3, X>
5261 if (!isShuffleMaskConsecutive(SVOp,
5262 0, // Mask Start Index
5263 NumElems-NumZeros, // Mask End Index(exclusive)
5264 NumZeros, // Where to start looking in the src vector
5265 NumElems, // Number of elements in vector
5266 OpSrc)) // Which source operand ?
5271 ShVal = SVOp->getOperand(OpSrc);
5275 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5276 /// logical left shift of a vector.
5277 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5278 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5280 SVOp->getSimpleValueType(0).getVectorNumElements();
5281 unsigned NumZeros = getNumOfConsecutiveZeros(
5282 SVOp, NumElems, true /* check zeros from left */, DAG,
5283 NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5289 // Considering the elements in the mask that are not consecutive zeros,
5290 // check if they consecutively come from only one of the source vectors.
5292 // 0 { A, B, X, X } = V2
5294 // vector_shuffle V1, V2 <X, X, 4, 5>
5296 if (!isShuffleMaskConsecutive(SVOp,
5297 NumZeros, // Mask Start Index
5298 NumElems, // Mask End Index(exclusive)
5299 0, // Where to start looking in the src vector
5300 NumElems, // Number of elements in vector
5301 OpSrc)) // Which source operand ?
5306 ShVal = SVOp->getOperand(OpSrc);
5310 /// isVectorShift - Returns true if the shuffle can be implemented as a
5311 /// logical left or right shift of a vector.
5312 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5313 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5314 // Although the logic below support any bitwidth size, there are no
5315 // shift instructions which handle more than 128-bit vectors.
5316 if (!SVOp->getSimpleValueType(0).is128BitVector())
5319 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5320 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5326 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5328 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5329 unsigned NumNonZero, unsigned NumZero,
5331 const X86Subtarget* Subtarget,
5332 const TargetLowering &TLI) {
5339 for (unsigned i = 0; i < 16; ++i) {
5340 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5341 if (ThisIsNonZero && First) {
5343 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5345 V = DAG.getUNDEF(MVT::v8i16);
5350 SDValue ThisElt, LastElt;
5351 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5352 if (LastIsNonZero) {
5353 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5354 MVT::i16, Op.getOperand(i-1));
5356 if (ThisIsNonZero) {
5357 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5358 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5359 ThisElt, DAG.getConstant(8, MVT::i8));
5361 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5365 if (ThisElt.getNode())
5366 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5367 DAG.getIntPtrConstant(i/2));
5371 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5374 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5376 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5377 unsigned NumNonZero, unsigned NumZero,
5379 const X86Subtarget* Subtarget,
5380 const TargetLowering &TLI) {
5387 for (unsigned i = 0; i < 8; ++i) {
5388 bool isNonZero = (NonZeros & (1 << i)) != 0;
5392 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5394 V = DAG.getUNDEF(MVT::v8i16);
5397 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5398 MVT::v8i16, V, Op.getOperand(i),
5399 DAG.getIntPtrConstant(i));
5406 /// getVShift - Return a vector logical shift node.
5408 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5409 unsigned NumBits, SelectionDAG &DAG,
5410 const TargetLowering &TLI, SDLoc dl) {
5411 assert(VT.is128BitVector() && "Unknown type for VShift");
5412 EVT ShVT = MVT::v2i64;
5413 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5414 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5415 return DAG.getNode(ISD::BITCAST, dl, VT,
5416 DAG.getNode(Opc, dl, ShVT, SrcOp,
5417 DAG.getConstant(NumBits,
5418 TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5422 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5424 // Check if the scalar load can be widened into a vector load. And if
5425 // the address is "base + cst" see if the cst can be "absorbed" into
5426 // the shuffle mask.
5427 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5428 SDValue Ptr = LD->getBasePtr();
5429 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5431 EVT PVT = LD->getValueType(0);
5432 if (PVT != MVT::i32 && PVT != MVT::f32)
5437 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5438 FI = FINode->getIndex();
5440 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5441 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5442 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5443 Offset = Ptr.getConstantOperandVal(1);
5444 Ptr = Ptr.getOperand(0);
5449 // FIXME: 256-bit vector instructions don't require a strict alignment,
5450 // improve this code to support it better.
5451 unsigned RequiredAlign = VT.getSizeInBits()/8;
5452 SDValue Chain = LD->getChain();
5453 // Make sure the stack object alignment is at least 16 or 32.
5454 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5455 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5456 if (MFI->isFixedObjectIndex(FI)) {
5457 // Can't change the alignment. FIXME: It's possible to compute
5458 // the exact stack offset and reference FI + adjust offset instead.
5459 // If someone *really* cares about this. That's the way to implement it.
5462 MFI->setObjectAlignment(FI, RequiredAlign);
5466 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5467 // Ptr + (Offset & ~15).
5470 if ((Offset % RequiredAlign) & 3)
5472 int64_t StartOffset = Offset & ~(RequiredAlign-1);
5474 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5475 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5477 int EltNo = (Offset - StartOffset) >> 2;
5478 unsigned NumElems = VT.getVectorNumElements();
5480 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5481 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5482 LD->getPointerInfo().getWithOffset(StartOffset),
5483 false, false, false, 0);
5485 SmallVector<int, 8> Mask;
5486 for (unsigned i = 0; i != NumElems; ++i)
5487 Mask.push_back(EltNo);
5489 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5495 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5496 /// vector of type 'VT', see if the elements can be replaced by a single large
5497 /// load which has the same value as a build_vector whose operands are 'elts'.
5499 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5501 /// FIXME: we'd also like to handle the case where the last elements are zero
5502 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5503 /// There's even a handy isZeroNode for that purpose.
5504 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5505 SDLoc &DL, SelectionDAG &DAG,
5506 bool isAfterLegalize) {
5507 EVT EltVT = VT.getVectorElementType();
5508 unsigned NumElems = Elts.size();
5510 LoadSDNode *LDBase = nullptr;
5511 unsigned LastLoadedElt = -1U;
5513 // For each element in the initializer, see if we've found a load or an undef.
5514 // If we don't find an initial load element, or later load elements are
5515 // non-consecutive, bail out.
5516 for (unsigned i = 0; i < NumElems; ++i) {
5517 SDValue Elt = Elts[i];
5519 if (!Elt.getNode() ||
5520 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5523 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5525 LDBase = cast<LoadSDNode>(Elt.getNode());
5529 if (Elt.getOpcode() == ISD::UNDEF)
5532 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5533 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5538 // If we have found an entire vector of loads and undefs, then return a large
5539 // load of the entire vector width starting at the base pointer. If we found
5540 // consecutive loads for the low half, generate a vzext_load node.
5541 if (LastLoadedElt == NumElems - 1) {
5543 if (isAfterLegalize &&
5544 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5547 SDValue NewLd = SDValue();
5549 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5550 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5551 LDBase->getPointerInfo(),
5552 LDBase->isVolatile(), LDBase->isNonTemporal(),
5553 LDBase->isInvariant(), 0);
5554 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5555 LDBase->getPointerInfo(),
5556 LDBase->isVolatile(), LDBase->isNonTemporal(),
5557 LDBase->isInvariant(), LDBase->getAlignment());
5559 if (LDBase->hasAnyUseOfValue(1)) {
5560 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5562 SDValue(NewLd.getNode(), 1));
5563 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5564 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5565 SDValue(NewLd.getNode(), 1));
5570 if (NumElems == 4 && LastLoadedElt == 1 &&
5571 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5572 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5573 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5575 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops,
5576 array_lengthof(Ops), MVT::i64,
5577 LDBase->getPointerInfo(),
5578 LDBase->getAlignment(),
5579 false/*isVolatile*/, true/*ReadMem*/,
5582 // Make sure the newly-created LOAD is in the same position as LDBase in
5583 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5584 // update uses of LDBase's output chain to use the TokenFactor.
5585 if (LDBase->hasAnyUseOfValue(1)) {
5586 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5587 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5588 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5589 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5590 SDValue(ResNode.getNode(), 1));
5593 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5598 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5599 /// to generate a splat value for the following cases:
5600 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5601 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5602 /// a scalar load, or a constant.
5603 /// The VBROADCAST node is returned when a pattern is found,
5604 /// or SDValue() otherwise.
5605 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5606 SelectionDAG &DAG) {
5607 if (!Subtarget->hasFp256())
5610 MVT VT = Op.getSimpleValueType();
5613 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5614 "Unsupported vector type for broadcast.");
5619 switch (Op.getOpcode()) {
5621 // Unknown pattern found.
5624 case ISD::BUILD_VECTOR: {
5625 // The BUILD_VECTOR node must be a splat.
5626 if (!isSplatVector(Op.getNode()))
5629 Ld = Op.getOperand(0);
5630 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5631 Ld.getOpcode() == ISD::ConstantFP);
5633 // The suspected load node has several users. Make sure that all
5634 // of its users are from the BUILD_VECTOR node.
5635 // Constants may have multiple users.
5636 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5641 case ISD::VECTOR_SHUFFLE: {
5642 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5644 // Shuffles must have a splat mask where the first element is
5646 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5649 SDValue Sc = Op.getOperand(0);
5650 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5651 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5653 if (!Subtarget->hasInt256())
5656 // Use the register form of the broadcast instruction available on AVX2.
5657 if (VT.getSizeInBits() >= 256)
5658 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5659 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5662 Ld = Sc.getOperand(0);
5663 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5664 Ld.getOpcode() == ISD::ConstantFP);
5666 // The scalar_to_vector node and the suspected
5667 // load node must have exactly one user.
5668 // Constants may have multiple users.
5670 // AVX-512 has register version of the broadcast
5671 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5672 Ld.getValueType().getSizeInBits() >= 32;
5673 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5680 bool IsGE256 = (VT.getSizeInBits() >= 256);
5682 // Handle the broadcasting a single constant scalar from the constant pool
5683 // into a vector. On Sandybridge it is still better to load a constant vector
5684 // from the constant pool and not to broadcast it from a scalar.
5685 if (ConstSplatVal && Subtarget->hasInt256()) {
5686 EVT CVT = Ld.getValueType();
5687 assert(!CVT.isVector() && "Must not broadcast a vector type");
5688 unsigned ScalarSize = CVT.getSizeInBits();
5690 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5691 const Constant *C = nullptr;
5692 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5693 C = CI->getConstantIntValue();
5694 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5695 C = CF->getConstantFPValue();
5697 assert(C && "Invalid constant type");
5699 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5700 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5701 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5702 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5703 MachinePointerInfo::getConstantPool(),
5704 false, false, false, Alignment);
5706 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5710 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5711 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5713 // Handle AVX2 in-register broadcasts.
5714 if (!IsLoad && Subtarget->hasInt256() &&
5715 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5716 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5718 // The scalar source must be a normal load.
5722 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5723 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5725 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5726 // double since there is no vbroadcastsd xmm
5727 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5728 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5729 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5732 // Unsupported broadcast.
5736 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5737 /// underlying vector and index.
5739 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5741 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5743 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5744 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5747 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5749 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5751 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5752 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5755 // In this case the vector is the extract_subvector expression and the index
5756 // is 2, as specified by the shuffle.
5757 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5758 SDValue ShuffleVec = SVOp->getOperand(0);
5759 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5760 assert(ShuffleVecVT.getVectorElementType() ==
5761 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5763 int ShuffleIdx = SVOp->getMaskElt(Idx);
5764 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5765 ExtractedFromVec = ShuffleVec;
5771 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5772 MVT VT = Op.getSimpleValueType();
5774 // Skip if insert_vec_elt is not supported.
5775 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5776 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5780 unsigned NumElems = Op.getNumOperands();
5784 SmallVector<unsigned, 4> InsertIndices;
5785 SmallVector<int, 8> Mask(NumElems, -1);
5787 for (unsigned i = 0; i != NumElems; ++i) {
5788 unsigned Opc = Op.getOperand(i).getOpcode();
5790 if (Opc == ISD::UNDEF)
5793 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5794 // Quit if more than 1 elements need inserting.
5795 if (InsertIndices.size() > 1)
5798 InsertIndices.push_back(i);
5802 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5803 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5804 // Quit if non-constant index.
5805 if (!isa<ConstantSDNode>(ExtIdx))
5807 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5809 // Quit if extracted from vector of different type.
5810 if (ExtractedFromVec.getValueType() != VT)
5813 if (!VecIn1.getNode())
5814 VecIn1 = ExtractedFromVec;
5815 else if (VecIn1 != ExtractedFromVec) {
5816 if (!VecIn2.getNode())
5817 VecIn2 = ExtractedFromVec;
5818 else if (VecIn2 != ExtractedFromVec)
5819 // Quit if more than 2 vectors to shuffle
5823 if (ExtractedFromVec == VecIn1)
5825 else if (ExtractedFromVec == VecIn2)
5826 Mask[i] = Idx + NumElems;
5829 if (!VecIn1.getNode())
5832 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5833 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5834 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5835 unsigned Idx = InsertIndices[i];
5836 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5837 DAG.getIntPtrConstant(Idx));
5843 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5845 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5847 MVT VT = Op.getSimpleValueType();
5848 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5849 "Unexpected type in LowerBUILD_VECTORvXi1!");
5852 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5853 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5854 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5855 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5856 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5857 Ops, VT.getVectorNumElements());
5860 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5861 SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5862 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5863 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5864 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5865 Ops, VT.getVectorNumElements());
5868 bool AllContants = true;
5869 uint64_t Immediate = 0;
5870 int NonConstIdx = -1;
5871 bool IsSplat = true;
5872 unsigned NumNonConsts = 0;
5873 unsigned NumConsts = 0;
5874 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5875 SDValue In = Op.getOperand(idx);
5876 if (In.getOpcode() == ISD::UNDEF)
5878 if (!isa<ConstantSDNode>(In)) {
5879 AllContants = false;
5885 if (cast<ConstantSDNode>(In)->getZExtValue())
5886 Immediate |= (1ULL << idx);
5888 if (In != Op.getOperand(0))
5893 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5894 DAG.getConstant(Immediate, MVT::i16));
5895 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5896 DAG.getIntPtrConstant(0));
5899 if (NumNonConsts == 1 && NonConstIdx != 0) {
5902 SDValue VecAsImm = DAG.getConstant(Immediate,
5903 MVT::getIntegerVT(VT.getSizeInBits()));
5904 DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
5907 DstVec = DAG.getUNDEF(VT);
5908 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5909 Op.getOperand(NonConstIdx),
5910 DAG.getIntPtrConstant(NonConstIdx));
5912 if (!IsSplat && (NonConstIdx != 0))
5913 llvm_unreachable("Unsupported BUILD_VECTOR operation");
5914 MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
5917 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5918 DAG.getConstant(-1, SelectVT),
5919 DAG.getConstant(0, SelectVT));
5921 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5922 DAG.getConstant((Immediate | 1), SelectVT),
5923 DAG.getConstant(Immediate, SelectVT));
5924 return DAG.getNode(ISD::BITCAST, dl, VT, Select);
5928 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5931 MVT VT = Op.getSimpleValueType();
5932 MVT ExtVT = VT.getVectorElementType();
5933 unsigned NumElems = Op.getNumOperands();
5935 // Generate vectors for predicate vectors.
5936 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5937 return LowerBUILD_VECTORvXi1(Op, DAG);
5939 // Vectors containing all zeros can be matched by pxor and xorps later
5940 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5941 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5942 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5943 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5946 return getZeroVector(VT, Subtarget, DAG, dl);
5949 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5950 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5951 // vpcmpeqd on 256-bit vectors.
5952 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5953 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5956 if (!VT.is512BitVector())
5957 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5960 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
5961 if (Broadcast.getNode())
5964 unsigned EVTBits = ExtVT.getSizeInBits();
5966 unsigned NumZero = 0;
5967 unsigned NumNonZero = 0;
5968 unsigned NonZeros = 0;
5969 bool IsAllConstants = true;
5970 SmallSet<SDValue, 8> Values;
5971 for (unsigned i = 0; i < NumElems; ++i) {
5972 SDValue Elt = Op.getOperand(i);
5973 if (Elt.getOpcode() == ISD::UNDEF)
5976 if (Elt.getOpcode() != ISD::Constant &&
5977 Elt.getOpcode() != ISD::ConstantFP)
5978 IsAllConstants = false;
5979 if (X86::isZeroNode(Elt))
5982 NonZeros |= (1 << i);
5987 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5988 if (NumNonZero == 0)
5989 return DAG.getUNDEF(VT);
5991 // Special case for single non-zero, non-undef, element.
5992 if (NumNonZero == 1) {
5993 unsigned Idx = countTrailingZeros(NonZeros);
5994 SDValue Item = Op.getOperand(Idx);
5996 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5997 // the value are obviously zero, truncate the value to i32 and do the
5998 // insertion that way. Only do this if the value is non-constant or if the
5999 // value is a constant being inserted into element 0. It is cheaper to do
6000 // a constant pool load than it is to do a movd + shuffle.
6001 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6002 (!IsAllConstants || Idx == 0)) {
6003 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6005 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6006 EVT VecVT = MVT::v4i32;
6007 unsigned VecElts = 4;
6009 // Truncate the value (which may itself be a constant) to i32, and
6010 // convert it to a vector with movd (S2V+shuffle to zero extend).
6011 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6012 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6013 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6015 // Now we have our 32-bit value zero extended in the low element of
6016 // a vector. If Idx != 0, swizzle it into place.
6018 SmallVector<int, 4> Mask;
6019 Mask.push_back(Idx);
6020 for (unsigned i = 1; i != VecElts; ++i)
6022 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6025 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6029 // If we have a constant or non-constant insertion into the low element of
6030 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6031 // the rest of the elements. This will be matched as movd/movq/movss/movsd
6032 // depending on what the source datatype is.
6035 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6037 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6038 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6039 if (VT.is256BitVector() || VT.is512BitVector()) {
6040 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6041 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6042 Item, DAG.getIntPtrConstant(0));
6044 assert(VT.is128BitVector() && "Expected an SSE value type!");
6045 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6046 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6047 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6050 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6051 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6052 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6053 if (VT.is256BitVector()) {
6054 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6055 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6057 assert(VT.is128BitVector() && "Expected an SSE value type!");
6058 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6060 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6064 // Is it a vector logical left shift?
6065 if (NumElems == 2 && Idx == 1 &&
6066 X86::isZeroNode(Op.getOperand(0)) &&
6067 !X86::isZeroNode(Op.getOperand(1))) {
6068 unsigned NumBits = VT.getSizeInBits();
6069 return getVShift(true, VT,
6070 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6071 VT, Op.getOperand(1)),
6072 NumBits/2, DAG, *this, dl);
6075 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6078 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6079 // is a non-constant being inserted into an element other than the low one,
6080 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6081 // movd/movss) to move this into the low element, then shuffle it into
6083 if (EVTBits == 32) {
6084 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6086 // Turn it into a shuffle of zero and zero-extended scalar to vector.
6087 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6088 SmallVector<int, 8> MaskVec;
6089 for (unsigned i = 0; i != NumElems; ++i)
6090 MaskVec.push_back(i == Idx ? 0 : 1);
6091 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6095 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6096 if (Values.size() == 1) {
6097 if (EVTBits == 32) {
6098 // Instead of a shuffle like this:
6099 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6100 // Check if it's possible to issue this instead.
6101 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6102 unsigned Idx = countTrailingZeros(NonZeros);
6103 SDValue Item = Op.getOperand(Idx);
6104 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6105 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6110 // A vector full of immediates; various special cases are already
6111 // handled, so this is best done with a single constant-pool load.
6115 // For AVX-length vectors, build the individual 128-bit pieces and use
6116 // shuffles to put them in place.
6117 if (VT.is256BitVector() || VT.is512BitVector()) {
6118 SmallVector<SDValue, 64> V;
6119 for (unsigned i = 0; i != NumElems; ++i)
6120 V.push_back(Op.getOperand(i));
6122 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6124 // Build both the lower and upper subvector.
6125 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
6126 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
6129 // Recreate the wider vector with the lower and upper part.
6130 if (VT.is256BitVector())
6131 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6132 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6135 // Let legalizer expand 2-wide build_vectors.
6136 if (EVTBits == 64) {
6137 if (NumNonZero == 1) {
6138 // One half is zero or undef.
6139 unsigned Idx = countTrailingZeros(NonZeros);
6140 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6141 Op.getOperand(Idx));
6142 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6147 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6148 if (EVTBits == 8 && NumElems == 16) {
6149 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6151 if (V.getNode()) return V;
6154 if (EVTBits == 16 && NumElems == 8) {
6155 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6157 if (V.getNode()) return V;
6160 // If element VT is == 32 bits, turn it into a number of shuffles.
6161 SmallVector<SDValue, 8> V(NumElems);
6162 if (NumElems == 4 && NumZero > 0) {
6163 for (unsigned i = 0; i < 4; ++i) {
6164 bool isZero = !(NonZeros & (1 << i));
6166 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6168 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6171 for (unsigned i = 0; i < 2; ++i) {
6172 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6175 V[i] = V[i*2]; // Must be a zero vector.
6178 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6181 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6184 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6189 bool Reverse1 = (NonZeros & 0x3) == 2;
6190 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6194 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6195 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6197 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6200 if (Values.size() > 1 && VT.is128BitVector()) {
6201 // Check for a build vector of consecutive loads.
6202 for (unsigned i = 0; i < NumElems; ++i)
6203 V[i] = Op.getOperand(i);
6205 // Check for elements which are consecutive loads.
6206 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6210 // Check for a build vector from mostly shuffle plus few inserting.
6211 SDValue Sh = buildFromShuffleMostly(Op, DAG);
6215 // For SSE 4.1, use insertps to put the high elements into the low element.
6216 if (getSubtarget()->hasSSE41()) {
6218 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6219 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6221 Result = DAG.getUNDEF(VT);
6223 for (unsigned i = 1; i < NumElems; ++i) {
6224 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6225 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6226 Op.getOperand(i), DAG.getIntPtrConstant(i));
6231 // Otherwise, expand into a number of unpckl*, start by extending each of
6232 // our (non-undef) elements to the full vector width with the element in the
6233 // bottom slot of the vector (which generates no code for SSE).
6234 for (unsigned i = 0; i < NumElems; ++i) {
6235 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6236 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6238 V[i] = DAG.getUNDEF(VT);
6241 // Next, we iteratively mix elements, e.g. for v4f32:
6242 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6243 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6244 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6245 unsigned EltStride = NumElems >> 1;
6246 while (EltStride != 0) {
6247 for (unsigned i = 0; i < EltStride; ++i) {
6248 // If V[i+EltStride] is undef and this is the first round of mixing,
6249 // then it is safe to just drop this shuffle: V[i] is already in the
6250 // right place, the one element (since it's the first round) being
6251 // inserted as undef can be dropped. This isn't safe for successive
6252 // rounds because they will permute elements within both vectors.
6253 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6254 EltStride == NumElems/2)
6257 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6266 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6267 // to create 256-bit vectors from two other 128-bit ones.
6268 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6270 MVT ResVT = Op.getSimpleValueType();
6272 assert((ResVT.is256BitVector() ||
6273 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6275 SDValue V1 = Op.getOperand(0);
6276 SDValue V2 = Op.getOperand(1);
6277 unsigned NumElems = ResVT.getVectorNumElements();
6278 if(ResVT.is256BitVector())
6279 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6281 if (Op.getNumOperands() == 4) {
6282 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6283 ResVT.getVectorNumElements()/2);
6284 SDValue V3 = Op.getOperand(2);
6285 SDValue V4 = Op.getOperand(3);
6286 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6287 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6289 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6292 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6293 MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6294 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6295 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6296 Op.getNumOperands() == 4)));
6298 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6299 // from two other 128-bit ones.
6301 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6302 return LowerAVXCONCAT_VECTORS(Op, DAG);
6305 // Try to lower a shuffle node into a simple blend instruction.
6307 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6308 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6309 SDValue V1 = SVOp->getOperand(0);
6310 SDValue V2 = SVOp->getOperand(1);
6312 MVT VT = SVOp->getSimpleValueType(0);
6313 MVT EltVT = VT.getVectorElementType();
6314 unsigned NumElems = VT.getVectorNumElements();
6316 // There is no blend with immediate in AVX-512.
6317 if (VT.is512BitVector())
6320 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
6322 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
6325 // Check the mask for BLEND and build the value.
6326 unsigned MaskValue = 0;
6327 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6328 unsigned NumLanes = (NumElems-1)/8 + 1;
6329 unsigned NumElemsInLane = NumElems / NumLanes;
6331 // Blend for v16i16 should be symetric for the both lanes.
6332 for (unsigned i = 0; i < NumElemsInLane; ++i) {
6334 int SndLaneEltIdx = (NumLanes == 2) ?
6335 SVOp->getMaskElt(i + NumElemsInLane) : -1;
6336 int EltIdx = SVOp->getMaskElt(i);
6338 if ((EltIdx < 0 || EltIdx == (int)i) &&
6339 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6342 if (((unsigned)EltIdx == (i + NumElems)) &&
6343 (SndLaneEltIdx < 0 ||
6344 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6345 MaskValue |= (1<<i);
6350 // Convert i32 vectors to floating point if it is not AVX2.
6351 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6353 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6354 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6356 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6357 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6360 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6361 DAG.getConstant(MaskValue, MVT::i32));
6362 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6365 /// In vector type \p VT, return true if the element at index \p InputIdx
6366 /// falls on a different 128-bit lane than \p OutputIdx.
6367 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
6368 unsigned OutputIdx) {
6369 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6370 return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
6373 /// Generate a PSHUFB if possible. Selects elements from \p V1 according to
6374 /// \p MaskVals. MaskVals[OutputIdx] = InputIdx specifies that we want to
6375 /// shuffle the element at InputIdx in V1 to OutputIdx in the result. If \p
6376 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
6378 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
6379 SelectionDAG &DAG) {
6380 MVT VT = V1.getSimpleValueType();
6381 assert(VT.is128BitVector() || VT.is256BitVector());
6383 MVT EltVT = VT.getVectorElementType();
6384 unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
6385 unsigned NumElts = VT.getVectorNumElements();
6387 SmallVector<SDValue, 32> PshufbMask;
6388 for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
6389 int InputIdx = MaskVals[OutputIdx];
6390 unsigned InputByteIdx;
6392 if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
6393 InputByteIdx = 0x80;
6395 // Cross lane is not allowed.
6396 if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
6398 InputByteIdx = InputIdx * EltSizeInBytes;
6399 // Index is an byte offset within the 128-bit lane.
6400 InputByteIdx &= 0xf;
6403 for (unsigned j = 0; j < EltSizeInBytes; ++j) {
6404 PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
6405 if (InputByteIdx != 0x80)
6410 MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
6412 V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
6413 return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
6414 DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT,
6415 PshufbMask.data(), PshufbMask.size()));
6418 // v8i16 shuffles - Prefer shuffles in the following order:
6419 // 1. [all] pshuflw, pshufhw, optional move
6420 // 2. [ssse3] 1 x pshufb
6421 // 3. [ssse3] 2 x pshufb + 1 x por
6422 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6424 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6425 SelectionDAG &DAG) {
6426 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6427 SDValue V1 = SVOp->getOperand(0);
6428 SDValue V2 = SVOp->getOperand(1);
6430 SmallVector<int, 8> MaskVals;
6432 // Determine if more than 1 of the words in each of the low and high quadwords
6433 // of the result come from the same quadword of one of the two inputs. Undef
6434 // mask values count as coming from any quadword, for better codegen.
6436 // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
6437 // feeds this quad. For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
6438 unsigned LoQuad[] = { 0, 0, 0, 0 };
6439 unsigned HiQuad[] = { 0, 0, 0, 0 };
6440 // Indices of quads used.
6441 std::bitset<4> InputQuads;
6442 for (unsigned i = 0; i < 8; ++i) {
6443 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6444 int EltIdx = SVOp->getMaskElt(i);
6445 MaskVals.push_back(EltIdx);
6454 InputQuads.set(EltIdx / 4);
6457 int BestLoQuad = -1;
6458 unsigned MaxQuad = 1;
6459 for (unsigned i = 0; i < 4; ++i) {
6460 if (LoQuad[i] > MaxQuad) {
6462 MaxQuad = LoQuad[i];
6466 int BestHiQuad = -1;
6468 for (unsigned i = 0; i < 4; ++i) {
6469 if (HiQuad[i] > MaxQuad) {
6471 MaxQuad = HiQuad[i];
6475 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6476 // of the two input vectors, shuffle them into one input vector so only a
6477 // single pshufb instruction is necessary. If there are more than 2 input
6478 // quads, disable the next transformation since it does not help SSSE3.
6479 bool V1Used = InputQuads[0] || InputQuads[1];
6480 bool V2Used = InputQuads[2] || InputQuads[3];
6481 if (Subtarget->hasSSSE3()) {
6482 if (InputQuads.count() == 2 && V1Used && V2Used) {
6483 BestLoQuad = InputQuads[0] ? 0 : 1;
6484 BestHiQuad = InputQuads[2] ? 2 : 3;
6486 if (InputQuads.count() > 2) {
6492 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6493 // the shuffle mask. If a quad is scored as -1, that means that it contains
6494 // words from all 4 input quadwords.
6496 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6498 BestLoQuad < 0 ? 0 : BestLoQuad,
6499 BestHiQuad < 0 ? 1 : BestHiQuad
6501 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6502 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6503 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6504 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6506 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6507 // source words for the shuffle, to aid later transformations.
6508 bool AllWordsInNewV = true;
6509 bool InOrder[2] = { true, true };
6510 for (unsigned i = 0; i != 8; ++i) {
6511 int idx = MaskVals[i];
6513 InOrder[i/4] = false;
6514 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6516 AllWordsInNewV = false;
6520 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6521 if (AllWordsInNewV) {
6522 for (int i = 0; i != 8; ++i) {
6523 int idx = MaskVals[i];
6526 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6527 if ((idx != i) && idx < 4)
6529 if ((idx != i) && idx > 3)
6538 // If we've eliminated the use of V2, and the new mask is a pshuflw or
6539 // pshufhw, that's as cheap as it gets. Return the new shuffle.
6540 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6541 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6542 unsigned TargetMask = 0;
6543 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6544 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6545 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6546 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6547 getShufflePSHUFLWImmediate(SVOp);
6548 V1 = NewV.getOperand(0);
6549 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6553 // Promote splats to a larger type which usually leads to more efficient code.
6554 // FIXME: Is this true if pshufb is available?
6555 if (SVOp->isSplat())
6556 return PromoteSplat(SVOp, DAG);
6558 // If we have SSSE3, and all words of the result are from 1 input vector,
6559 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
6560 // is present, fall back to case 4.
6561 if (Subtarget->hasSSSE3()) {
6562 SmallVector<SDValue,16> pshufbMask;
6564 // If we have elements from both input vectors, set the high bit of the
6565 // shuffle mask element to zero out elements that come from V2 in the V1
6566 // mask, and elements that come from V1 in the V2 mask, so that the two
6567 // results can be OR'd together.
6568 bool TwoInputs = V1Used && V2Used;
6569 V1 = getPSHUFB(MaskVals, V1, dl, DAG);
6571 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6573 // Calculate the shuffle mask for the second input, shuffle it, and
6574 // OR it with the first shuffled input.
6575 CommuteVectorShuffleMask(MaskVals, 8);
6576 V2 = getPSHUFB(MaskVals, V2, dl, DAG);
6577 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6578 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6581 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6582 // and update MaskVals with new element order.
6583 std::bitset<8> InOrder;
6584 if (BestLoQuad >= 0) {
6585 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6586 for (int i = 0; i != 4; ++i) {
6587 int idx = MaskVals[i];
6590 } else if ((idx / 4) == BestLoQuad) {
6595 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6598 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6599 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6600 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6602 getShufflePSHUFLWImmediate(SVOp), DAG);
6606 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6607 // and update MaskVals with the new element order.
6608 if (BestHiQuad >= 0) {
6609 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6610 for (unsigned i = 4; i != 8; ++i) {
6611 int idx = MaskVals[i];
6614 } else if ((idx / 4) == BestHiQuad) {
6615 MaskV[i] = (idx & 3) + 4;
6619 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6622 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6623 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6624 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6626 getShufflePSHUFHWImmediate(SVOp), DAG);
6630 // In case BestHi & BestLo were both -1, which means each quadword has a word
6631 // from each of the four input quadwords, calculate the InOrder bitvector now
6632 // before falling through to the insert/extract cleanup.
6633 if (BestLoQuad == -1 && BestHiQuad == -1) {
6635 for (int i = 0; i != 8; ++i)
6636 if (MaskVals[i] < 0 || MaskVals[i] == i)
6640 // The other elements are put in the right place using pextrw and pinsrw.
6641 for (unsigned i = 0; i != 8; ++i) {
6644 int EltIdx = MaskVals[i];
6647 SDValue ExtOp = (EltIdx < 8) ?
6648 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6649 DAG.getIntPtrConstant(EltIdx)) :
6650 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6651 DAG.getIntPtrConstant(EltIdx - 8));
6652 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6653 DAG.getIntPtrConstant(i));
6658 /// \brief v16i16 shuffles
6660 /// FIXME: We only support generation of a single pshufb currently. We can
6661 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
6662 /// well (e.g 2 x pshufb + 1 x por).
6664 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
6665 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6666 SDValue V1 = SVOp->getOperand(0);
6667 SDValue V2 = SVOp->getOperand(1);
6670 if (V2.getOpcode() != ISD::UNDEF)
6673 SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6674 return getPSHUFB(MaskVals, V1, dl, DAG);
6677 // v16i8 shuffles - Prefer shuffles in the following order:
6678 // 1. [ssse3] 1 x pshufb
6679 // 2. [ssse3] 2 x pshufb + 1 x por
6680 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
6681 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6682 const X86Subtarget* Subtarget,
6683 SelectionDAG &DAG) {
6684 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6685 SDValue V1 = SVOp->getOperand(0);
6686 SDValue V2 = SVOp->getOperand(1);
6688 ArrayRef<int> MaskVals = SVOp->getMask();
6690 // Promote splats to a larger type which usually leads to more efficient code.
6691 // FIXME: Is this true if pshufb is available?
6692 if (SVOp->isSplat())
6693 return PromoteSplat(SVOp, DAG);
6695 // If we have SSSE3, case 1 is generated when all result bytes come from
6696 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
6697 // present, fall back to case 3.
6699 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6700 if (Subtarget->hasSSSE3()) {
6701 SmallVector<SDValue,16> pshufbMask;
6703 // If all result elements are from one input vector, then only translate
6704 // undef mask values to 0x80 (zero out result) in the pshufb mask.
6706 // Otherwise, we have elements from both input vectors, and must zero out
6707 // elements that come from V2 in the first mask, and V1 in the second mask
6708 // so that we can OR them together.
6709 for (unsigned i = 0; i != 16; ++i) {
6710 int EltIdx = MaskVals[i];
6711 if (EltIdx < 0 || EltIdx >= 16)
6713 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6715 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6716 DAG.getNode(ISD::BUILD_VECTOR, dl,
6717 MVT::v16i8, &pshufbMask[0], 16));
6719 // As PSHUFB will zero elements with negative indices, it's safe to ignore
6720 // the 2nd operand if it's undefined or zero.
6721 if (V2.getOpcode() == ISD::UNDEF ||
6722 ISD::isBuildVectorAllZeros(V2.getNode()))
6725 // Calculate the shuffle mask for the second input, shuffle it, and
6726 // OR it with the first shuffled input.
6728 for (unsigned i = 0; i != 16; ++i) {
6729 int EltIdx = MaskVals[i];
6730 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6731 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6733 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6734 DAG.getNode(ISD::BUILD_VECTOR, dl,
6735 MVT::v16i8, &pshufbMask[0], 16));
6736 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6739 // No SSSE3 - Calculate in place words and then fix all out of place words
6740 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
6741 // the 16 different words that comprise the two doublequadword input vectors.
6742 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6743 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6745 for (int i = 0; i != 8; ++i) {
6746 int Elt0 = MaskVals[i*2];
6747 int Elt1 = MaskVals[i*2+1];
6749 // This word of the result is all undef, skip it.
6750 if (Elt0 < 0 && Elt1 < 0)
6753 // This word of the result is already in the correct place, skip it.
6754 if ((Elt0 == i*2) && (Elt1 == i*2+1))
6757 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6758 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6761 // If Elt0 and Elt1 are defined, are consecutive, and can be load
6762 // using a single extract together, load it and store it.
6763 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6764 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6765 DAG.getIntPtrConstant(Elt1 / 2));
6766 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6767 DAG.getIntPtrConstant(i));
6771 // If Elt1 is defined, extract it from the appropriate source. If the
6772 // source byte is not also odd, shift the extracted word left 8 bits
6773 // otherwise clear the bottom 8 bits if we need to do an or.
6775 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6776 DAG.getIntPtrConstant(Elt1 / 2));
6777 if ((Elt1 & 1) == 0)
6778 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6780 TLI.getShiftAmountTy(InsElt.getValueType())));
6782 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6783 DAG.getConstant(0xFF00, MVT::i16));
6785 // If Elt0 is defined, extract it from the appropriate source. If the
6786 // source byte is not also even, shift the extracted word right 8 bits. If
6787 // Elt1 was also defined, OR the extracted values together before
6788 // inserting them in the result.
6790 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6791 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6792 if ((Elt0 & 1) != 0)
6793 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6795 TLI.getShiftAmountTy(InsElt0.getValueType())));
6797 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6798 DAG.getConstant(0x00FF, MVT::i16));
6799 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6802 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6803 DAG.getIntPtrConstant(i));
6805 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6808 // v32i8 shuffles - Translate to VPSHUFB if possible.
6810 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6811 const X86Subtarget *Subtarget,
6812 SelectionDAG &DAG) {
6813 MVT VT = SVOp->getSimpleValueType(0);
6814 SDValue V1 = SVOp->getOperand(0);
6815 SDValue V2 = SVOp->getOperand(1);
6817 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6819 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6820 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6821 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6823 // VPSHUFB may be generated if
6824 // (1) one of input vector is undefined or zeroinitializer.
6825 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6826 // And (2) the mask indexes don't cross the 128-bit lane.
6827 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6828 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6831 if (V1IsAllZero && !V2IsAllZero) {
6832 CommuteVectorShuffleMask(MaskVals, 32);
6835 return getPSHUFB(MaskVals, V1, dl, DAG);
6838 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6839 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6840 /// done when every pair / quad of shuffle mask elements point to elements in
6841 /// the right sequence. e.g.
6842 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6844 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6845 SelectionDAG &DAG) {
6846 MVT VT = SVOp->getSimpleValueType(0);
6848 unsigned NumElems = VT.getVectorNumElements();
6851 switch (VT.SimpleTy) {
6852 default: llvm_unreachable("Unexpected!");
6853 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
6854 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
6855 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
6856 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
6857 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6858 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
6861 SmallVector<int, 8> MaskVec;
6862 for (unsigned i = 0; i != NumElems; i += Scale) {
6864 for (unsigned j = 0; j != Scale; ++j) {
6865 int EltIdx = SVOp->getMaskElt(i+j);
6869 StartIdx = (EltIdx / Scale);
6870 if (EltIdx != (int)(StartIdx*Scale + j))
6873 MaskVec.push_back(StartIdx);
6876 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6877 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6878 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6881 /// getVZextMovL - Return a zero-extending vector move low node.
6883 static SDValue getVZextMovL(MVT VT, MVT OpVT,
6884 SDValue SrcOp, SelectionDAG &DAG,
6885 const X86Subtarget *Subtarget, SDLoc dl) {
6886 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6887 LoadSDNode *LD = nullptr;
6888 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6889 LD = dyn_cast<LoadSDNode>(SrcOp);
6891 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6893 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6894 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6895 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6896 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6897 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6899 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6900 return DAG.getNode(ISD::BITCAST, dl, VT,
6901 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6902 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6910 return DAG.getNode(ISD::BITCAST, dl, VT,
6911 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6912 DAG.getNode(ISD::BITCAST, dl,
6916 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6917 /// which could not be matched by any known target speficic shuffle
6919 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6921 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6922 if (NewOp.getNode())
6925 MVT VT = SVOp->getSimpleValueType(0);
6927 unsigned NumElems = VT.getVectorNumElements();
6928 unsigned NumLaneElems = NumElems / 2;
6931 MVT EltVT = VT.getVectorElementType();
6932 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6935 SmallVector<int, 16> Mask;
6936 for (unsigned l = 0; l < 2; ++l) {
6937 // Build a shuffle mask for the output, discovering on the fly which
6938 // input vectors to use as shuffle operands (recorded in InputUsed).
6939 // If building a suitable shuffle vector proves too hard, then bail
6940 // out with UseBuildVector set.
6941 bool UseBuildVector = false;
6942 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6943 unsigned LaneStart = l * NumLaneElems;
6944 for (unsigned i = 0; i != NumLaneElems; ++i) {
6945 // The mask element. This indexes into the input.
6946 int Idx = SVOp->getMaskElt(i+LaneStart);
6948 // the mask element does not index into any input vector.
6953 // The input vector this mask element indexes into.
6954 int Input = Idx / NumLaneElems;
6956 // Turn the index into an offset from the start of the input vector.
6957 Idx -= Input * NumLaneElems;
6959 // Find or create a shuffle vector operand to hold this input.
6961 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6962 if (InputUsed[OpNo] == Input)
6963 // This input vector is already an operand.
6965 if (InputUsed[OpNo] < 0) {
6966 // Create a new operand for this input vector.
6967 InputUsed[OpNo] = Input;
6972 if (OpNo >= array_lengthof(InputUsed)) {
6973 // More than two input vectors used! Give up on trying to create a
6974 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
6975 UseBuildVector = true;
6979 // Add the mask index for the new shuffle vector.
6980 Mask.push_back(Idx + OpNo * NumLaneElems);
6983 if (UseBuildVector) {
6984 SmallVector<SDValue, 16> SVOps;
6985 for (unsigned i = 0; i != NumLaneElems; ++i) {
6986 // The mask element. This indexes into the input.
6987 int Idx = SVOp->getMaskElt(i+LaneStart);
6989 SVOps.push_back(DAG.getUNDEF(EltVT));
6993 // The input vector this mask element indexes into.
6994 int Input = Idx / NumElems;
6996 // Turn the index into an offset from the start of the input vector.
6997 Idx -= Input * NumElems;
6999 // Extract the vector element by hand.
7000 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
7001 SVOp->getOperand(Input),
7002 DAG.getIntPtrConstant(Idx)));
7005 // Construct the output using a BUILD_VECTOR.
7006 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
7008 } else if (InputUsed[0] < 0) {
7009 // No input vectors were used! The result is undefined.
7010 Output[l] = DAG.getUNDEF(NVT);
7012 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
7013 (InputUsed[0] % 2) * NumLaneElems,
7015 // If only one input was used, use an undefined vector for the other.
7016 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
7017 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
7018 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
7019 // At least one input vector was used. Create a new shuffle vector.
7020 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
7026 // Concatenate the result back
7027 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
7030 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
7031 /// 4 elements, and match them with several different shuffle types.
7033 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7034 SDValue V1 = SVOp->getOperand(0);
7035 SDValue V2 = SVOp->getOperand(1);
7037 MVT VT = SVOp->getSimpleValueType(0);
7039 assert(VT.is128BitVector() && "Unsupported vector size");
7041 std::pair<int, int> Locs[4];
7042 int Mask1[] = { -1, -1, -1, -1 };
7043 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
7047 for (unsigned i = 0; i != 4; ++i) {
7048 int Idx = PermMask[i];
7050 Locs[i] = std::make_pair(-1, -1);
7052 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
7054 Locs[i] = std::make_pair(0, NumLo);
7058 Locs[i] = std::make_pair(1, NumHi);
7060 Mask1[2+NumHi] = Idx;
7066 if (NumLo <= 2 && NumHi <= 2) {
7067 // If no more than two elements come from either vector. This can be
7068 // implemented with two shuffles. First shuffle gather the elements.
7069 // The second shuffle, which takes the first shuffle as both of its
7070 // vector operands, put the elements into the right order.
7071 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7073 int Mask2[] = { -1, -1, -1, -1 };
7075 for (unsigned i = 0; i != 4; ++i)
7076 if (Locs[i].first != -1) {
7077 unsigned Idx = (i < 2) ? 0 : 4;
7078 Idx += Locs[i].first * 2 + Locs[i].second;
7082 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
7085 if (NumLo == 3 || NumHi == 3) {
7086 // Otherwise, we must have three elements from one vector, call it X, and
7087 // one element from the other, call it Y. First, use a shufps to build an
7088 // intermediate vector with the one element from Y and the element from X
7089 // that will be in the same half in the final destination (the indexes don't
7090 // matter). Then, use a shufps to build the final vector, taking the half
7091 // containing the element from Y from the intermediate, and the other half
7094 // Normalize it so the 3 elements come from V1.
7095 CommuteVectorShuffleMask(PermMask, 4);
7099 // Find the element from V2.
7101 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
7102 int Val = PermMask[HiIndex];
7109 Mask1[0] = PermMask[HiIndex];
7111 Mask1[2] = PermMask[HiIndex^1];
7113 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7116 Mask1[0] = PermMask[0];
7117 Mask1[1] = PermMask[1];
7118 Mask1[2] = HiIndex & 1 ? 6 : 4;
7119 Mask1[3] = HiIndex & 1 ? 4 : 6;
7120 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7123 Mask1[0] = HiIndex & 1 ? 2 : 0;
7124 Mask1[1] = HiIndex & 1 ? 0 : 2;
7125 Mask1[2] = PermMask[2];
7126 Mask1[3] = PermMask[3];
7131 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7134 // Break it into (shuffle shuffle_hi, shuffle_lo).
7135 int LoMask[] = { -1, -1, -1, -1 };
7136 int HiMask[] = { -1, -1, -1, -1 };
7138 int *MaskPtr = LoMask;
7139 unsigned MaskIdx = 0;
7142 for (unsigned i = 0; i != 4; ++i) {
7149 int Idx = PermMask[i];
7151 Locs[i] = std::make_pair(-1, -1);
7152 } else if (Idx < 4) {
7153 Locs[i] = std::make_pair(MaskIdx, LoIdx);
7154 MaskPtr[LoIdx] = Idx;
7157 Locs[i] = std::make_pair(MaskIdx, HiIdx);
7158 MaskPtr[HiIdx] = Idx;
7163 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7164 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7165 int MaskOps[] = { -1, -1, -1, -1 };
7166 for (unsigned i = 0; i != 4; ++i)
7167 if (Locs[i].first != -1)
7168 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7169 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7172 static bool MayFoldVectorLoad(SDValue V) {
7173 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7174 V = V.getOperand(0);
7176 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7177 V = V.getOperand(0);
7178 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7179 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7180 // BUILD_VECTOR (load), undef
7181 V = V.getOperand(0);
7183 return MayFoldLoad(V);
7187 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7188 MVT VT = Op.getSimpleValueType();
7190 // Canonizalize to v2f64.
7191 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7192 return DAG.getNode(ISD::BITCAST, dl, VT,
7193 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7198 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7200 SDValue V1 = Op.getOperand(0);
7201 SDValue V2 = Op.getOperand(1);
7202 MVT VT = Op.getSimpleValueType();
7204 assert(VT != MVT::v2i64 && "unsupported shuffle type");
7206 if (HasSSE2 && VT == MVT::v2f64)
7207 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7209 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7210 return DAG.getNode(ISD::BITCAST, dl, VT,
7211 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7212 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7213 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7217 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7218 SDValue V1 = Op.getOperand(0);
7219 SDValue V2 = Op.getOperand(1);
7220 MVT VT = Op.getSimpleValueType();
7222 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7223 "unsupported shuffle type");
7225 if (V2.getOpcode() == ISD::UNDEF)
7229 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7233 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7234 SDValue V1 = Op.getOperand(0);
7235 SDValue V2 = Op.getOperand(1);
7236 MVT VT = Op.getSimpleValueType();
7237 unsigned NumElems = VT.getVectorNumElements();
7239 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7240 // operand of these instructions is only memory, so check if there's a
7241 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7243 bool CanFoldLoad = false;
7245 // Trivial case, when V2 comes from a load.
7246 if (MayFoldVectorLoad(V2))
7249 // When V1 is a load, it can be folded later into a store in isel, example:
7250 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7252 // (MOVLPSmr addr:$src1, VR128:$src2)
7253 // So, recognize this potential and also use MOVLPS or MOVLPD
7254 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7257 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7259 if (HasSSE2 && NumElems == 2)
7260 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7263 // If we don't care about the second element, proceed to use movss.
7264 if (SVOp->getMaskElt(1) != -1)
7265 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7268 // movl and movlp will both match v2i64, but v2i64 is never matched by
7269 // movl earlier because we make it strict to avoid messing with the movlp load
7270 // folding logic (see the code above getMOVLP call). Match it here then,
7271 // this is horrible, but will stay like this until we move all shuffle
7272 // matching to x86 specific nodes. Note that for the 1st condition all
7273 // types are matched with movsd.
7275 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7276 // as to remove this logic from here, as much as possible
7277 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7278 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7279 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7282 assert(VT != MVT::v4i32 && "unsupported shuffle type");
7284 // Invert the operand order and use SHUFPS to match it.
7285 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7286 getShuffleSHUFImmediate(SVOp), DAG);
7289 // It is only safe to call this function if isINSERTPSMask is true for
7290 // this shufflevector mask.
7291 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
7292 SelectionDAG &DAG) {
7293 // Generate an insertps instruction when inserting an f32 from memory onto a
7294 // v4f32 or when copying a member from one v4f32 to another.
7295 // We also use it for transferring i32 from one register to another,
7296 // since it simply copies the same bits.
7297 // If we're transfering an i32 from memory to a specific element in a
7298 // register, we output a generic DAG that will match the PINSRD
7300 // TODO: Optimize for AVX cases too (VINSERTPS)
7301 MVT VT = SVOp->getSimpleValueType(0);
7302 MVT EVT = VT.getVectorElementType();
7303 SDValue V1 = SVOp->getOperand(0);
7304 SDValue V2 = SVOp->getOperand(1);
7305 auto Mask = SVOp->getMask();
7306 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
7307 "unsupported vector type for insertps/pinsrd");
7309 int FromV1 = std::count_if(Mask.begin(), Mask.end(),
7310 [](const int &i) { return i < 4; });
7318 DestIndex = std::find_if(Mask.begin(), Mask.end(),
7319 [](const int &i) { return i < 4; }) -
7324 DestIndex = std::find_if(Mask.begin(), Mask.end(),
7325 [](const int &i) { return i >= 4; }) -
7329 if (MayFoldLoad(From)) {
7330 // Trivial case, when From comes from a load and is only used by the
7331 // shuffle. Make it use insertps from the vector that we need from that
7333 SDValue Addr = From.getOperand(1);
7335 DAG.getNode(ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
7336 DAG.getConstant(DestIndex * EVT.getStoreSize(),
7337 Addr.getSimpleValueType()));
7339 LoadSDNode *Load = cast<LoadSDNode>(From);
7341 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
7342 DAG.getMachineFunction().getMachineMemOperand(
7343 Load->getMemOperand(), 0, EVT.getStoreSize()));
7345 if (EVT == MVT::f32) {
7346 // Create this as a scalar to vector to match the instruction pattern.
7347 SDValue LoadScalarToVector =
7348 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
7349 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
7350 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
7352 } else { // EVT == MVT::i32
7353 // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
7354 // instruction, to match the PINSRD instruction, which loads an i32 to a
7355 // certain vector element.
7356 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
7357 DAG.getConstant(DestIndex, MVT::i32));
7361 // Vector-element-to-vector
7362 unsigned SrcIndex = Mask[DestIndex] % 4;
7363 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
7364 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
7367 // Reduce a vector shuffle to zext.
7368 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7369 SelectionDAG &DAG) {
7370 // PMOVZX is only available from SSE41.
7371 if (!Subtarget->hasSSE41())
7374 MVT VT = Op.getSimpleValueType();
7376 // Only AVX2 support 256-bit vector integer extending.
7377 if (!Subtarget->hasInt256() && VT.is256BitVector())
7380 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7382 SDValue V1 = Op.getOperand(0);
7383 SDValue V2 = Op.getOperand(1);
7384 unsigned NumElems = VT.getVectorNumElements();
7386 // Extending is an unary operation and the element type of the source vector
7387 // won't be equal to or larger than i64.
7388 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7389 VT.getVectorElementType() == MVT::i64)
7392 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7393 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7394 while ((1U << Shift) < NumElems) {
7395 if (SVOp->getMaskElt(1U << Shift) == 1)
7398 // The maximal ratio is 8, i.e. from i8 to i64.
7403 // Check the shuffle mask.
7404 unsigned Mask = (1U << Shift) - 1;
7405 for (unsigned i = 0; i != NumElems; ++i) {
7406 int EltIdx = SVOp->getMaskElt(i);
7407 if ((i & Mask) != 0 && EltIdx != -1)
7409 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7413 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7414 MVT NeVT = MVT::getIntegerVT(NBits);
7415 MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7417 if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7420 // Simplify the operand as it's prepared to be fed into shuffle.
7421 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7422 if (V1.getOpcode() == ISD::BITCAST &&
7423 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7424 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7425 V1.getOperand(0).getOperand(0)
7426 .getSimpleValueType().getSizeInBits() == SignificantBits) {
7427 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7428 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7429 ConstantSDNode *CIdx =
7430 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7431 // If it's foldable, i.e. normal load with single use, we will let code
7432 // selection to fold it. Otherwise, we will short the conversion sequence.
7433 if (CIdx && CIdx->getZExtValue() == 0 &&
7434 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7435 MVT FullVT = V.getSimpleValueType();
7436 MVT V1VT = V1.getSimpleValueType();
7437 if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7438 // The "ext_vec_elt" node is wider than the result node.
7439 // In this case we should extract subvector from V.
7440 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7441 unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7442 MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7443 FullVT.getVectorNumElements()/Ratio);
7444 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7445 DAG.getIntPtrConstant(0));
7447 V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7451 return DAG.getNode(ISD::BITCAST, DL, VT,
7452 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7456 NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7457 SelectionDAG &DAG) {
7458 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7459 MVT VT = Op.getSimpleValueType();
7461 SDValue V1 = Op.getOperand(0);
7462 SDValue V2 = Op.getOperand(1);
7464 if (isZeroShuffle(SVOp))
7465 return getZeroVector(VT, Subtarget, DAG, dl);
7467 // Handle splat operations
7468 if (SVOp->isSplat()) {
7469 // Use vbroadcast whenever the splat comes from a foldable load
7470 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7471 if (Broadcast.getNode())
7475 // Check integer expanding shuffles.
7476 SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7477 if (NewOp.getNode())
7480 // If the shuffle can be profitably rewritten as a narrower shuffle, then
7482 if (VT == MVT::v8i16 || VT == MVT::v16i8 ||
7483 VT == MVT::v16i16 || VT == MVT::v32i8) {
7484 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7485 if (NewOp.getNode())
7486 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7487 } else if ((VT == MVT::v4i32 ||
7488 (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
7489 // FIXME: Figure out a cleaner way to do this.
7490 // Try to make use of movq to zero out the top part.
7491 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7492 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7493 if (NewOp.getNode()) {
7494 MVT NewVT = NewOp.getSimpleValueType();
7495 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7496 NewVT, true, false))
7497 return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
7498 DAG, Subtarget, dl);
7500 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7501 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7502 if (NewOp.getNode()) {
7503 MVT NewVT = NewOp.getSimpleValueType();
7504 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7505 return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
7506 DAG, Subtarget, dl);
7514 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7515 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7516 SDValue V1 = Op.getOperand(0);
7517 SDValue V2 = Op.getOperand(1);
7518 MVT VT = Op.getSimpleValueType();
7520 unsigned NumElems = VT.getVectorNumElements();
7521 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7522 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7523 bool V1IsSplat = false;
7524 bool V2IsSplat = false;
7525 bool HasSSE2 = Subtarget->hasSSE2();
7526 bool HasFp256 = Subtarget->hasFp256();
7527 bool HasInt256 = Subtarget->hasInt256();
7528 MachineFunction &MF = DAG.getMachineFunction();
7529 bool OptForSize = MF.getFunction()->getAttributes().
7530 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7532 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7534 if (V1IsUndef && V2IsUndef)
7535 return DAG.getUNDEF(VT);
7537 // When we create a shuffle node we put the UNDEF node to second operand,
7538 // but in some cases the first operand may be transformed to UNDEF.
7539 // In this case we should just commute the node.
7541 return CommuteVectorShuffle(SVOp, DAG);
7543 // Vector shuffle lowering takes 3 steps:
7545 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7546 // narrowing and commutation of operands should be handled.
7547 // 2) Matching of shuffles with known shuffle masks to x86 target specific
7549 // 3) Rewriting of unmatched masks into new generic shuffle operations,
7550 // so the shuffle can be broken into other shuffles and the legalizer can
7551 // try the lowering again.
7553 // The general idea is that no vector_shuffle operation should be left to
7554 // be matched during isel, all of them must be converted to a target specific
7557 // Normalize the input vectors. Here splats, zeroed vectors, profitable
7558 // narrowing and commutation of operands should be handled. The actual code
7559 // doesn't include all of those, work in progress...
7560 SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7561 if (NewOp.getNode())
7564 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7566 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7567 // unpckh_undef). Only use pshufd if speed is more important than size.
7568 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7569 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7570 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7571 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7573 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7574 V2IsUndef && MayFoldVectorLoad(V1))
7575 return getMOVDDup(Op, dl, V1, DAG);
7577 if (isMOVHLPS_v_undef_Mask(M, VT))
7578 return getMOVHighToLow(Op, dl, DAG);
7580 // Use to match splats
7581 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7582 (VT == MVT::v2f64 || VT == MVT::v2i64))
7583 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7585 if (isPSHUFDMask(M, VT)) {
7586 // The actual implementation will match the mask in the if above and then
7587 // during isel it can match several different instructions, not only pshufd
7588 // as its name says, sad but true, emulate the behavior for now...
7589 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7590 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7592 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7594 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7595 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7597 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7598 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7601 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7605 if (isPALIGNRMask(M, VT, Subtarget))
7606 return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7607 getShufflePALIGNRImmediate(SVOp),
7610 // Check if this can be converted into a logical shift.
7611 bool isLeft = false;
7614 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7615 if (isShift && ShVal.hasOneUse()) {
7616 // If the shifted value has multiple uses, it may be cheaper to use
7617 // v_set0 + movlhps or movhlps, etc.
7618 MVT EltVT = VT.getVectorElementType();
7619 ShAmt *= EltVT.getSizeInBits();
7620 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7623 if (isMOVLMask(M, VT)) {
7624 if (ISD::isBuildVectorAllZeros(V1.getNode()))
7625 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7626 if (!isMOVLPMask(M, VT)) {
7627 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7628 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7630 if (VT == MVT::v4i32 || VT == MVT::v4f32)
7631 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7635 // FIXME: fold these into legal mask.
7636 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7637 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7639 if (isMOVHLPSMask(M, VT))
7640 return getMOVHighToLow(Op, dl, DAG);
7642 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7643 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7645 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7646 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7648 if (isMOVLPMask(M, VT))
7649 return getMOVLP(Op, dl, DAG, HasSSE2);
7651 if (ShouldXformToMOVHLPS(M, VT) ||
7652 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7653 return CommuteVectorShuffle(SVOp, DAG);
7656 // No better options. Use a vshldq / vsrldq.
7657 MVT EltVT = VT.getVectorElementType();
7658 ShAmt *= EltVT.getSizeInBits();
7659 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7662 bool Commuted = false;
7663 // FIXME: This should also accept a bitcast of a splat? Be careful, not
7664 // 1,1,1,1 -> v8i16 though.
7665 V1IsSplat = isSplatVector(V1.getNode());
7666 V2IsSplat = isSplatVector(V2.getNode());
7668 // Canonicalize the splat or undef, if present, to be on the RHS.
7669 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7670 CommuteVectorShuffleMask(M, NumElems);
7672 std::swap(V1IsSplat, V2IsSplat);
7676 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7677 // Shuffling low element of v1 into undef, just return v1.
7680 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7681 // the instruction selector will not match, so get a canonical MOVL with
7682 // swapped operands to undo the commute.
7683 return getMOVL(DAG, dl, VT, V2, V1);
7686 if (isUNPCKLMask(M, VT, HasInt256))
7687 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7689 if (isUNPCKHMask(M, VT, HasInt256))
7690 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7693 // Normalize mask so all entries that point to V2 points to its first
7694 // element then try to match unpck{h|l} again. If match, return a
7695 // new vector_shuffle with the corrected mask.p
7696 SmallVector<int, 8> NewMask(M.begin(), M.end());
7697 NormalizeMask(NewMask, NumElems);
7698 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7699 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7700 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7701 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7705 // Commute is back and try unpck* again.
7706 // FIXME: this seems wrong.
7707 CommuteVectorShuffleMask(M, NumElems);
7709 std::swap(V1IsSplat, V2IsSplat);
7711 if (isUNPCKLMask(M, VT, HasInt256))
7712 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7714 if (isUNPCKHMask(M, VT, HasInt256))
7715 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7718 // Normalize the node to match x86 shuffle ops if needed
7719 if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
7720 return CommuteVectorShuffle(SVOp, DAG);
7722 // The checks below are all present in isShuffleMaskLegal, but they are
7723 // inlined here right now to enable us to directly emit target specific
7724 // nodes, and remove one by one until they don't return Op anymore.
7726 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7727 SVOp->getSplatIndex() == 0 && V2IsUndef) {
7728 if (VT == MVT::v2f64 || VT == MVT::v2i64)
7729 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7732 if (isPSHUFHWMask(M, VT, HasInt256))
7733 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7734 getShufflePSHUFHWImmediate(SVOp),
7737 if (isPSHUFLWMask(M, VT, HasInt256))
7738 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7739 getShufflePSHUFLWImmediate(SVOp),
7742 if (isSHUFPMask(M, VT))
7743 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7744 getShuffleSHUFImmediate(SVOp), DAG);
7746 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7747 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7748 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7749 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7751 //===--------------------------------------------------------------------===//
7752 // Generate target specific nodes for 128 or 256-bit shuffles only
7753 // supported in the AVX instruction set.
7756 // Handle VMOVDDUPY permutations
7757 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7758 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7760 // Handle VPERMILPS/D* permutations
7761 if (isVPERMILPMask(M, VT)) {
7762 if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
7763 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7764 getShuffleSHUFImmediate(SVOp), DAG);
7765 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7766 getShuffleSHUFImmediate(SVOp), DAG);
7769 // Handle VPERM2F128/VPERM2I128 permutations
7770 if (isVPERM2X128Mask(M, VT, HasFp256))
7771 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7772 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7774 SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7775 if (BlendOp.getNode())
7778 if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
7779 return getINSERTPS(SVOp, dl, DAG);
7782 if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
7783 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
7785 if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
7786 VT.is512BitVector()) {
7787 MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
7788 MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
7789 SmallVector<SDValue, 16> permclMask;
7790 for (unsigned i = 0; i != NumElems; ++i) {
7791 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
7794 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT,
7795 &permclMask[0], NumElems);
7797 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7798 return DAG.getNode(X86ISD::VPERMV, dl, VT,
7799 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7800 return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
7801 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
7804 //===--------------------------------------------------------------------===//
7805 // Since no target specific shuffle was selected for this generic one,
7806 // lower it into other known shuffles. FIXME: this isn't true yet, but
7807 // this is the plan.
7810 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7811 if (VT == MVT::v8i16) {
7812 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7813 if (NewOp.getNode())
7817 if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
7818 SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
7819 if (NewOp.getNode())
7823 if (VT == MVT::v16i8) {
7824 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
7825 if (NewOp.getNode())
7829 if (VT == MVT::v32i8) {
7830 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7831 if (NewOp.getNode())
7835 // Handle all 128-bit wide vectors with 4 elements, and match them with
7836 // several different shuffle types.
7837 if (NumElems == 4 && VT.is128BitVector())
7838 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7840 // Handle general 256-bit shuffles
7841 if (VT.is256BitVector())
7842 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7847 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7848 MVT VT = Op.getSimpleValueType();
7851 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
7854 if (VT.getSizeInBits() == 8) {
7855 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7856 Op.getOperand(0), Op.getOperand(1));
7857 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7858 DAG.getValueType(VT));
7859 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7862 if (VT.getSizeInBits() == 16) {
7863 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7864 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7866 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7867 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7868 DAG.getNode(ISD::BITCAST, dl,
7872 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7873 Op.getOperand(0), Op.getOperand(1));
7874 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7875 DAG.getValueType(VT));
7876 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7879 if (VT == MVT::f32) {
7880 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7881 // the result back to FR32 register. It's only worth matching if the
7882 // result has a single use which is a store or a bitcast to i32. And in
7883 // the case of a store, it's not worth it if the index is a constant 0,
7884 // because a MOVSSmr can be used instead, which is smaller and faster.
7885 if (!Op.hasOneUse())
7887 SDNode *User = *Op.getNode()->use_begin();
7888 if ((User->getOpcode() != ISD::STORE ||
7889 (isa<ConstantSDNode>(Op.getOperand(1)) &&
7890 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7891 (User->getOpcode() != ISD::BITCAST ||
7892 User->getValueType(0) != MVT::i32))
7894 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7895 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7898 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7901 if (VT == MVT::i32 || VT == MVT::i64) {
7902 // ExtractPS/pextrq works with constant index.
7903 if (isa<ConstantSDNode>(Op.getOperand(1)))
7909 /// Extract one bit from mask vector, like v16i1 or v8i1.
7910 /// AVX-512 feature.
7912 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
7913 SDValue Vec = Op.getOperand(0);
7915 MVT VecVT = Vec.getSimpleValueType();
7916 SDValue Idx = Op.getOperand(1);
7917 MVT EltVT = Op.getSimpleValueType();
7919 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
7921 // variable index can't be handled in mask registers,
7922 // extend vector to VR512
7923 if (!isa<ConstantSDNode>(Idx)) {
7924 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
7925 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
7926 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
7927 ExtVT.getVectorElementType(), Ext, Idx);
7928 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
7931 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7932 const TargetRegisterClass* rc = getRegClassFor(VecVT);
7933 unsigned MaxSift = rc->getSize()*8 - 1;
7934 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
7935 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
7936 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
7937 DAG.getConstant(MaxSift, MVT::i8));
7938 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
7939 DAG.getIntPtrConstant(0));
7943 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7944 SelectionDAG &DAG) const {
7946 SDValue Vec = Op.getOperand(0);
7947 MVT VecVT = Vec.getSimpleValueType();
7948 SDValue Idx = Op.getOperand(1);
7950 if (Op.getSimpleValueType() == MVT::i1)
7951 return ExtractBitFromMaskVector(Op, DAG);
7953 if (!isa<ConstantSDNode>(Idx)) {
7954 if (VecVT.is512BitVector() ||
7955 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
7956 VecVT.getVectorElementType().getSizeInBits() == 32)) {
7959 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
7960 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
7961 MaskEltVT.getSizeInBits());
7963 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
7964 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
7965 getZeroVector(MaskVT, Subtarget, DAG, dl),
7966 Idx, DAG.getConstant(0, getPointerTy()));
7967 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
7968 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
7969 Perm, DAG.getConstant(0, getPointerTy()));
7974 // If this is a 256-bit vector result, first extract the 128-bit vector and
7975 // then extract the element from the 128-bit vector.
7976 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
7978 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7979 // Get the 128-bit vector.
7980 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7981 MVT EltVT = VecVT.getVectorElementType();
7983 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
7985 //if (IdxVal >= NumElems/2)
7986 // IdxVal -= NumElems/2;
7987 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
7988 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7989 DAG.getConstant(IdxVal, MVT::i32));
7992 assert(VecVT.is128BitVector() && "Unexpected vector length");
7994 if (Subtarget->hasSSE41()) {
7995 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
8000 MVT VT = Op.getSimpleValueType();
8001 // TODO: handle v16i8.
8002 if (VT.getSizeInBits() == 16) {
8003 SDValue Vec = Op.getOperand(0);
8004 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8006 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8007 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8008 DAG.getNode(ISD::BITCAST, dl,
8011 // Transform it so it match pextrw which produces a 32-bit result.
8012 MVT EltVT = MVT::i32;
8013 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
8014 Op.getOperand(0), Op.getOperand(1));
8015 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
8016 DAG.getValueType(VT));
8017 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8020 if (VT.getSizeInBits() == 32) {
8021 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8025 // SHUFPS the element to the lowest double word, then movss.
8026 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
8027 MVT VVT = Op.getOperand(0).getSimpleValueType();
8028 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8029 DAG.getUNDEF(VVT), Mask);
8030 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8031 DAG.getIntPtrConstant(0));
8034 if (VT.getSizeInBits() == 64) {
8035 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
8036 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
8037 // to match extract_elt for f64.
8038 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8042 // UNPCKHPD the element to the lowest double word, then movsd.
8043 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
8044 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
8045 int Mask[2] = { 1, -1 };
8046 MVT VVT = Op.getOperand(0).getSimpleValueType();
8047 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8048 DAG.getUNDEF(VVT), Mask);
8049 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8050 DAG.getIntPtrConstant(0));
8056 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8057 MVT VT = Op.getSimpleValueType();
8058 MVT EltVT = VT.getVectorElementType();
8061 SDValue N0 = Op.getOperand(0);
8062 SDValue N1 = Op.getOperand(1);
8063 SDValue N2 = Op.getOperand(2);
8065 if (!VT.is128BitVector())
8068 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
8069 isa<ConstantSDNode>(N2)) {
8071 if (VT == MVT::v8i16)
8072 Opc = X86ISD::PINSRW;
8073 else if (VT == MVT::v16i8)
8074 Opc = X86ISD::PINSRB;
8076 Opc = X86ISD::PINSRB;
8078 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
8080 if (N1.getValueType() != MVT::i32)
8081 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8082 if (N2.getValueType() != MVT::i32)
8083 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8084 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
8087 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
8088 // Bits [7:6] of the constant are the source select. This will always be
8089 // zero here. The DAG Combiner may combine an extract_elt index into these
8090 // bits. For example (insert (extract, 3), 2) could be matched by putting
8091 // the '3' into bits [7:6] of X86ISD::INSERTPS.
8092 // Bits [5:4] of the constant are the destination select. This is the
8093 // value of the incoming immediate.
8094 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
8095 // combine either bitwise AND or insert of float 0.0 to set these bits.
8096 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
8097 // Create this as a scalar to vector..
8098 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
8099 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
8102 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
8103 // PINSR* works with constant index.
8109 /// Insert one bit to mask vector, like v16i1 or v8i1.
8110 /// AVX-512 feature.
8112 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
8114 SDValue Vec = Op.getOperand(0);
8115 SDValue Elt = Op.getOperand(1);
8116 SDValue Idx = Op.getOperand(2);
8117 MVT VecVT = Vec.getSimpleValueType();
8119 if (!isa<ConstantSDNode>(Idx)) {
8120 // Non constant index. Extend source and destination,
8121 // insert element and then truncate the result.
8122 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
8123 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
8124 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
8125 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
8126 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
8127 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
8130 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8131 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
8132 if (Vec.getOpcode() == ISD::UNDEF)
8133 return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8134 DAG.getConstant(IdxVal, MVT::i8));
8135 const TargetRegisterClass* rc = getRegClassFor(VecVT);
8136 unsigned MaxSift = rc->getSize()*8 - 1;
8137 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8138 DAG.getConstant(MaxSift, MVT::i8));
8139 EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
8140 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8141 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
8144 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
8145 MVT VT = Op.getSimpleValueType();
8146 MVT EltVT = VT.getVectorElementType();
8148 if (EltVT == MVT::i1)
8149 return InsertBitToMaskVector(Op, DAG);
8152 SDValue N0 = Op.getOperand(0);
8153 SDValue N1 = Op.getOperand(1);
8154 SDValue N2 = Op.getOperand(2);
8156 // If this is a 256-bit vector result, first extract the 128-bit vector,
8157 // insert the element into the extracted half and then place it back.
8158 if (VT.is256BitVector() || VT.is512BitVector()) {
8159 if (!isa<ConstantSDNode>(N2))
8162 // Get the desired 128-bit vector half.
8163 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
8164 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
8166 // Insert the element into the desired half.
8167 unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
8168 unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
8170 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
8171 DAG.getConstant(IdxIn128, MVT::i32));
8173 // Insert the changed part back to the 256-bit vector
8174 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
8177 if (Subtarget->hasSSE41())
8178 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
8180 if (EltVT == MVT::i8)
8183 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
8184 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
8185 // as its second argument.
8186 if (N1.getValueType() != MVT::i32)
8187 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8188 if (N2.getValueType() != MVT::i32)
8189 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8190 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
8195 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
8197 MVT OpVT = Op.getSimpleValueType();
8199 // If this is a 256-bit vector result, first insert into a 128-bit
8200 // vector and then insert into the 256-bit vector.
8201 if (!OpVT.is128BitVector()) {
8202 // Insert into a 128-bit vector.
8203 unsigned SizeFactor = OpVT.getSizeInBits()/128;
8204 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
8205 OpVT.getVectorNumElements() / SizeFactor);
8207 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
8209 // Insert the 128-bit vector.
8210 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
8213 if (OpVT == MVT::v1i64 &&
8214 Op.getOperand(0).getValueType() == MVT::i64)
8215 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
8217 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
8218 assert(OpVT.is128BitVector() && "Expected an SSE type!");
8219 return DAG.getNode(ISD::BITCAST, dl, OpVT,
8220 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
8223 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
8224 // a simple subregister reference or explicit instructions to grab
8225 // upper bits of a vector.
8226 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8227 SelectionDAG &DAG) {
8229 SDValue In = Op.getOperand(0);
8230 SDValue Idx = Op.getOperand(1);
8231 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8232 MVT ResVT = Op.getSimpleValueType();
8233 MVT InVT = In.getSimpleValueType();
8235 if (Subtarget->hasFp256()) {
8236 if (ResVT.is128BitVector() &&
8237 (InVT.is256BitVector() || InVT.is512BitVector()) &&
8238 isa<ConstantSDNode>(Idx)) {
8239 return Extract128BitVector(In, IdxVal, DAG, dl);
8241 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
8242 isa<ConstantSDNode>(Idx)) {
8243 return Extract256BitVector(In, IdxVal, DAG, dl);
8249 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
8250 // simple superregister reference or explicit instructions to insert
8251 // the upper bits of a vector.
8252 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8253 SelectionDAG &DAG) {
8254 if (Subtarget->hasFp256()) {
8255 SDLoc dl(Op.getNode());
8256 SDValue Vec = Op.getNode()->getOperand(0);
8257 SDValue SubVec = Op.getNode()->getOperand(1);
8258 SDValue Idx = Op.getNode()->getOperand(2);
8260 if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8261 Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8262 SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8263 isa<ConstantSDNode>(Idx)) {
8264 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8265 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8268 if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8269 SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8270 isa<ConstantSDNode>(Idx)) {
8271 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8272 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8278 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8279 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8280 // one of the above mentioned nodes. It has to be wrapped because otherwise
8281 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8282 // be used to form addressing mode. These wrapped nodes will be selected
8285 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8286 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8288 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8290 unsigned char OpFlag = 0;
8291 unsigned WrapperKind = X86ISD::Wrapper;
8292 CodeModel::Model M = getTargetMachine().getCodeModel();
8294 if (Subtarget->isPICStyleRIPRel() &&
8295 (M == CodeModel::Small || M == CodeModel::Kernel))
8296 WrapperKind = X86ISD::WrapperRIP;
8297 else if (Subtarget->isPICStyleGOT())
8298 OpFlag = X86II::MO_GOTOFF;
8299 else if (Subtarget->isPICStyleStubPIC())
8300 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8302 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8304 CP->getOffset(), OpFlag);
8306 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8307 // With PIC, the address is actually $g + Offset.
8309 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8310 DAG.getNode(X86ISD::GlobalBaseReg,
8311 SDLoc(), getPointerTy()),
8318 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8319 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8321 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8323 unsigned char OpFlag = 0;
8324 unsigned WrapperKind = X86ISD::Wrapper;
8325 CodeModel::Model M = getTargetMachine().getCodeModel();
8327 if (Subtarget->isPICStyleRIPRel() &&
8328 (M == CodeModel::Small || M == CodeModel::Kernel))
8329 WrapperKind = X86ISD::WrapperRIP;
8330 else if (Subtarget->isPICStyleGOT())
8331 OpFlag = X86II::MO_GOTOFF;
8332 else if (Subtarget->isPICStyleStubPIC())
8333 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8335 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8338 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8340 // With PIC, the address is actually $g + Offset.
8342 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8343 DAG.getNode(X86ISD::GlobalBaseReg,
8344 SDLoc(), getPointerTy()),
8351 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8352 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8354 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8356 unsigned char OpFlag = 0;
8357 unsigned WrapperKind = X86ISD::Wrapper;
8358 CodeModel::Model M = getTargetMachine().getCodeModel();
8360 if (Subtarget->isPICStyleRIPRel() &&
8361 (M == CodeModel::Small || M == CodeModel::Kernel)) {
8362 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8363 OpFlag = X86II::MO_GOTPCREL;
8364 WrapperKind = X86ISD::WrapperRIP;
8365 } else if (Subtarget->isPICStyleGOT()) {
8366 OpFlag = X86II::MO_GOT;
8367 } else if (Subtarget->isPICStyleStubPIC()) {
8368 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8369 } else if (Subtarget->isPICStyleStubNoDynamic()) {
8370 OpFlag = X86II::MO_DARWIN_NONLAZY;
8373 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8376 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8378 // With PIC, the address is actually $g + Offset.
8379 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
8380 !Subtarget->is64Bit()) {
8381 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8382 DAG.getNode(X86ISD::GlobalBaseReg,
8383 SDLoc(), getPointerTy()),
8387 // For symbols that require a load from a stub to get the address, emit the
8389 if (isGlobalStubReference(OpFlag))
8390 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8391 MachinePointerInfo::getGOT(), false, false, false, 0);
8397 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8398 // Create the TargetBlockAddressAddress node.
8399 unsigned char OpFlags =
8400 Subtarget->ClassifyBlockAddressReference();
8401 CodeModel::Model M = getTargetMachine().getCodeModel();
8402 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8403 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8405 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8408 if (Subtarget->isPICStyleRIPRel() &&
8409 (M == CodeModel::Small || M == CodeModel::Kernel))
8410 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8412 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8414 // With PIC, the address is actually $g + Offset.
8415 if (isGlobalRelativeToPICBase(OpFlags)) {
8416 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8417 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8425 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8426 int64_t Offset, SelectionDAG &DAG) const {
8427 // Create the TargetGlobalAddress node, folding in the constant
8428 // offset if it is legal.
8429 unsigned char OpFlags =
8430 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
8431 CodeModel::Model M = getTargetMachine().getCodeModel();
8433 if (OpFlags == X86II::MO_NO_FLAG &&
8434 X86::isOffsetSuitableForCodeModel(Offset, M)) {
8435 // A direct static reference to a global.
8436 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8439 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8442 if (Subtarget->isPICStyleRIPRel() &&
8443 (M == CodeModel::Small || M == CodeModel::Kernel))
8444 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8446 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8448 // With PIC, the address is actually $g + Offset.
8449 if (isGlobalRelativeToPICBase(OpFlags)) {
8450 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8451 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8455 // For globals that require a load from a stub to get the address, emit the
8457 if (isGlobalStubReference(OpFlags))
8458 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8459 MachinePointerInfo::getGOT(), false, false, false, 0);
8461 // If there was a non-zero offset that we didn't fold, create an explicit
8464 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8465 DAG.getConstant(Offset, getPointerTy()));
8471 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8472 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8473 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8474 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8478 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8479 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8480 unsigned char OperandFlags, bool LocalDynamic = false) {
8481 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8482 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8484 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8485 GA->getValueType(0),
8489 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8493 SDValue Ops[] = { Chain, TGA, *InFlag };
8494 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8496 SDValue Ops[] = { Chain, TGA };
8497 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8500 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8501 MFI->setAdjustsStack(true);
8503 SDValue Flag = Chain.getValue(1);
8504 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8507 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8509 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8512 SDLoc dl(GA); // ? function entry point might be better
8513 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8514 DAG.getNode(X86ISD::GlobalBaseReg,
8515 SDLoc(), PtrVT), InFlag);
8516 InFlag = Chain.getValue(1);
8518 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8521 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8523 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8525 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
8526 X86::RAX, X86II::MO_TLSGD);
8529 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8535 // Get the start address of the TLS block for this module.
8536 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8537 .getInfo<X86MachineFunctionInfo>();
8538 MFI->incNumLocalDynamicTLSAccesses();
8542 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
8543 X86II::MO_TLSLD, /*LocalDynamic=*/true);
8546 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8547 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8548 InFlag = Chain.getValue(1);
8549 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8550 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8553 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8557 unsigned char OperandFlags = X86II::MO_DTPOFF;
8558 unsigned WrapperKind = X86ISD::Wrapper;
8559 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8560 GA->getValueType(0),
8561 GA->getOffset(), OperandFlags);
8562 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8564 // Add x@dtpoff with the base.
8565 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8568 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8569 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8570 const EVT PtrVT, TLSModel::Model model,
8571 bool is64Bit, bool isPIC) {
8574 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8575 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8576 is64Bit ? 257 : 256));
8578 SDValue ThreadPointer =
8579 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
8580 MachinePointerInfo(Ptr), false, false, false, 0);
8582 unsigned char OperandFlags = 0;
8583 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
8585 unsigned WrapperKind = X86ISD::Wrapper;
8586 if (model == TLSModel::LocalExec) {
8587 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8588 } else if (model == TLSModel::InitialExec) {
8590 OperandFlags = X86II::MO_GOTTPOFF;
8591 WrapperKind = X86ISD::WrapperRIP;
8593 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8596 llvm_unreachable("Unexpected model");
8599 // emit "addl x@ntpoff,%eax" (local exec)
8600 // or "addl x@indntpoff,%eax" (initial exec)
8601 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8603 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
8604 GA->getOffset(), OperandFlags);
8605 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8607 if (model == TLSModel::InitialExec) {
8608 if (isPIC && !is64Bit) {
8609 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8610 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8614 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8615 MachinePointerInfo::getGOT(), false, false, false, 0);
8618 // The address of the thread local variable is the add of the thread
8619 // pointer with the offset of the variable.
8620 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8624 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8626 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8627 const GlobalValue *GV = GA->getGlobal();
8629 if (Subtarget->isTargetELF()) {
8630 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8633 case TLSModel::GeneralDynamic:
8634 if (Subtarget->is64Bit())
8635 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8636 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8637 case TLSModel::LocalDynamic:
8638 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8639 Subtarget->is64Bit());
8640 case TLSModel::InitialExec:
8641 case TLSModel::LocalExec:
8642 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8643 Subtarget->is64Bit(),
8644 getTargetMachine().getRelocationModel() == Reloc::PIC_);
8646 llvm_unreachable("Unknown TLS model.");
8649 if (Subtarget->isTargetDarwin()) {
8650 // Darwin only has one model of TLS. Lower to that.
8651 unsigned char OpFlag = 0;
8652 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8653 X86ISD::WrapperRIP : X86ISD::Wrapper;
8655 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8657 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8658 !Subtarget->is64Bit();
8660 OpFlag = X86II::MO_TLVP_PIC_BASE;
8662 OpFlag = X86II::MO_TLVP;
8664 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8665 GA->getValueType(0),
8666 GA->getOffset(), OpFlag);
8667 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8669 // With PIC32, the address is actually $g + Offset.
8671 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8672 DAG.getNode(X86ISD::GlobalBaseReg,
8673 SDLoc(), getPointerTy()),
8676 // Lowering the machine isd will make sure everything is in the right
8678 SDValue Chain = DAG.getEntryNode();
8679 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8680 SDValue Args[] = { Chain, Offset };
8681 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
8683 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8684 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8685 MFI->setAdjustsStack(true);
8687 // And our return value (tls address) is in the standard call return value
8689 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8690 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8694 if (Subtarget->isTargetKnownWindowsMSVC() ||
8695 Subtarget->isTargetWindowsGNU()) {
8696 // Just use the implicit TLS architecture
8697 // Need to generate someting similar to:
8698 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8700 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
8701 // mov rcx, qword [rdx+rcx*8]
8702 // mov eax, .tls$:tlsvar
8703 // [rax+rcx] contains the address
8704 // Windows 64bit: gs:0x58
8705 // Windows 32bit: fs:__tls_array
8707 // If GV is an alias then use the aliasee for determining
8708 // thread-localness.
8709 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
8710 GV = GA->getAliasedGlobal();
8712 SDValue Chain = DAG.getEntryNode();
8714 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8715 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8716 // use its literal value of 0x2C.
8717 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8718 ? Type::getInt8PtrTy(*DAG.getContext(),
8720 : Type::getInt32PtrTy(*DAG.getContext(),
8724 Subtarget->is64Bit()
8725 ? DAG.getIntPtrConstant(0x58)
8726 : (Subtarget->isTargetWindowsGNU()
8727 ? DAG.getIntPtrConstant(0x2C)
8728 : DAG.getExternalSymbol("_tls_array", getPointerTy()));
8730 SDValue ThreadPointer =
8731 DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8732 MachinePointerInfo(Ptr), false, false, false, 0);
8734 // Load the _tls_index variable
8735 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8736 if (Subtarget->is64Bit())
8737 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8738 IDX, MachinePointerInfo(), MVT::i32,
8741 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
8742 false, false, false, 0);
8744 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
8746 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
8748 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
8749 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
8750 false, false, false, 0);
8752 // Get the offset of start of .tls section
8753 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8754 GA->getValueType(0),
8755 GA->getOffset(), X86II::MO_SECREL);
8756 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
8758 // The address of the thread local variable is the add of the thread
8759 // pointer with the offset of the variable.
8760 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
8763 llvm_unreachable("TLS not implemented for this target.");
8766 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
8767 /// and take a 2 x i32 value to shift plus a shift amount.
8768 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
8769 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
8770 MVT VT = Op.getSimpleValueType();
8771 unsigned VTBits = VT.getSizeInBits();
8773 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
8774 SDValue ShOpLo = Op.getOperand(0);
8775 SDValue ShOpHi = Op.getOperand(1);
8776 SDValue ShAmt = Op.getOperand(2);
8777 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
8778 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
8780 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8781 DAG.getConstant(VTBits - 1, MVT::i8));
8782 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
8783 DAG.getConstant(VTBits - 1, MVT::i8))
8784 : DAG.getConstant(0, VT);
8787 if (Op.getOpcode() == ISD::SHL_PARTS) {
8788 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
8789 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
8791 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
8792 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
8795 // If the shift amount is larger or equal than the width of a part we can't
8796 // rely on the results of shld/shrd. Insert a test and select the appropriate
8797 // values for large shift amounts.
8798 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8799 DAG.getConstant(VTBits, MVT::i8));
8800 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8801 AndNode, DAG.getConstant(0, MVT::i8));
8804 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8805 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
8806 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
8808 if (Op.getOpcode() == ISD::SHL_PARTS) {
8809 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8810 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8812 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8813 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8816 SDValue Ops[2] = { Lo, Hi };
8817 return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
8820 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
8821 SelectionDAG &DAG) const {
8822 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
8824 if (SrcVT.isVector())
8827 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
8828 "Unknown SINT_TO_FP to lower!");
8830 // These are really Legal; return the operand so the caller accepts it as
8832 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
8834 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
8835 Subtarget->is64Bit()) {
8840 unsigned Size = SrcVT.getSizeInBits()/8;
8841 MachineFunction &MF = DAG.getMachineFunction();
8842 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8843 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8844 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8846 MachinePointerInfo::getFixedStack(SSFI),
8848 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8851 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8853 SelectionDAG &DAG) const {
8857 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8859 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8861 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8863 unsigned ByteSize = SrcVT.getSizeInBits()/8;
8865 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8866 MachineMemOperand *MMO;
8868 int SSFI = FI->getIndex();
8870 DAG.getMachineFunction()
8871 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8872 MachineMemOperand::MOLoad, ByteSize, ByteSize);
8874 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8875 StackSlot = StackSlot.getOperand(1);
8877 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8878 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8880 Tys, Ops, array_lengthof(Ops),
8884 Chain = Result.getValue(1);
8885 SDValue InFlag = Result.getValue(2);
8887 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8888 // shouldn't be necessary except that RFP cannot be live across
8889 // multiple blocks. When stackifier is fixed, they can be uncoupled.
8890 MachineFunction &MF = DAG.getMachineFunction();
8891 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8892 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8893 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8894 Tys = DAG.getVTList(MVT::Other);
8896 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8898 MachineMemOperand *MMO =
8899 DAG.getMachineFunction()
8900 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8901 MachineMemOperand::MOStore, SSFISize, SSFISize);
8903 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8904 Ops, array_lengthof(Ops),
8905 Op.getValueType(), MMO);
8906 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8907 MachinePointerInfo::getFixedStack(SSFI),
8908 false, false, false, 0);
8914 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8915 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8916 SelectionDAG &DAG) const {
8917 // This algorithm is not obvious. Here it is what we're trying to output:
8920 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8921 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8925 pshufd $0x4e, %xmm0, %xmm1
8931 LLVMContext *Context = DAG.getContext();
8933 // Build some magic constants.
8934 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8935 Constant *C0 = ConstantDataVector::get(*Context, CV0);
8936 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8938 SmallVector<Constant*,2> CV1;
8940 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8941 APInt(64, 0x4330000000000000ULL))));
8943 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8944 APInt(64, 0x4530000000000000ULL))));
8945 Constant *C1 = ConstantVector::get(CV1);
8946 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8948 // Load the 64-bit value into an XMM register.
8949 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8951 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8952 MachinePointerInfo::getConstantPool(),
8953 false, false, false, 16);
8954 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8955 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8958 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8959 MachinePointerInfo::getConstantPool(),
8960 false, false, false, 16);
8961 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8962 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8965 if (Subtarget->hasSSE3()) {
8966 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8967 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8969 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8970 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8972 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8973 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8977 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8978 DAG.getIntPtrConstant(0));
8981 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8982 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8983 SelectionDAG &DAG) const {
8985 // FP constant to bias correct the final result.
8986 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8989 // Load the 32-bit value into an XMM register.
8990 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8993 // Zero out the upper parts of the register.
8994 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8996 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8997 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8998 DAG.getIntPtrConstant(0));
9000 // Or the load with the bias.
9001 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
9002 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9003 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9005 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9006 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9007 MVT::v2f64, Bias)));
9008 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9009 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
9010 DAG.getIntPtrConstant(0));
9012 // Subtract the bias.
9013 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
9015 // Handle final rounding.
9016 EVT DestVT = Op.getValueType();
9018 if (DestVT.bitsLT(MVT::f64))
9019 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
9020 DAG.getIntPtrConstant(0));
9021 if (DestVT.bitsGT(MVT::f64))
9022 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
9024 // Handle final rounding.
9028 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
9029 SelectionDAG &DAG) const {
9030 SDValue N0 = Op.getOperand(0);
9031 MVT SVT = N0.getSimpleValueType();
9034 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
9035 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
9036 "Custom UINT_TO_FP is not supported!");
9038 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
9039 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
9040 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
9043 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
9044 SelectionDAG &DAG) const {
9045 SDValue N0 = Op.getOperand(0);
9048 if (Op.getValueType().isVector())
9049 return lowerUINT_TO_FP_vec(Op, DAG);
9051 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
9052 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
9053 // the optimization here.
9054 if (DAG.SignBitIsZero(N0))
9055 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
9057 MVT SrcVT = N0.getSimpleValueType();
9058 MVT DstVT = Op.getSimpleValueType();
9059 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
9060 return LowerUINT_TO_FP_i64(Op, DAG);
9061 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
9062 return LowerUINT_TO_FP_i32(Op, DAG);
9063 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
9066 // Make a 64-bit buffer, and use it to build an FILD.
9067 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
9068 if (SrcVT == MVT::i32) {
9069 SDValue WordOff = DAG.getConstant(4, getPointerTy());
9070 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
9071 getPointerTy(), StackSlot, WordOff);
9072 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9073 StackSlot, MachinePointerInfo(),
9075 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
9076 OffsetSlot, MachinePointerInfo(),
9078 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
9082 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
9083 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9084 StackSlot, MachinePointerInfo(),
9086 // For i64 source, we need to add the appropriate power of 2 if the input
9087 // was negative. This is the same as the optimization in
9088 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
9089 // we must be careful to do the computation in x87 extended precision, not
9090 // in SSE. (The generic code can't know it's OK to do this, or how to.)
9091 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
9092 MachineMemOperand *MMO =
9093 DAG.getMachineFunction()
9094 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9095 MachineMemOperand::MOLoad, 8, 8);
9097 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
9098 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
9099 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
9100 array_lengthof(Ops), MVT::i64, MMO);
9102 APInt FF(32, 0x5F800000ULL);
9104 // Check whether the sign bit is set.
9105 SDValue SignSet = DAG.getSetCC(dl,
9106 getSetCCResultType(*DAG.getContext(), MVT::i64),
9107 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
9110 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
9111 SDValue FudgePtr = DAG.getConstantPool(
9112 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
9115 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
9116 SDValue Zero = DAG.getIntPtrConstant(0);
9117 SDValue Four = DAG.getIntPtrConstant(4);
9118 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
9120 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
9122 // Load the value out, extending it from f32 to f80.
9123 // FIXME: Avoid the extend by constructing the right constant pool?
9124 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
9125 FudgePtr, MachinePointerInfo::getConstantPool(),
9126 MVT::f32, false, false, 4);
9127 // Extend everything to 80 bits to force it to be done on x87.
9128 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
9129 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
9132 std::pair<SDValue,SDValue>
9133 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
9134 bool IsSigned, bool IsReplace) const {
9137 EVT DstTy = Op.getValueType();
9139 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
9140 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
9144 assert(DstTy.getSimpleVT() <= MVT::i64 &&
9145 DstTy.getSimpleVT() >= MVT::i16 &&
9146 "Unknown FP_TO_INT to lower!");
9148 // These are really Legal.
9149 if (DstTy == MVT::i32 &&
9150 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9151 return std::make_pair(SDValue(), SDValue());
9152 if (Subtarget->is64Bit() &&
9153 DstTy == MVT::i64 &&
9154 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9155 return std::make_pair(SDValue(), SDValue());
9157 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
9158 // stack slot, or into the FTOL runtime function.
9159 MachineFunction &MF = DAG.getMachineFunction();
9160 unsigned MemSize = DstTy.getSizeInBits()/8;
9161 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9162 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9165 if (!IsSigned && isIntegerTypeFTOL(DstTy))
9166 Opc = X86ISD::WIN_FTOL;
9168 switch (DstTy.getSimpleVT().SimpleTy) {
9169 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
9170 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
9171 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
9172 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
9175 SDValue Chain = DAG.getEntryNode();
9176 SDValue Value = Op.getOperand(0);
9177 EVT TheVT = Op.getOperand(0).getValueType();
9178 // FIXME This causes a redundant load/store if the SSE-class value is already
9179 // in memory, such as if it is on the callstack.
9180 if (isScalarFPTypeInSSEReg(TheVT)) {
9181 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
9182 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
9183 MachinePointerInfo::getFixedStack(SSFI),
9185 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
9187 Chain, StackSlot, DAG.getValueType(TheVT)
9190 MachineMemOperand *MMO =
9191 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9192 MachineMemOperand::MOLoad, MemSize, MemSize);
9193 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops,
9194 array_lengthof(Ops), DstTy, MMO);
9195 Chain = Value.getValue(1);
9196 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9197 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9200 MachineMemOperand *MMO =
9201 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9202 MachineMemOperand::MOStore, MemSize, MemSize);
9204 if (Opc != X86ISD::WIN_FTOL) {
9205 // Build the FP_TO_INT*_IN_MEM
9206 SDValue Ops[] = { Chain, Value, StackSlot };
9207 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
9208 Ops, array_lengthof(Ops), DstTy,
9210 return std::make_pair(FIST, StackSlot);
9212 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
9213 DAG.getVTList(MVT::Other, MVT::Glue),
9215 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
9216 MVT::i32, ftol.getValue(1));
9217 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
9218 MVT::i32, eax.getValue(2));
9219 SDValue Ops[] = { eax, edx };
9220 SDValue pair = IsReplace
9221 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, array_lengthof(Ops))
9222 : DAG.getMergeValues(Ops, array_lengthof(Ops), DL);
9223 return std::make_pair(pair, SDValue());
9227 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
9228 const X86Subtarget *Subtarget) {
9229 MVT VT = Op->getSimpleValueType(0);
9230 SDValue In = Op->getOperand(0);
9231 MVT InVT = In.getSimpleValueType();
9234 // Optimize vectors in AVX mode:
9237 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
9238 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
9239 // Concat upper and lower parts.
9242 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
9243 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
9244 // Concat upper and lower parts.
9247 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
9248 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
9249 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
9252 if (Subtarget->hasInt256())
9253 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
9255 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
9256 SDValue Undef = DAG.getUNDEF(InVT);
9257 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9258 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9259 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9261 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9262 VT.getVectorNumElements()/2);
9264 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9265 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9267 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9270 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9271 SelectionDAG &DAG) {
9272 MVT VT = Op->getSimpleValueType(0);
9273 SDValue In = Op->getOperand(0);
9274 MVT InVT = In.getSimpleValueType();
9276 unsigned int NumElts = VT.getVectorNumElements();
9277 if (NumElts != 8 && NumElts != 16)
9280 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9281 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9283 EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9284 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9285 // Now we have only mask extension
9286 assert(InVT.getVectorElementType() == MVT::i1);
9287 SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9288 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9289 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9290 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9291 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9292 MachinePointerInfo::getConstantPool(),
9293 false, false, false, Alignment);
9295 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9296 if (VT.is512BitVector())
9298 return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9301 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9302 SelectionDAG &DAG) {
9303 if (Subtarget->hasFp256()) {
9304 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9312 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9313 SelectionDAG &DAG) {
9315 MVT VT = Op.getSimpleValueType();
9316 SDValue In = Op.getOperand(0);
9317 MVT SVT = In.getSimpleValueType();
9319 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9320 return LowerZERO_EXTEND_AVX512(Op, DAG);
9322 if (Subtarget->hasFp256()) {
9323 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9328 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9329 VT.getVectorNumElements() != SVT.getVectorNumElements());
9333 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9335 MVT VT = Op.getSimpleValueType();
9336 SDValue In = Op.getOperand(0);
9337 MVT InVT = In.getSimpleValueType();
9339 if (VT == MVT::i1) {
9340 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9341 "Invalid scalar TRUNCATE operation");
9342 if (InVT == MVT::i32)
9344 if (InVT.getSizeInBits() == 64)
9345 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9346 else if (InVT.getSizeInBits() < 32)
9347 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9348 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
9350 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9351 "Invalid TRUNCATE operation");
9353 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9354 if (VT.getVectorElementType().getSizeInBits() >=8)
9355 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9357 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9358 unsigned NumElts = InVT.getVectorNumElements();
9359 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9360 if (InVT.getSizeInBits() < 512) {
9361 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9362 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9366 SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9367 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9368 SDValue CP = DAG.getConstantPool(C, getPointerTy());
9369 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9370 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9371 MachinePointerInfo::getConstantPool(),
9372 false, false, false, Alignment);
9373 SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9374 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9375 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9378 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9379 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9380 if (Subtarget->hasInt256()) {
9381 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9382 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9383 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9385 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9386 DAG.getIntPtrConstant(0));
9389 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9390 DAG.getIntPtrConstant(0));
9391 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9392 DAG.getIntPtrConstant(2));
9393 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9394 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9395 static const int ShufMask[] = {0, 2, 4, 6};
9396 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
9399 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9400 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9401 if (Subtarget->hasInt256()) {
9402 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9404 SmallVector<SDValue,32> pshufbMask;
9405 for (unsigned i = 0; i < 2; ++i) {
9406 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9407 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9408 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9409 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9410 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9411 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9412 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9413 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9414 for (unsigned j = 0; j < 8; ++j)
9415 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9417 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
9418 &pshufbMask[0], 32);
9419 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9420 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9422 static const int ShufMask[] = {0, 2, -1, -1};
9423 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
9425 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9426 DAG.getIntPtrConstant(0));
9427 return DAG.getNode(ISD::BITCAST, DL, VT, In);
9430 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9431 DAG.getIntPtrConstant(0));
9433 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9434 DAG.getIntPtrConstant(4));
9436 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9437 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9440 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
9441 -1, -1, -1, -1, -1, -1, -1, -1};
9443 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9444 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9445 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9447 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9448 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9450 // The MOVLHPS Mask:
9451 static const int ShufMask2[] = {0, 1, 4, 5};
9452 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9453 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9456 // Handle truncation of V256 to V128 using shuffles.
9457 if (!VT.is128BitVector() || !InVT.is256BitVector())
9460 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9462 unsigned NumElems = VT.getVectorNumElements();
9463 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
9465 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9466 // Prepare truncation shuffle mask
9467 for (unsigned i = 0; i != NumElems; ++i)
9469 SDValue V = DAG.getVectorShuffle(NVT, DL,
9470 DAG.getNode(ISD::BITCAST, DL, NVT, In),
9471 DAG.getUNDEF(NVT), &MaskVec[0]);
9472 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9473 DAG.getIntPtrConstant(0));
9476 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9477 SelectionDAG &DAG) const {
9478 assert(!Op.getSimpleValueType().isVector());
9480 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9481 /*IsSigned=*/ true, /*IsReplace=*/ false);
9482 SDValue FIST = Vals.first, StackSlot = Vals.second;
9483 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9484 if (!FIST.getNode()) return Op;
9486 if (StackSlot.getNode())
9488 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9489 FIST, StackSlot, MachinePointerInfo(),
9490 false, false, false, 0);
9492 // The node is the result.
9496 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9497 SelectionDAG &DAG) const {
9498 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9499 /*IsSigned=*/ false, /*IsReplace=*/ false);
9500 SDValue FIST = Vals.first, StackSlot = Vals.second;
9501 assert(FIST.getNode() && "Unexpected failure");
9503 if (StackSlot.getNode())
9505 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9506 FIST, StackSlot, MachinePointerInfo(),
9507 false, false, false, 0);
9509 // The node is the result.
9513 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9515 MVT VT = Op.getSimpleValueType();
9516 SDValue In = Op.getOperand(0);
9517 MVT SVT = In.getSimpleValueType();
9519 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9521 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9522 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9523 In, DAG.getUNDEF(SVT)));
9526 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
9527 LLVMContext *Context = DAG.getContext();
9529 MVT VT = Op.getSimpleValueType();
9531 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9532 if (VT.isVector()) {
9533 EltVT = VT.getVectorElementType();
9534 NumElts = VT.getVectorNumElements();
9537 if (EltVT == MVT::f64)
9538 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9539 APInt(64, ~(1ULL << 63))));
9541 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9542 APInt(32, ~(1U << 31))));
9543 C = ConstantVector::getSplat(NumElts, C);
9544 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9545 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9546 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9547 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9548 MachinePointerInfo::getConstantPool(),
9549 false, false, false, Alignment);
9550 if (VT.isVector()) {
9551 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9552 return DAG.getNode(ISD::BITCAST, dl, VT,
9553 DAG.getNode(ISD::AND, dl, ANDVT,
9554 DAG.getNode(ISD::BITCAST, dl, ANDVT,
9556 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9558 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9561 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
9562 LLVMContext *Context = DAG.getContext();
9564 MVT VT = Op.getSimpleValueType();
9566 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9567 if (VT.isVector()) {
9568 EltVT = VT.getVectorElementType();
9569 NumElts = VT.getVectorNumElements();
9572 if (EltVT == MVT::f64)
9573 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9574 APInt(64, 1ULL << 63)));
9576 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9577 APInt(32, 1U << 31)));
9578 C = ConstantVector::getSplat(NumElts, C);
9579 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9580 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9581 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9582 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9583 MachinePointerInfo::getConstantPool(),
9584 false, false, false, Alignment);
9585 if (VT.isVector()) {
9586 MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
9587 return DAG.getNode(ISD::BITCAST, dl, VT,
9588 DAG.getNode(ISD::XOR, dl, XORVT,
9589 DAG.getNode(ISD::BITCAST, dl, XORVT,
9591 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9594 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9597 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
9598 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9599 LLVMContext *Context = DAG.getContext();
9600 SDValue Op0 = Op.getOperand(0);
9601 SDValue Op1 = Op.getOperand(1);
9603 MVT VT = Op.getSimpleValueType();
9604 MVT SrcVT = Op1.getSimpleValueType();
9606 // If second operand is smaller, extend it first.
9607 if (SrcVT.bitsLT(VT)) {
9608 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9611 // And if it is bigger, shrink it first.
9612 if (SrcVT.bitsGT(VT)) {
9613 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9617 // At this point the operands and the result should have the same
9618 // type, and that won't be f80 since that is not custom lowered.
9620 // First get the sign bit of second operand.
9621 SmallVector<Constant*,4> CV;
9622 if (SrcVT == MVT::f64) {
9623 const fltSemantics &Sem = APFloat::IEEEdouble;
9624 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9625 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9627 const fltSemantics &Sem = APFloat::IEEEsingle;
9628 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9629 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9630 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9631 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9633 Constant *C = ConstantVector::get(CV);
9634 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9635 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9636 MachinePointerInfo::getConstantPool(),
9637 false, false, false, 16);
9638 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9640 // Shift sign bit right or left if the two operands have different types.
9641 if (SrcVT.bitsGT(VT)) {
9642 // Op0 is MVT::f32, Op1 is MVT::f64.
9643 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9644 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9645 DAG.getConstant(32, MVT::i32));
9646 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9647 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9648 DAG.getIntPtrConstant(0));
9651 // Clear first operand sign bit.
9653 if (VT == MVT::f64) {
9654 const fltSemantics &Sem = APFloat::IEEEdouble;
9655 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9656 APInt(64, ~(1ULL << 63)))));
9657 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9659 const fltSemantics &Sem = APFloat::IEEEsingle;
9660 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9661 APInt(32, ~(1U << 31)))));
9662 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9663 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9664 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9666 C = ConstantVector::get(CV);
9667 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9668 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9669 MachinePointerInfo::getConstantPool(),
9670 false, false, false, 16);
9671 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9673 // Or the value with the sign bit.
9674 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9677 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9678 SDValue N0 = Op.getOperand(0);
9680 MVT VT = Op.getSimpleValueType();
9682 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9683 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9684 DAG.getConstant(1, VT));
9685 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9688 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9690 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
9691 SelectionDAG &DAG) {
9692 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9694 if (!Subtarget->hasSSE41())
9697 if (!Op->hasOneUse())
9700 SDNode *N = Op.getNode();
9703 SmallVector<SDValue, 8> Opnds;
9704 DenseMap<SDValue, unsigned> VecInMap;
9705 SmallVector<SDValue, 8> VecIns;
9706 EVT VT = MVT::Other;
9708 // Recognize a special case where a vector is casted into wide integer to
9710 Opnds.push_back(N->getOperand(0));
9711 Opnds.push_back(N->getOperand(1));
9713 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9714 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9715 // BFS traverse all OR'd operands.
9716 if (I->getOpcode() == ISD::OR) {
9717 Opnds.push_back(I->getOperand(0));
9718 Opnds.push_back(I->getOperand(1));
9719 // Re-evaluate the number of nodes to be traversed.
9720 e += 2; // 2 more nodes (LHS and RHS) are pushed.
9724 // Quit if a non-EXTRACT_VECTOR_ELT
9725 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9728 // Quit if without a constant index.
9729 SDValue Idx = I->getOperand(1);
9730 if (!isa<ConstantSDNode>(Idx))
9733 SDValue ExtractedFromVec = I->getOperand(0);
9734 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9735 if (M == VecInMap.end()) {
9736 VT = ExtractedFromVec.getValueType();
9737 // Quit if not 128/256-bit vector.
9738 if (!VT.is128BitVector() && !VT.is256BitVector())
9740 // Quit if not the same type.
9741 if (VecInMap.begin() != VecInMap.end() &&
9742 VT != VecInMap.begin()->first.getValueType())
9744 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9745 VecIns.push_back(ExtractedFromVec);
9747 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9750 assert((VT.is128BitVector() || VT.is256BitVector()) &&
9751 "Not extracted from 128-/256-bit vector.");
9753 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
9755 for (DenseMap<SDValue, unsigned>::const_iterator
9756 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
9757 // Quit if not all elements are used.
9758 if (I->second != FullMask)
9762 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9764 // Cast all vectors into TestVT for PTEST.
9765 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
9766 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
9768 // If more than one full vectors are evaluated, OR them first before PTEST.
9769 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
9770 // Each iteration will OR 2 nodes and append the result until there is only
9771 // 1 node left, i.e. the final OR'd value of all vectors.
9772 SDValue LHS = VecIns[Slot];
9773 SDValue RHS = VecIns[Slot + 1];
9774 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
9777 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
9778 VecIns.back(), VecIns.back());
9781 /// \brief return true if \c Op has a use that doesn't just read flags.
9782 static bool hasNonFlagsUse(SDValue Op) {
9783 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
9786 unsigned UOpNo = UI.getOperandNo();
9787 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9788 // Look pass truncate.
9789 UOpNo = User->use_begin().getOperandNo();
9790 User = *User->use_begin();
9793 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
9794 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
9800 /// Emit nodes that will be selected as "test Op0,Op0", or something
9802 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
9803 SelectionDAG &DAG) const {
9804 if (Op.getValueType() == MVT::i1)
9805 // KORTEST instruction should be selected
9806 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9807 DAG.getConstant(0, Op.getValueType()));
9809 // CF and OF aren't always set the way we want. Determine which
9810 // of these we need.
9811 bool NeedCF = false;
9812 bool NeedOF = false;
9815 case X86::COND_A: case X86::COND_AE:
9816 case X86::COND_B: case X86::COND_BE:
9819 case X86::COND_G: case X86::COND_GE:
9820 case X86::COND_L: case X86::COND_LE:
9821 case X86::COND_O: case X86::COND_NO:
9825 // See if we can use the EFLAGS value from the operand instead of
9826 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
9827 // we prove that the arithmetic won't overflow, we can't use OF or CF.
9828 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
9829 // Emit a CMP with 0, which is the TEST pattern.
9830 //if (Op.getValueType() == MVT::i1)
9831 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
9832 // DAG.getConstant(0, MVT::i1));
9833 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9834 DAG.getConstant(0, Op.getValueType()));
9836 unsigned Opcode = 0;
9837 unsigned NumOperands = 0;
9839 // Truncate operations may prevent the merge of the SETCC instruction
9840 // and the arithmetic instruction before it. Attempt to truncate the operands
9841 // of the arithmetic instruction and use a reduced bit-width instruction.
9842 bool NeedTruncation = false;
9843 SDValue ArithOp = Op;
9844 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
9845 SDValue Arith = Op->getOperand(0);
9846 // Both the trunc and the arithmetic op need to have one user each.
9847 if (Arith->hasOneUse())
9848 switch (Arith.getOpcode()) {
9855 NeedTruncation = true;
9861 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
9862 // which may be the result of a CAST. We use the variable 'Op', which is the
9863 // non-casted variable when we check for possible users.
9864 switch (ArithOp.getOpcode()) {
9866 // Due to an isel shortcoming, be conservative if this add is likely to be
9867 // selected as part of a load-modify-store instruction. When the root node
9868 // in a match is a store, isel doesn't know how to remap non-chain non-flag
9869 // uses of other nodes in the match, such as the ADD in this case. This
9870 // leads to the ADD being left around and reselected, with the result being
9871 // two adds in the output. Alas, even if none our users are stores, that
9872 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
9873 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
9874 // climbing the DAG back to the root, and it doesn't seem to be worth the
9876 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9877 UE = Op.getNode()->use_end(); UI != UE; ++UI)
9878 if (UI->getOpcode() != ISD::CopyToReg &&
9879 UI->getOpcode() != ISD::SETCC &&
9880 UI->getOpcode() != ISD::STORE)
9883 if (ConstantSDNode *C =
9884 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
9885 // An add of one will be selected as an INC.
9886 if (C->getAPIntValue() == 1) {
9887 Opcode = X86ISD::INC;
9892 // An add of negative one (subtract of one) will be selected as a DEC.
9893 if (C->getAPIntValue().isAllOnesValue()) {
9894 Opcode = X86ISD::DEC;
9900 // Otherwise use a regular EFLAGS-setting add.
9901 Opcode = X86ISD::ADD;
9906 // If we have a constant logical shift that's only used in a comparison
9907 // against zero turn it into an equivalent AND. This allows turning it into
9908 // a TEST instruction later.
9909 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) &&
9910 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
9911 EVT VT = Op.getValueType();
9912 unsigned BitWidth = VT.getSizeInBits();
9913 unsigned ShAmt = Op->getConstantOperandVal(1);
9914 if (ShAmt >= BitWidth) // Avoid undefined shifts.
9916 APInt Mask = ArithOp.getOpcode() == ISD::SRL
9917 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
9918 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
9919 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
9921 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
9922 DAG.getConstant(Mask, VT));
9923 DAG.ReplaceAllUsesWith(Op, New);
9929 // If the primary and result isn't used, don't bother using X86ISD::AND,
9930 // because a TEST instruction will be better.
9931 if (!hasNonFlagsUse(Op))
9937 // Due to the ISEL shortcoming noted above, be conservative if this op is
9938 // likely to be selected as part of a load-modify-store instruction.
9939 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9940 UE = Op.getNode()->use_end(); UI != UE; ++UI)
9941 if (UI->getOpcode() == ISD::STORE)
9944 // Otherwise use a regular EFLAGS-setting instruction.
9945 switch (ArithOp.getOpcode()) {
9946 default: llvm_unreachable("unexpected operator!");
9947 case ISD::SUB: Opcode = X86ISD::SUB; break;
9948 case ISD::XOR: Opcode = X86ISD::XOR; break;
9949 case ISD::AND: Opcode = X86ISD::AND; break;
9951 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9952 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
9953 if (EFLAGS.getNode())
9956 Opcode = X86ISD::OR;
9970 return SDValue(Op.getNode(), 1);
9976 // If we found that truncation is beneficial, perform the truncation and
9978 if (NeedTruncation) {
9979 EVT VT = Op.getValueType();
9980 SDValue WideVal = Op->getOperand(0);
9981 EVT WideVT = WideVal.getValueType();
9982 unsigned ConvertedOp = 0;
9983 // Use a target machine opcode to prevent further DAGCombine
9984 // optimizations that may separate the arithmetic operations
9985 // from the setcc node.
9986 switch (WideVal.getOpcode()) {
9988 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9989 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9990 case ISD::AND: ConvertedOp = X86ISD::AND; break;
9991 case ISD::OR: ConvertedOp = X86ISD::OR; break;
9992 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9996 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9997 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9998 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9999 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
10000 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
10006 // Emit a CMP with 0, which is the TEST pattern.
10007 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10008 DAG.getConstant(0, Op.getValueType()));
10010 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10011 SmallVector<SDValue, 4> Ops;
10012 for (unsigned i = 0; i != NumOperands; ++i)
10013 Ops.push_back(Op.getOperand(i));
10015 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
10016 DAG.ReplaceAllUsesWith(Op, New);
10017 return SDValue(New.getNode(), 1);
10020 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
10022 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
10023 SDLoc dl, SelectionDAG &DAG) const {
10024 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
10025 if (C->getAPIntValue() == 0)
10026 return EmitTest(Op0, X86CC, dl, DAG);
10028 if (Op0.getValueType() == MVT::i1)
10029 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
10032 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
10033 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
10034 // Do the comparison at i32 if it's smaller, besides the Atom case.
10035 // This avoids subregister aliasing issues. Keep the smaller reference
10036 // if we're optimizing for size, however, as that'll allow better folding
10037 // of memory operations.
10038 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
10039 !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
10040 AttributeSet::FunctionIndex, Attribute::MinSize) &&
10041 !Subtarget->isAtom()) {
10042 unsigned ExtendOp =
10043 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
10044 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
10045 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
10047 // Use SUB instead of CMP to enable CSE between SUB and CMP.
10048 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
10049 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
10051 return SDValue(Sub.getNode(), 1);
10053 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
10056 /// Convert a comparison if required by the subtarget.
10057 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
10058 SelectionDAG &DAG) const {
10059 // If the subtarget does not support the FUCOMI instruction, floating-point
10060 // comparisons have to be converted.
10061 if (Subtarget->hasCMov() ||
10062 Cmp.getOpcode() != X86ISD::CMP ||
10063 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
10064 !Cmp.getOperand(1).getValueType().isFloatingPoint())
10067 // The instruction selector will select an FUCOM instruction instead of
10068 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
10069 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
10070 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
10072 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
10073 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
10074 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
10075 DAG.getConstant(8, MVT::i8));
10076 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
10077 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
10080 static bool isAllOnes(SDValue V) {
10081 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10082 return C && C->isAllOnesValue();
10085 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
10086 /// if it's possible.
10087 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
10088 SDLoc dl, SelectionDAG &DAG) const {
10089 SDValue Op0 = And.getOperand(0);
10090 SDValue Op1 = And.getOperand(1);
10091 if (Op0.getOpcode() == ISD::TRUNCATE)
10092 Op0 = Op0.getOperand(0);
10093 if (Op1.getOpcode() == ISD::TRUNCATE)
10094 Op1 = Op1.getOperand(0);
10097 if (Op1.getOpcode() == ISD::SHL)
10098 std::swap(Op0, Op1);
10099 if (Op0.getOpcode() == ISD::SHL) {
10100 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
10101 if (And00C->getZExtValue() == 1) {
10102 // If we looked past a truncate, check that it's only truncating away
10104 unsigned BitWidth = Op0.getValueSizeInBits();
10105 unsigned AndBitWidth = And.getValueSizeInBits();
10106 if (BitWidth > AndBitWidth) {
10108 DAG.ComputeMaskedBits(Op0, Zeros, Ones);
10109 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
10113 RHS = Op0.getOperand(1);
10115 } else if (Op1.getOpcode() == ISD::Constant) {
10116 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
10117 uint64_t AndRHSVal = AndRHS->getZExtValue();
10118 SDValue AndLHS = Op0;
10120 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
10121 LHS = AndLHS.getOperand(0);
10122 RHS = AndLHS.getOperand(1);
10125 // Use BT if the immediate can't be encoded in a TEST instruction.
10126 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
10128 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
10132 if (LHS.getNode()) {
10133 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
10134 // instruction. Since the shift amount is in-range-or-undefined, we know
10135 // that doing a bittest on the i32 value is ok. We extend to i32 because
10136 // the encoding for the i16 version is larger than the i32 version.
10137 // Also promote i16 to i32 for performance / code size reason.
10138 if (LHS.getValueType() == MVT::i8 ||
10139 LHS.getValueType() == MVT::i16)
10140 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
10142 // If the operand types disagree, extend the shift amount to match. Since
10143 // BT ignores high bits (like shifts) we can use anyextend.
10144 if (LHS.getValueType() != RHS.getValueType())
10145 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
10147 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
10148 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
10149 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10150 DAG.getConstant(Cond, MVT::i8), BT);
10156 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
10158 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
10163 // SSE Condition code mapping:
10172 switch (SetCCOpcode) {
10173 default: llvm_unreachable("Unexpected SETCC condition");
10175 case ISD::SETEQ: SSECC = 0; break;
10177 case ISD::SETGT: Swap = true; // Fallthrough
10179 case ISD::SETOLT: SSECC = 1; break;
10181 case ISD::SETGE: Swap = true; // Fallthrough
10183 case ISD::SETOLE: SSECC = 2; break;
10184 case ISD::SETUO: SSECC = 3; break;
10186 case ISD::SETNE: SSECC = 4; break;
10187 case ISD::SETULE: Swap = true; // Fallthrough
10188 case ISD::SETUGE: SSECC = 5; break;
10189 case ISD::SETULT: Swap = true; // Fallthrough
10190 case ISD::SETUGT: SSECC = 6; break;
10191 case ISD::SETO: SSECC = 7; break;
10193 case ISD::SETONE: SSECC = 8; break;
10196 std::swap(Op0, Op1);
10201 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
10202 // ones, and then concatenate the result back.
10203 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
10204 MVT VT = Op.getSimpleValueType();
10206 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
10207 "Unsupported value type for operation");
10209 unsigned NumElems = VT.getVectorNumElements();
10211 SDValue CC = Op.getOperand(2);
10213 // Extract the LHS vectors
10214 SDValue LHS = Op.getOperand(0);
10215 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10216 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10218 // Extract the RHS vectors
10219 SDValue RHS = Op.getOperand(1);
10220 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10221 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10223 // Issue the operation on the smaller types and concatenate the result back
10224 MVT EltVT = VT.getVectorElementType();
10225 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10226 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10227 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
10228 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
10231 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
10232 const X86Subtarget *Subtarget) {
10233 SDValue Op0 = Op.getOperand(0);
10234 SDValue Op1 = Op.getOperand(1);
10235 SDValue CC = Op.getOperand(2);
10236 MVT VT = Op.getSimpleValueType();
10239 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
10240 Op.getValueType().getScalarType() == MVT::i1 &&
10241 "Cannot set masked compare for this operation");
10243 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10245 bool Unsigned = false;
10248 switch (SetCCOpcode) {
10249 default: llvm_unreachable("Unexpected SETCC condition");
10250 case ISD::SETNE: SSECC = 4; break;
10251 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
10252 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
10253 case ISD::SETLT: Swap = true; //fall-through
10254 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
10255 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
10256 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
10257 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
10258 case ISD::SETULE: Unsigned = true; //fall-through
10259 case ISD::SETLE: SSECC = 2; break;
10263 std::swap(Op0, Op1);
10265 return DAG.getNode(Opc, dl, VT, Op0, Op1);
10266 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
10267 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10268 DAG.getConstant(SSECC, MVT::i8));
10271 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
10272 /// operand \p Op1. If non-trivial (for example because it's not constant)
10273 /// return an empty value.
10274 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
10276 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
10280 MVT VT = Op1.getSimpleValueType();
10281 MVT EVT = VT.getVectorElementType();
10282 unsigned n = VT.getVectorNumElements();
10283 SmallVector<SDValue, 8> ULTOp1;
10285 for (unsigned i = 0; i < n; ++i) {
10286 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
10287 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
10290 // Avoid underflow.
10291 APInt Val = Elt->getAPIntValue();
10295 ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
10298 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1.data(), ULTOp1.size());
10301 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
10302 SelectionDAG &DAG) {
10303 SDValue Op0 = Op.getOperand(0);
10304 SDValue Op1 = Op.getOperand(1);
10305 SDValue CC = Op.getOperand(2);
10306 MVT VT = Op.getSimpleValueType();
10307 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10308 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10313 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10314 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10317 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10318 unsigned Opc = X86ISD::CMPP;
10319 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10320 assert(VT.getVectorNumElements() <= 16);
10321 Opc = X86ISD::CMPM;
10323 // In the two special cases we can't handle, emit two comparisons.
10326 unsigned CombineOpc;
10327 if (SetCCOpcode == ISD::SETUEQ) {
10328 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10330 assert(SetCCOpcode == ISD::SETONE);
10331 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10334 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10335 DAG.getConstant(CC0, MVT::i8));
10336 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10337 DAG.getConstant(CC1, MVT::i8));
10338 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10340 // Handle all other FP comparisons here.
10341 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10342 DAG.getConstant(SSECC, MVT::i8));
10345 // Break 256-bit integer vector compare into smaller ones.
10346 if (VT.is256BitVector() && !Subtarget->hasInt256())
10347 return Lower256IntVSETCC(Op, DAG);
10349 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10350 EVT OpVT = Op1.getValueType();
10351 if (Subtarget->hasAVX512()) {
10352 if (Op1.getValueType().is512BitVector() ||
10353 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10354 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
10356 // In AVX-512 architecture setcc returns mask with i1 elements,
10357 // But there is no compare instruction for i8 and i16 elements.
10358 // We are not talking about 512-bit operands in this case, these
10359 // types are illegal.
10361 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10362 OpVT.getVectorElementType().getSizeInBits() >= 8))
10363 return DAG.getNode(ISD::TRUNCATE, dl, VT,
10364 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10367 // We are handling one of the integer comparisons here. Since SSE only has
10368 // GT and EQ comparisons for integer, swapping operands and multiple
10369 // operations may be required for some comparisons.
10371 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10372 bool Subus = false;
10374 switch (SetCCOpcode) {
10375 default: llvm_unreachable("Unexpected SETCC condition");
10376 case ISD::SETNE: Invert = true;
10377 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
10378 case ISD::SETLT: Swap = true;
10379 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
10380 case ISD::SETGE: Swap = true;
10381 case ISD::SETLE: Opc = X86ISD::PCMPGT;
10382 Invert = true; break;
10383 case ISD::SETULT: Swap = true;
10384 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
10385 FlipSigns = true; break;
10386 case ISD::SETUGE: Swap = true;
10387 case ISD::SETULE: Opc = X86ISD::PCMPGT;
10388 FlipSigns = true; Invert = true; break;
10391 // Special case: Use min/max operations for SETULE/SETUGE
10392 MVT VET = VT.getVectorElementType();
10394 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10395 || (Subtarget->hasSSE2() && (VET == MVT::i8));
10398 switch (SetCCOpcode) {
10400 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10401 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10404 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10407 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
10408 if (!MinMax && hasSubus) {
10409 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
10411 // t = psubus Op0, Op1
10412 // pcmpeq t, <0..0>
10413 switch (SetCCOpcode) {
10415 case ISD::SETULT: {
10416 // If the comparison is against a constant we can turn this into a
10417 // setule. With psubus, setule does not require a swap. This is
10418 // beneficial because the constant in the register is no longer
10419 // destructed as the destination so it can be hoisted out of a loop.
10420 // Only do this pre-AVX since vpcmp* is no longer destructive.
10421 if (Subtarget->hasAVX())
10423 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
10424 if (ULEOp1.getNode()) {
10426 Subus = true; Invert = false; Swap = false;
10430 // Psubus is better than flip-sign because it requires no inversion.
10431 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
10432 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
10436 Opc = X86ISD::SUBUS;
10442 std::swap(Op0, Op1);
10444 // Check that the operation in question is available (most are plain SSE2,
10445 // but PCMPGTQ and PCMPEQQ have different requirements).
10446 if (VT == MVT::v2i64) {
10447 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10448 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10450 // First cast everything to the right type.
10451 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10452 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10454 // Since SSE has no unsigned integer comparisons, we need to flip the sign
10455 // bits of the inputs before performing those operations. The lower
10456 // compare is always unsigned.
10459 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10461 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10462 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10463 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10464 Sign, Zero, Sign, Zero);
10466 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10467 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10469 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10470 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10471 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10473 // Create masks for only the low parts/high parts of the 64 bit integers.
10474 static const int MaskHi[] = { 1, 1, 3, 3 };
10475 static const int MaskLo[] = { 0, 0, 2, 2 };
10476 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10477 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10478 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10480 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10481 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10484 Result = DAG.getNOT(dl, Result, MVT::v4i32);
10486 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10489 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10490 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10491 // pcmpeqd + pshufd + pand.
10492 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10494 // First cast everything to the right type.
10495 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10496 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10499 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
10501 // Make sure the lower and upper halves are both all-ones.
10502 static const int Mask[] = { 1, 0, 3, 2 };
10503 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
10504 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
10507 Result = DAG.getNOT(dl, Result, MVT::v4i32);
10509 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10513 // Since SSE has no unsigned integer comparisons, we need to flip the sign
10514 // bits of the inputs before performing those operations.
10516 EVT EltVT = VT.getVectorElementType();
10517 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
10518 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
10519 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
10522 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
10524 // If the logical-not of the result is required, perform that now.
10526 Result = DAG.getNOT(dl, Result, VT);
10529 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
10532 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
10533 getZeroVector(VT, Subtarget, DAG, dl));
10538 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
10540 MVT VT = Op.getSimpleValueType();
10542 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
10544 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
10545 && "SetCC type must be 8-bit or 1-bit integer");
10546 SDValue Op0 = Op.getOperand(0);
10547 SDValue Op1 = Op.getOperand(1);
10549 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10551 // Optimize to BT if possible.
10552 // Lower (X & (1 << N)) == 0 to BT(X, N).
10553 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
10554 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
10555 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
10556 Op1.getOpcode() == ISD::Constant &&
10557 cast<ConstantSDNode>(Op1)->isNullValue() &&
10558 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10559 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
10560 if (NewSetCC.getNode())
10564 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
10566 if (Op1.getOpcode() == ISD::Constant &&
10567 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
10568 cast<ConstantSDNode>(Op1)->isNullValue()) &&
10569 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10571 // If the input is a setcc, then reuse the input setcc or use a new one with
10572 // the inverted condition.
10573 if (Op0.getOpcode() == X86ISD::SETCC) {
10574 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
10575 bool Invert = (CC == ISD::SETNE) ^
10576 cast<ConstantSDNode>(Op1)->isNullValue();
10580 CCode = X86::GetOppositeBranchCondition(CCode);
10581 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10582 DAG.getConstant(CCode, MVT::i8),
10583 Op0.getOperand(1));
10585 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10589 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
10590 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
10591 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10593 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
10594 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
10597 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
10598 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
10599 if (X86CC == X86::COND_INVALID)
10602 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
10603 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
10604 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10605 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
10607 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10611 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10612 static bool isX86LogicalCmp(SDValue Op) {
10613 unsigned Opc = Op.getNode()->getOpcode();
10614 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10615 Opc == X86ISD::SAHF)
10617 if (Op.getResNo() == 1 &&
10618 (Opc == X86ISD::ADD ||
10619 Opc == X86ISD::SUB ||
10620 Opc == X86ISD::ADC ||
10621 Opc == X86ISD::SBB ||
10622 Opc == X86ISD::SMUL ||
10623 Opc == X86ISD::UMUL ||
10624 Opc == X86ISD::INC ||
10625 Opc == X86ISD::DEC ||
10626 Opc == X86ISD::OR ||
10627 Opc == X86ISD::XOR ||
10628 Opc == X86ISD::AND))
10631 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
10637 static bool isZero(SDValue V) {
10638 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10639 return C && C->isNullValue();
10642 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
10643 if (V.getOpcode() != ISD::TRUNCATE)
10646 SDValue VOp0 = V.getOperand(0);
10647 unsigned InBits = VOp0.getValueSizeInBits();
10648 unsigned Bits = V.getValueSizeInBits();
10649 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
10652 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
10653 bool addTest = true;
10654 SDValue Cond = Op.getOperand(0);
10655 SDValue Op1 = Op.getOperand(1);
10656 SDValue Op2 = Op.getOperand(2);
10658 EVT VT = Op1.getValueType();
10661 // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
10662 // are available. Otherwise fp cmovs get lowered into a less efficient branch
10663 // sequence later on.
10664 if (Cond.getOpcode() == ISD::SETCC &&
10665 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
10666 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
10667 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
10668 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
10669 int SSECC = translateX86FSETCC(
10670 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
10673 if (Subtarget->hasAVX512()) {
10674 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
10675 DAG.getConstant(SSECC, MVT::i8));
10676 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
10678 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
10679 DAG.getConstant(SSECC, MVT::i8));
10680 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
10681 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
10682 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
10686 if (Cond.getOpcode() == ISD::SETCC) {
10687 SDValue NewCond = LowerSETCC(Cond, DAG);
10688 if (NewCond.getNode())
10692 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
10693 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
10694 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
10695 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
10696 if (Cond.getOpcode() == X86ISD::SETCC &&
10697 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
10698 isZero(Cond.getOperand(1).getOperand(1))) {
10699 SDValue Cmp = Cond.getOperand(1);
10701 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
10703 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
10704 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
10705 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
10707 SDValue CmpOp0 = Cmp.getOperand(0);
10708 // Apply further optimizations for special cases
10709 // (select (x != 0), -1, 0) -> neg & sbb
10710 // (select (x == 0), 0, -1) -> neg & sbb
10711 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
10712 if (YC->isNullValue() &&
10713 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
10714 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
10715 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
10716 DAG.getConstant(0, CmpOp0.getValueType()),
10718 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10719 DAG.getConstant(X86::COND_B, MVT::i8),
10720 SDValue(Neg.getNode(), 1));
10724 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10725 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10726 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10728 SDValue Res = // Res = 0 or -1.
10729 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10730 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
10732 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
10733 Res = DAG.getNOT(DL, Res, Res.getValueType());
10735 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
10736 if (!N2C || !N2C->isNullValue())
10737 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
10742 // Look past (and (setcc_carry (cmp ...)), 1).
10743 if (Cond.getOpcode() == ISD::AND &&
10744 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10745 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10746 if (C && C->getAPIntValue() == 1)
10747 Cond = Cond.getOperand(0);
10750 // If condition flag is set by a X86ISD::CMP, then use it as the condition
10751 // setting operand in place of the X86ISD::SETCC.
10752 unsigned CondOpcode = Cond.getOpcode();
10753 if (CondOpcode == X86ISD::SETCC ||
10754 CondOpcode == X86ISD::SETCC_CARRY) {
10755 CC = Cond.getOperand(0);
10757 SDValue Cmp = Cond.getOperand(1);
10758 unsigned Opc = Cmp.getOpcode();
10759 MVT VT = Op.getSimpleValueType();
10761 bool IllegalFPCMov = false;
10762 if (VT.isFloatingPoint() && !VT.isVector() &&
10763 !isScalarFPTypeInSSEReg(VT)) // FPStack?
10764 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
10766 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
10767 Opc == X86ISD::BT) { // FIXME
10771 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10772 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10773 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10774 Cond.getOperand(0).getValueType() != MVT::i8)) {
10775 SDValue LHS = Cond.getOperand(0);
10776 SDValue RHS = Cond.getOperand(1);
10777 unsigned X86Opcode;
10780 switch (CondOpcode) {
10781 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10782 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10783 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10784 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10785 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10786 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10787 default: llvm_unreachable("unexpected overflowing operator");
10789 if (CondOpcode == ISD::UMULO)
10790 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10793 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10795 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
10797 if (CondOpcode == ISD::UMULO)
10798 Cond = X86Op.getValue(2);
10800 Cond = X86Op.getValue(1);
10802 CC = DAG.getConstant(X86Cond, MVT::i8);
10807 // Look pass the truncate if the high bits are known zero.
10808 if (isTruncWithZeroHighBitsInput(Cond, DAG))
10809 Cond = Cond.getOperand(0);
10811 // We know the result of AND is compared against zero. Try to match
10813 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10814 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
10815 if (NewSetCC.getNode()) {
10816 CC = NewSetCC.getOperand(0);
10817 Cond = NewSetCC.getOperand(1);
10824 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10825 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
10828 // a < b ? -1 : 0 -> RES = ~setcc_carry
10829 // a < b ? 0 : -1 -> RES = setcc_carry
10830 // a >= b ? -1 : 0 -> RES = setcc_carry
10831 // a >= b ? 0 : -1 -> RES = ~setcc_carry
10832 if (Cond.getOpcode() == X86ISD::SUB) {
10833 Cond = ConvertCmpIfNecessary(Cond, DAG);
10834 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
10836 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
10837 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
10838 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10839 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
10840 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
10841 return DAG.getNOT(DL, Res, Res.getValueType());
10846 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
10847 // widen the cmov and push the truncate through. This avoids introducing a new
10848 // branch during isel and doesn't add any extensions.
10849 if (Op.getValueType() == MVT::i8 &&
10850 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
10851 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
10852 if (T1.getValueType() == T2.getValueType() &&
10853 // Blacklist CopyFromReg to avoid partial register stalls.
10854 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
10855 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
10856 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
10857 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
10861 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
10862 // condition is true.
10863 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
10864 SDValue Ops[] = { Op2, Op1, CC, Cond };
10865 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
10868 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
10869 MVT VT = Op->getSimpleValueType(0);
10870 SDValue In = Op->getOperand(0);
10871 MVT InVT = In.getSimpleValueType();
10874 unsigned int NumElts = VT.getVectorNumElements();
10875 if (NumElts != 8 && NumElts != 16)
10878 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
10879 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10881 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10882 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
10884 MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
10885 Constant *C = ConstantInt::get(*DAG.getContext(),
10886 APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
10888 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
10889 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
10890 SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
10891 MachinePointerInfo::getConstantPool(),
10892 false, false, false, Alignment);
10893 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
10894 if (VT.is512BitVector())
10896 return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
10899 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
10900 SelectionDAG &DAG) {
10901 MVT VT = Op->getSimpleValueType(0);
10902 SDValue In = Op->getOperand(0);
10903 MVT InVT = In.getSimpleValueType();
10906 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
10907 return LowerSIGN_EXTEND_AVX512(Op, DAG);
10909 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
10910 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
10911 (VT != MVT::v16i16 || InVT != MVT::v16i8))
10914 if (Subtarget->hasInt256())
10915 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10917 // Optimize vectors in AVX mode
10918 // Sign extend v8i16 to v8i32 and
10921 // Divide input vector into two parts
10922 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
10923 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
10924 // concat the vectors to original VT
10926 unsigned NumElems = InVT.getVectorNumElements();
10927 SDValue Undef = DAG.getUNDEF(InVT);
10929 SmallVector<int,8> ShufMask1(NumElems, -1);
10930 for (unsigned i = 0; i != NumElems/2; ++i)
10933 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
10935 SmallVector<int,8> ShufMask2(NumElems, -1);
10936 for (unsigned i = 0; i != NumElems/2; ++i)
10937 ShufMask2[i] = i + NumElems/2;
10939 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
10941 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
10942 VT.getVectorNumElements()/2);
10944 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
10945 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
10947 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
10950 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
10951 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
10952 // from the AND / OR.
10953 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
10954 Opc = Op.getOpcode();
10955 if (Opc != ISD::OR && Opc != ISD::AND)
10957 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10958 Op.getOperand(0).hasOneUse() &&
10959 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
10960 Op.getOperand(1).hasOneUse());
10963 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
10964 // 1 and that the SETCC node has a single use.
10965 static bool isXor1OfSetCC(SDValue Op) {
10966 if (Op.getOpcode() != ISD::XOR)
10968 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10969 if (N1C && N1C->getAPIntValue() == 1) {
10970 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10971 Op.getOperand(0).hasOneUse();
10976 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
10977 bool addTest = true;
10978 SDValue Chain = Op.getOperand(0);
10979 SDValue Cond = Op.getOperand(1);
10980 SDValue Dest = Op.getOperand(2);
10983 bool Inverted = false;
10985 if (Cond.getOpcode() == ISD::SETCC) {
10986 // Check for setcc([su]{add,sub,mul}o == 0).
10987 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
10988 isa<ConstantSDNode>(Cond.getOperand(1)) &&
10989 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
10990 Cond.getOperand(0).getResNo() == 1 &&
10991 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
10992 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
10993 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
10994 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
10995 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
10996 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
10998 Cond = Cond.getOperand(0);
11000 SDValue NewCond = LowerSETCC(Cond, DAG);
11001 if (NewCond.getNode())
11006 // FIXME: LowerXALUO doesn't handle these!!
11007 else if (Cond.getOpcode() == X86ISD::ADD ||
11008 Cond.getOpcode() == X86ISD::SUB ||
11009 Cond.getOpcode() == X86ISD::SMUL ||
11010 Cond.getOpcode() == X86ISD::UMUL)
11011 Cond = LowerXALUO(Cond, DAG);
11014 // Look pass (and (setcc_carry (cmp ...)), 1).
11015 if (Cond.getOpcode() == ISD::AND &&
11016 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
11017 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11018 if (C && C->getAPIntValue() == 1)
11019 Cond = Cond.getOperand(0);
11022 // If condition flag is set by a X86ISD::CMP, then use it as the condition
11023 // setting operand in place of the X86ISD::SETCC.
11024 unsigned CondOpcode = Cond.getOpcode();
11025 if (CondOpcode == X86ISD::SETCC ||
11026 CondOpcode == X86ISD::SETCC_CARRY) {
11027 CC = Cond.getOperand(0);
11029 SDValue Cmp = Cond.getOperand(1);
11030 unsigned Opc = Cmp.getOpcode();
11031 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
11032 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
11036 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
11040 // These can only come from an arithmetic instruction with overflow,
11041 // e.g. SADDO, UADDO.
11042 Cond = Cond.getNode()->getOperand(1);
11048 CondOpcode = Cond.getOpcode();
11049 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11050 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11051 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11052 Cond.getOperand(0).getValueType() != MVT::i8)) {
11053 SDValue LHS = Cond.getOperand(0);
11054 SDValue RHS = Cond.getOperand(1);
11055 unsigned X86Opcode;
11058 // Keep this in sync with LowerXALUO, otherwise we might create redundant
11059 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
11061 switch (CondOpcode) {
11062 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11064 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11066 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
11069 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11070 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11072 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11074 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
11077 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11078 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11079 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11080 default: llvm_unreachable("unexpected overflowing operator");
11083 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
11084 if (CondOpcode == ISD::UMULO)
11085 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11088 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11090 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
11092 if (CondOpcode == ISD::UMULO)
11093 Cond = X86Op.getValue(2);
11095 Cond = X86Op.getValue(1);
11097 CC = DAG.getConstant(X86Cond, MVT::i8);
11101 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
11102 SDValue Cmp = Cond.getOperand(0).getOperand(1);
11103 if (CondOpc == ISD::OR) {
11104 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
11105 // two branches instead of an explicit OR instruction with a
11107 if (Cmp == Cond.getOperand(1).getOperand(1) &&
11108 isX86LogicalCmp(Cmp)) {
11109 CC = Cond.getOperand(0).getOperand(0);
11110 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11111 Chain, Dest, CC, Cmp);
11112 CC = Cond.getOperand(1).getOperand(0);
11116 } else { // ISD::AND
11117 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
11118 // two branches instead of an explicit AND instruction with a
11119 // separate test. However, we only do this if this block doesn't
11120 // have a fall-through edge, because this requires an explicit
11121 // jmp when the condition is false.
11122 if (Cmp == Cond.getOperand(1).getOperand(1) &&
11123 isX86LogicalCmp(Cmp) &&
11124 Op.getNode()->hasOneUse()) {
11125 X86::CondCode CCode =
11126 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11127 CCode = X86::GetOppositeBranchCondition(CCode);
11128 CC = DAG.getConstant(CCode, MVT::i8);
11129 SDNode *User = *Op.getNode()->use_begin();
11130 // Look for an unconditional branch following this conditional branch.
11131 // We need this because we need to reverse the successors in order
11132 // to implement FCMP_OEQ.
11133 if (User->getOpcode() == ISD::BR) {
11134 SDValue FalseBB = User->getOperand(1);
11136 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11137 assert(NewBR == User);
11141 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11142 Chain, Dest, CC, Cmp);
11143 X86::CondCode CCode =
11144 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
11145 CCode = X86::GetOppositeBranchCondition(CCode);
11146 CC = DAG.getConstant(CCode, MVT::i8);
11152 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
11153 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
11154 // It should be transformed during dag combiner except when the condition
11155 // is set by a arithmetics with overflow node.
11156 X86::CondCode CCode =
11157 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11158 CCode = X86::GetOppositeBranchCondition(CCode);
11159 CC = DAG.getConstant(CCode, MVT::i8);
11160 Cond = Cond.getOperand(0).getOperand(1);
11162 } else if (Cond.getOpcode() == ISD::SETCC &&
11163 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
11164 // For FCMP_OEQ, we can emit
11165 // two branches instead of an explicit AND instruction with a
11166 // separate test. However, we only do this if this block doesn't
11167 // have a fall-through edge, because this requires an explicit
11168 // jmp when the condition is false.
11169 if (Op.getNode()->hasOneUse()) {
11170 SDNode *User = *Op.getNode()->use_begin();
11171 // Look for an unconditional branch following this conditional branch.
11172 // We need this because we need to reverse the successors in order
11173 // to implement FCMP_OEQ.
11174 if (User->getOpcode() == ISD::BR) {
11175 SDValue FalseBB = User->getOperand(1);
11177 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11178 assert(NewBR == User);
11182 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11183 Cond.getOperand(0), Cond.getOperand(1));
11184 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11185 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11186 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11187 Chain, Dest, CC, Cmp);
11188 CC = DAG.getConstant(X86::COND_P, MVT::i8);
11193 } else if (Cond.getOpcode() == ISD::SETCC &&
11194 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
11195 // For FCMP_UNE, we can emit
11196 // two branches instead of an explicit AND instruction with a
11197 // separate test. However, we only do this if this block doesn't
11198 // have a fall-through edge, because this requires an explicit
11199 // jmp when the condition is false.
11200 if (Op.getNode()->hasOneUse()) {
11201 SDNode *User = *Op.getNode()->use_begin();
11202 // Look for an unconditional branch following this conditional branch.
11203 // We need this because we need to reverse the successors in order
11204 // to implement FCMP_UNE.
11205 if (User->getOpcode() == ISD::BR) {
11206 SDValue FalseBB = User->getOperand(1);
11208 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11209 assert(NewBR == User);
11212 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11213 Cond.getOperand(0), Cond.getOperand(1));
11214 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11215 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11216 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11217 Chain, Dest, CC, Cmp);
11218 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
11228 // Look pass the truncate if the high bits are known zero.
11229 if (isTruncWithZeroHighBitsInput(Cond, DAG))
11230 Cond = Cond.getOperand(0);
11232 // We know the result of AND is compared against zero. Try to match
11234 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11235 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
11236 if (NewSetCC.getNode()) {
11237 CC = NewSetCC.getOperand(0);
11238 Cond = NewSetCC.getOperand(1);
11245 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11246 Cond = EmitTest(Cond, X86::COND_NE, dl, DAG);
11248 Cond = ConvertCmpIfNecessary(Cond, DAG);
11249 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11250 Chain, Dest, CC, Cond);
11253 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
11254 // Calls to _alloca is needed to probe the stack when allocating more than 4k
11255 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
11256 // that the guard pages used by the OS virtual memory manager are allocated in
11257 // correct sequence.
11259 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
11260 SelectionDAG &DAG) const {
11261 MachineFunction &MF = DAG.getMachineFunction();
11262 bool SplitStack = MF.shouldSplitStack();
11263 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
11268 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11269 SDNode* Node = Op.getNode();
11271 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
11272 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
11273 " not tell us which reg is the stack pointer!");
11274 EVT VT = Node->getValueType(0);
11275 SDValue Tmp1 = SDValue(Node, 0);
11276 SDValue Tmp2 = SDValue(Node, 1);
11277 SDValue Tmp3 = Node->getOperand(2);
11278 SDValue Chain = Tmp1.getOperand(0);
11280 // Chain the dynamic stack allocation so that it doesn't modify the stack
11281 // pointer when other instructions are using the stack.
11282 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
11285 SDValue Size = Tmp2.getOperand(1);
11286 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
11287 Chain = SP.getValue(1);
11288 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
11289 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
11290 unsigned StackAlign = TFI.getStackAlignment();
11291 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
11292 if (Align > StackAlign)
11293 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
11294 DAG.getConstant(-(uint64_t)Align, VT));
11295 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
11297 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
11298 DAG.getIntPtrConstant(0, true), SDValue(),
11301 SDValue Ops[2] = { Tmp1, Tmp2 };
11302 return DAG.getMergeValues(Ops, 2, dl);
11306 SDValue Chain = Op.getOperand(0);
11307 SDValue Size = Op.getOperand(1);
11308 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11309 EVT VT = Op.getNode()->getValueType(0);
11311 bool Is64Bit = Subtarget->is64Bit();
11312 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
11315 MachineRegisterInfo &MRI = MF.getRegInfo();
11318 // The 64 bit implementation of segmented stacks needs to clobber both r10
11319 // r11. This makes it impossible to use it along with nested parameters.
11320 const Function *F = MF.getFunction();
11322 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
11324 if (I->hasNestAttr())
11325 report_fatal_error("Cannot use segmented stacks with functions that "
11326 "have nested arguments.");
11329 const TargetRegisterClass *AddrRegClass =
11330 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
11331 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
11332 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
11333 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
11334 DAG.getRegister(Vreg, SPTy));
11335 SDValue Ops1[2] = { Value, Chain };
11336 return DAG.getMergeValues(Ops1, 2, dl);
11339 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
11341 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
11342 Flag = Chain.getValue(1);
11343 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11345 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
11347 const X86RegisterInfo *RegInfo =
11348 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11349 unsigned SPReg = RegInfo->getStackRegister();
11350 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
11351 Chain = SP.getValue(1);
11354 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11355 DAG.getConstant(-(uint64_t)Align, VT));
11356 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
11359 SDValue Ops1[2] = { SP, Chain };
11360 return DAG.getMergeValues(Ops1, 2, dl);
11364 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
11365 MachineFunction &MF = DAG.getMachineFunction();
11366 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
11368 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11371 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
11372 // vastart just stores the address of the VarArgsFrameIndex slot into the
11373 // memory location argument.
11374 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11376 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
11377 MachinePointerInfo(SV), false, false, 0);
11381 // gp_offset (0 - 6 * 8)
11382 // fp_offset (48 - 48 + 8 * 16)
11383 // overflow_arg_area (point to parameters coming in memory).
11385 SmallVector<SDValue, 8> MemOps;
11386 SDValue FIN = Op.getOperand(1);
11388 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
11389 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
11391 FIN, MachinePointerInfo(SV), false, false, 0);
11392 MemOps.push_back(Store);
11395 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11396 FIN, DAG.getIntPtrConstant(4));
11397 Store = DAG.getStore(Op.getOperand(0), DL,
11398 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
11400 FIN, MachinePointerInfo(SV, 4), false, false, 0);
11401 MemOps.push_back(Store);
11403 // Store ptr to overflow_arg_area
11404 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11405 FIN, DAG.getIntPtrConstant(4));
11406 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11408 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11409 MachinePointerInfo(SV, 8),
11411 MemOps.push_back(Store);
11413 // Store ptr to reg_save_area.
11414 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11415 FIN, DAG.getIntPtrConstant(8));
11416 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11418 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11419 MachinePointerInfo(SV, 16), false, false, 0);
11420 MemOps.push_back(Store);
11421 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11422 &MemOps[0], MemOps.size());
11425 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11426 assert(Subtarget->is64Bit() &&
11427 "LowerVAARG only handles 64-bit va_arg!");
11428 assert((Subtarget->isTargetLinux() ||
11429 Subtarget->isTargetDarwin()) &&
11430 "Unhandled target in LowerVAARG");
11431 assert(Op.getNode()->getNumOperands() == 4);
11432 SDValue Chain = Op.getOperand(0);
11433 SDValue SrcPtr = Op.getOperand(1);
11434 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11435 unsigned Align = Op.getConstantOperandVal(3);
11438 EVT ArgVT = Op.getNode()->getValueType(0);
11439 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11440 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11443 // Decide which area this value should be read from.
11444 // TODO: Implement the AMD64 ABI in its entirety. This simple
11445 // selection mechanism works only for the basic types.
11446 if (ArgVT == MVT::f80) {
11447 llvm_unreachable("va_arg for f80 not yet implemented");
11448 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11449 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
11450 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11451 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
11453 llvm_unreachable("Unhandled argument type in LowerVAARG");
11456 if (ArgMode == 2) {
11457 // Sanity Check: Make sure using fp_offset makes sense.
11458 assert(!getTargetMachine().Options.UseSoftFloat &&
11459 !(DAG.getMachineFunction()
11460 .getFunction()->getAttributes()
11461 .hasAttribute(AttributeSet::FunctionIndex,
11462 Attribute::NoImplicitFloat)) &&
11463 Subtarget->hasSSE1());
11466 // Insert VAARG_64 node into the DAG
11467 // VAARG_64 returns two values: Variable Argument Address, Chain
11468 SmallVector<SDValue, 11> InstOps;
11469 InstOps.push_back(Chain);
11470 InstOps.push_back(SrcPtr);
11471 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11472 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11473 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11474 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11475 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11476 VTs, &InstOps[0], InstOps.size(),
11478 MachinePointerInfo(SV),
11480 /*Volatile=*/false,
11482 /*WriteMem=*/true);
11483 Chain = VAARG.getValue(1);
11485 // Load the next argument and return it
11486 return DAG.getLoad(ArgVT, dl,
11489 MachinePointerInfo(),
11490 false, false, false, 0);
11493 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11494 SelectionDAG &DAG) {
11495 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
11496 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
11497 SDValue Chain = Op.getOperand(0);
11498 SDValue DstPtr = Op.getOperand(1);
11499 SDValue SrcPtr = Op.getOperand(2);
11500 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
11501 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11504 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
11505 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
11507 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
11510 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
11511 // amount is a constant. Takes immediate version of shift as input.
11512 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
11513 SDValue SrcOp, uint64_t ShiftAmt,
11514 SelectionDAG &DAG) {
11515 MVT ElementType = VT.getVectorElementType();
11517 // Check for ShiftAmt >= element width
11518 if (ShiftAmt >= ElementType.getSizeInBits()) {
11519 if (Opc == X86ISD::VSRAI)
11520 ShiftAmt = ElementType.getSizeInBits() - 1;
11522 return DAG.getConstant(0, VT);
11525 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
11526 && "Unknown target vector shift-by-constant node");
11528 // Fold this packed vector shift into a build vector if SrcOp is a
11529 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
11530 if (VT == SrcOp.getSimpleValueType() &&
11531 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
11532 SmallVector<SDValue, 8> Elts;
11533 unsigned NumElts = SrcOp->getNumOperands();
11534 ConstantSDNode *ND;
11537 default: llvm_unreachable(0);
11538 case X86ISD::VSHLI:
11539 for (unsigned i=0; i!=NumElts; ++i) {
11540 SDValue CurrentOp = SrcOp->getOperand(i);
11541 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11542 Elts.push_back(CurrentOp);
11545 ND = cast<ConstantSDNode>(CurrentOp);
11546 const APInt &C = ND->getAPIntValue();
11547 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
11550 case X86ISD::VSRLI:
11551 for (unsigned i=0; i!=NumElts; ++i) {
11552 SDValue CurrentOp = SrcOp->getOperand(i);
11553 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11554 Elts.push_back(CurrentOp);
11557 ND = cast<ConstantSDNode>(CurrentOp);
11558 const APInt &C = ND->getAPIntValue();
11559 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
11562 case X86ISD::VSRAI:
11563 for (unsigned i=0; i!=NumElts; ++i) {
11564 SDValue CurrentOp = SrcOp->getOperand(i);
11565 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11566 Elts.push_back(CurrentOp);
11569 ND = cast<ConstantSDNode>(CurrentOp);
11570 const APInt &C = ND->getAPIntValue();
11571 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
11576 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Elts[0], NumElts);
11579 return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
11582 // getTargetVShiftNode - Handle vector element shifts where the shift amount
11583 // may or may not be a constant. Takes immediate version of shift as input.
11584 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
11585 SDValue SrcOp, SDValue ShAmt,
11586 SelectionDAG &DAG) {
11587 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
11589 // Catch shift-by-constant.
11590 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
11591 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
11592 CShAmt->getZExtValue(), DAG);
11594 // Change opcode to non-immediate version
11596 default: llvm_unreachable("Unknown target vector shift node");
11597 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
11598 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
11599 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
11602 // Need to build a vector containing shift amount
11603 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
11606 ShOps[1] = DAG.getConstant(0, MVT::i32);
11607 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
11608 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
11610 // The return type has to be a 128-bit type with the same element
11611 // type as the input type.
11612 MVT EltVT = VT.getVectorElementType();
11613 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
11615 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
11616 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
11619 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
11621 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11623 default: return SDValue(); // Don't custom lower most intrinsics.
11624 // Comparison intrinsics.
11625 case Intrinsic::x86_sse_comieq_ss:
11626 case Intrinsic::x86_sse_comilt_ss:
11627 case Intrinsic::x86_sse_comile_ss:
11628 case Intrinsic::x86_sse_comigt_ss:
11629 case Intrinsic::x86_sse_comige_ss:
11630 case Intrinsic::x86_sse_comineq_ss:
11631 case Intrinsic::x86_sse_ucomieq_ss:
11632 case Intrinsic::x86_sse_ucomilt_ss:
11633 case Intrinsic::x86_sse_ucomile_ss:
11634 case Intrinsic::x86_sse_ucomigt_ss:
11635 case Intrinsic::x86_sse_ucomige_ss:
11636 case Intrinsic::x86_sse_ucomineq_ss:
11637 case Intrinsic::x86_sse2_comieq_sd:
11638 case Intrinsic::x86_sse2_comilt_sd:
11639 case Intrinsic::x86_sse2_comile_sd:
11640 case Intrinsic::x86_sse2_comigt_sd:
11641 case Intrinsic::x86_sse2_comige_sd:
11642 case Intrinsic::x86_sse2_comineq_sd:
11643 case Intrinsic::x86_sse2_ucomieq_sd:
11644 case Intrinsic::x86_sse2_ucomilt_sd:
11645 case Intrinsic::x86_sse2_ucomile_sd:
11646 case Intrinsic::x86_sse2_ucomigt_sd:
11647 case Intrinsic::x86_sse2_ucomige_sd:
11648 case Intrinsic::x86_sse2_ucomineq_sd: {
11652 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11653 case Intrinsic::x86_sse_comieq_ss:
11654 case Intrinsic::x86_sse2_comieq_sd:
11655 Opc = X86ISD::COMI;
11658 case Intrinsic::x86_sse_comilt_ss:
11659 case Intrinsic::x86_sse2_comilt_sd:
11660 Opc = X86ISD::COMI;
11663 case Intrinsic::x86_sse_comile_ss:
11664 case Intrinsic::x86_sse2_comile_sd:
11665 Opc = X86ISD::COMI;
11668 case Intrinsic::x86_sse_comigt_ss:
11669 case Intrinsic::x86_sse2_comigt_sd:
11670 Opc = X86ISD::COMI;
11673 case Intrinsic::x86_sse_comige_ss:
11674 case Intrinsic::x86_sse2_comige_sd:
11675 Opc = X86ISD::COMI;
11678 case Intrinsic::x86_sse_comineq_ss:
11679 case Intrinsic::x86_sse2_comineq_sd:
11680 Opc = X86ISD::COMI;
11683 case Intrinsic::x86_sse_ucomieq_ss:
11684 case Intrinsic::x86_sse2_ucomieq_sd:
11685 Opc = X86ISD::UCOMI;
11688 case Intrinsic::x86_sse_ucomilt_ss:
11689 case Intrinsic::x86_sse2_ucomilt_sd:
11690 Opc = X86ISD::UCOMI;
11693 case Intrinsic::x86_sse_ucomile_ss:
11694 case Intrinsic::x86_sse2_ucomile_sd:
11695 Opc = X86ISD::UCOMI;
11698 case Intrinsic::x86_sse_ucomigt_ss:
11699 case Intrinsic::x86_sse2_ucomigt_sd:
11700 Opc = X86ISD::UCOMI;
11703 case Intrinsic::x86_sse_ucomige_ss:
11704 case Intrinsic::x86_sse2_ucomige_sd:
11705 Opc = X86ISD::UCOMI;
11708 case Intrinsic::x86_sse_ucomineq_ss:
11709 case Intrinsic::x86_sse2_ucomineq_sd:
11710 Opc = X86ISD::UCOMI;
11715 SDValue LHS = Op.getOperand(1);
11716 SDValue RHS = Op.getOperand(2);
11717 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
11718 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
11719 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
11720 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11721 DAG.getConstant(X86CC, MVT::i8), Cond);
11722 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11725 // Arithmetic intrinsics.
11726 case Intrinsic::x86_sse2_pmulu_dq:
11727 case Intrinsic::x86_avx2_pmulu_dq:
11728 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
11729 Op.getOperand(1), Op.getOperand(2));
11731 // SSE2/AVX2 sub with unsigned saturation intrinsics
11732 case Intrinsic::x86_sse2_psubus_b:
11733 case Intrinsic::x86_sse2_psubus_w:
11734 case Intrinsic::x86_avx2_psubus_b:
11735 case Intrinsic::x86_avx2_psubus_w:
11736 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
11737 Op.getOperand(1), Op.getOperand(2));
11739 // SSE3/AVX horizontal add/sub intrinsics
11740 case Intrinsic::x86_sse3_hadd_ps:
11741 case Intrinsic::x86_sse3_hadd_pd:
11742 case Intrinsic::x86_avx_hadd_ps_256:
11743 case Intrinsic::x86_avx_hadd_pd_256:
11744 case Intrinsic::x86_sse3_hsub_ps:
11745 case Intrinsic::x86_sse3_hsub_pd:
11746 case Intrinsic::x86_avx_hsub_ps_256:
11747 case Intrinsic::x86_avx_hsub_pd_256:
11748 case Intrinsic::x86_ssse3_phadd_w_128:
11749 case Intrinsic::x86_ssse3_phadd_d_128:
11750 case Intrinsic::x86_avx2_phadd_w:
11751 case Intrinsic::x86_avx2_phadd_d:
11752 case Intrinsic::x86_ssse3_phsub_w_128:
11753 case Intrinsic::x86_ssse3_phsub_d_128:
11754 case Intrinsic::x86_avx2_phsub_w:
11755 case Intrinsic::x86_avx2_phsub_d: {
11758 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11759 case Intrinsic::x86_sse3_hadd_ps:
11760 case Intrinsic::x86_sse3_hadd_pd:
11761 case Intrinsic::x86_avx_hadd_ps_256:
11762 case Intrinsic::x86_avx_hadd_pd_256:
11763 Opcode = X86ISD::FHADD;
11765 case Intrinsic::x86_sse3_hsub_ps:
11766 case Intrinsic::x86_sse3_hsub_pd:
11767 case Intrinsic::x86_avx_hsub_ps_256:
11768 case Intrinsic::x86_avx_hsub_pd_256:
11769 Opcode = X86ISD::FHSUB;
11771 case Intrinsic::x86_ssse3_phadd_w_128:
11772 case Intrinsic::x86_ssse3_phadd_d_128:
11773 case Intrinsic::x86_avx2_phadd_w:
11774 case Intrinsic::x86_avx2_phadd_d:
11775 Opcode = X86ISD::HADD;
11777 case Intrinsic::x86_ssse3_phsub_w_128:
11778 case Intrinsic::x86_ssse3_phsub_d_128:
11779 case Intrinsic::x86_avx2_phsub_w:
11780 case Intrinsic::x86_avx2_phsub_d:
11781 Opcode = X86ISD::HSUB;
11784 return DAG.getNode(Opcode, dl, Op.getValueType(),
11785 Op.getOperand(1), Op.getOperand(2));
11788 // SSE2/SSE41/AVX2 integer max/min intrinsics.
11789 case Intrinsic::x86_sse2_pmaxu_b:
11790 case Intrinsic::x86_sse41_pmaxuw:
11791 case Intrinsic::x86_sse41_pmaxud:
11792 case Intrinsic::x86_avx2_pmaxu_b:
11793 case Intrinsic::x86_avx2_pmaxu_w:
11794 case Intrinsic::x86_avx2_pmaxu_d:
11795 case Intrinsic::x86_sse2_pminu_b:
11796 case Intrinsic::x86_sse41_pminuw:
11797 case Intrinsic::x86_sse41_pminud:
11798 case Intrinsic::x86_avx2_pminu_b:
11799 case Intrinsic::x86_avx2_pminu_w:
11800 case Intrinsic::x86_avx2_pminu_d:
11801 case Intrinsic::x86_sse41_pmaxsb:
11802 case Intrinsic::x86_sse2_pmaxs_w:
11803 case Intrinsic::x86_sse41_pmaxsd:
11804 case Intrinsic::x86_avx2_pmaxs_b:
11805 case Intrinsic::x86_avx2_pmaxs_w:
11806 case Intrinsic::x86_avx2_pmaxs_d:
11807 case Intrinsic::x86_sse41_pminsb:
11808 case Intrinsic::x86_sse2_pmins_w:
11809 case Intrinsic::x86_sse41_pminsd:
11810 case Intrinsic::x86_avx2_pmins_b:
11811 case Intrinsic::x86_avx2_pmins_w:
11812 case Intrinsic::x86_avx2_pmins_d: {
11815 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11816 case Intrinsic::x86_sse2_pmaxu_b:
11817 case Intrinsic::x86_sse41_pmaxuw:
11818 case Intrinsic::x86_sse41_pmaxud:
11819 case Intrinsic::x86_avx2_pmaxu_b:
11820 case Intrinsic::x86_avx2_pmaxu_w:
11821 case Intrinsic::x86_avx2_pmaxu_d:
11822 Opcode = X86ISD::UMAX;
11824 case Intrinsic::x86_sse2_pminu_b:
11825 case Intrinsic::x86_sse41_pminuw:
11826 case Intrinsic::x86_sse41_pminud:
11827 case Intrinsic::x86_avx2_pminu_b:
11828 case Intrinsic::x86_avx2_pminu_w:
11829 case Intrinsic::x86_avx2_pminu_d:
11830 Opcode = X86ISD::UMIN;
11832 case Intrinsic::x86_sse41_pmaxsb:
11833 case Intrinsic::x86_sse2_pmaxs_w:
11834 case Intrinsic::x86_sse41_pmaxsd:
11835 case Intrinsic::x86_avx2_pmaxs_b:
11836 case Intrinsic::x86_avx2_pmaxs_w:
11837 case Intrinsic::x86_avx2_pmaxs_d:
11838 Opcode = X86ISD::SMAX;
11840 case Intrinsic::x86_sse41_pminsb:
11841 case Intrinsic::x86_sse2_pmins_w:
11842 case Intrinsic::x86_sse41_pminsd:
11843 case Intrinsic::x86_avx2_pmins_b:
11844 case Intrinsic::x86_avx2_pmins_w:
11845 case Intrinsic::x86_avx2_pmins_d:
11846 Opcode = X86ISD::SMIN;
11849 return DAG.getNode(Opcode, dl, Op.getValueType(),
11850 Op.getOperand(1), Op.getOperand(2));
11853 // SSE/SSE2/AVX floating point max/min intrinsics.
11854 case Intrinsic::x86_sse_max_ps:
11855 case Intrinsic::x86_sse2_max_pd:
11856 case Intrinsic::x86_avx_max_ps_256:
11857 case Intrinsic::x86_avx_max_pd_256:
11858 case Intrinsic::x86_sse_min_ps:
11859 case Intrinsic::x86_sse2_min_pd:
11860 case Intrinsic::x86_avx_min_ps_256:
11861 case Intrinsic::x86_avx_min_pd_256: {
11864 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
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 Opcode = X86ISD::FMAX;
11871 case Intrinsic::x86_sse_min_ps:
11872 case Intrinsic::x86_sse2_min_pd:
11873 case Intrinsic::x86_avx_min_ps_256:
11874 case Intrinsic::x86_avx_min_pd_256:
11875 Opcode = X86ISD::FMIN;
11878 return DAG.getNode(Opcode, dl, Op.getValueType(),
11879 Op.getOperand(1), Op.getOperand(2));
11882 // AVX2 variable shift intrinsics
11883 case Intrinsic::x86_avx2_psllv_d:
11884 case Intrinsic::x86_avx2_psllv_q:
11885 case Intrinsic::x86_avx2_psllv_d_256:
11886 case Intrinsic::x86_avx2_psllv_q_256:
11887 case Intrinsic::x86_avx2_psrlv_d:
11888 case Intrinsic::x86_avx2_psrlv_q:
11889 case Intrinsic::x86_avx2_psrlv_d_256:
11890 case Intrinsic::x86_avx2_psrlv_q_256:
11891 case Intrinsic::x86_avx2_psrav_d:
11892 case Intrinsic::x86_avx2_psrav_d_256: {
11895 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11896 case Intrinsic::x86_avx2_psllv_d:
11897 case Intrinsic::x86_avx2_psllv_q:
11898 case Intrinsic::x86_avx2_psllv_d_256:
11899 case Intrinsic::x86_avx2_psllv_q_256:
11902 case Intrinsic::x86_avx2_psrlv_d:
11903 case Intrinsic::x86_avx2_psrlv_q:
11904 case Intrinsic::x86_avx2_psrlv_d_256:
11905 case Intrinsic::x86_avx2_psrlv_q_256:
11908 case Intrinsic::x86_avx2_psrav_d:
11909 case Intrinsic::x86_avx2_psrav_d_256:
11913 return DAG.getNode(Opcode, dl, Op.getValueType(),
11914 Op.getOperand(1), Op.getOperand(2));
11917 case Intrinsic::x86_ssse3_pshuf_b_128:
11918 case Intrinsic::x86_avx2_pshuf_b:
11919 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
11920 Op.getOperand(1), Op.getOperand(2));
11922 case Intrinsic::x86_ssse3_psign_b_128:
11923 case Intrinsic::x86_ssse3_psign_w_128:
11924 case Intrinsic::x86_ssse3_psign_d_128:
11925 case Intrinsic::x86_avx2_psign_b:
11926 case Intrinsic::x86_avx2_psign_w:
11927 case Intrinsic::x86_avx2_psign_d:
11928 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
11929 Op.getOperand(1), Op.getOperand(2));
11931 case Intrinsic::x86_sse41_insertps:
11932 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
11933 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11935 case Intrinsic::x86_avx_vperm2f128_ps_256:
11936 case Intrinsic::x86_avx_vperm2f128_pd_256:
11937 case Intrinsic::x86_avx_vperm2f128_si_256:
11938 case Intrinsic::x86_avx2_vperm2i128:
11939 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
11940 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11942 case Intrinsic::x86_avx2_permd:
11943 case Intrinsic::x86_avx2_permps:
11944 // Operands intentionally swapped. Mask is last operand to intrinsic,
11945 // but second operand for node/instruction.
11946 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
11947 Op.getOperand(2), Op.getOperand(1));
11949 case Intrinsic::x86_sse_sqrt_ps:
11950 case Intrinsic::x86_sse2_sqrt_pd:
11951 case Intrinsic::x86_avx_sqrt_ps_256:
11952 case Intrinsic::x86_avx_sqrt_pd_256:
11953 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
11955 // ptest and testp intrinsics. The intrinsic these come from are designed to
11956 // return an integer value, not just an instruction so lower it to the ptest
11957 // or testp pattern and a setcc for the result.
11958 case Intrinsic::x86_sse41_ptestz:
11959 case Intrinsic::x86_sse41_ptestc:
11960 case Intrinsic::x86_sse41_ptestnzc:
11961 case Intrinsic::x86_avx_ptestz_256:
11962 case Intrinsic::x86_avx_ptestc_256:
11963 case Intrinsic::x86_avx_ptestnzc_256:
11964 case Intrinsic::x86_avx_vtestz_ps:
11965 case Intrinsic::x86_avx_vtestc_ps:
11966 case Intrinsic::x86_avx_vtestnzc_ps:
11967 case Intrinsic::x86_avx_vtestz_pd:
11968 case Intrinsic::x86_avx_vtestc_pd:
11969 case Intrinsic::x86_avx_vtestnzc_pd:
11970 case Intrinsic::x86_avx_vtestz_ps_256:
11971 case Intrinsic::x86_avx_vtestc_ps_256:
11972 case Intrinsic::x86_avx_vtestnzc_ps_256:
11973 case Intrinsic::x86_avx_vtestz_pd_256:
11974 case Intrinsic::x86_avx_vtestc_pd_256:
11975 case Intrinsic::x86_avx_vtestnzc_pd_256: {
11976 bool IsTestPacked = false;
11979 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
11980 case Intrinsic::x86_avx_vtestz_ps:
11981 case Intrinsic::x86_avx_vtestz_pd:
11982 case Intrinsic::x86_avx_vtestz_ps_256:
11983 case Intrinsic::x86_avx_vtestz_pd_256:
11984 IsTestPacked = true; // Fallthrough
11985 case Intrinsic::x86_sse41_ptestz:
11986 case Intrinsic::x86_avx_ptestz_256:
11988 X86CC = X86::COND_E;
11990 case Intrinsic::x86_avx_vtestc_ps:
11991 case Intrinsic::x86_avx_vtestc_pd:
11992 case Intrinsic::x86_avx_vtestc_ps_256:
11993 case Intrinsic::x86_avx_vtestc_pd_256:
11994 IsTestPacked = true; // Fallthrough
11995 case Intrinsic::x86_sse41_ptestc:
11996 case Intrinsic::x86_avx_ptestc_256:
11998 X86CC = X86::COND_B;
12000 case Intrinsic::x86_avx_vtestnzc_ps:
12001 case Intrinsic::x86_avx_vtestnzc_pd:
12002 case Intrinsic::x86_avx_vtestnzc_ps_256:
12003 case Intrinsic::x86_avx_vtestnzc_pd_256:
12004 IsTestPacked = true; // Fallthrough
12005 case Intrinsic::x86_sse41_ptestnzc:
12006 case Intrinsic::x86_avx_ptestnzc_256:
12008 X86CC = X86::COND_A;
12012 SDValue LHS = Op.getOperand(1);
12013 SDValue RHS = Op.getOperand(2);
12014 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
12015 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
12016 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12017 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
12018 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12020 case Intrinsic::x86_avx512_kortestz_w:
12021 case Intrinsic::x86_avx512_kortestc_w: {
12022 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
12023 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
12024 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
12025 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12026 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
12027 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
12028 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12031 // SSE/AVX shift intrinsics
12032 case Intrinsic::x86_sse2_psll_w:
12033 case Intrinsic::x86_sse2_psll_d:
12034 case Intrinsic::x86_sse2_psll_q:
12035 case Intrinsic::x86_avx2_psll_w:
12036 case Intrinsic::x86_avx2_psll_d:
12037 case Intrinsic::x86_avx2_psll_q:
12038 case Intrinsic::x86_sse2_psrl_w:
12039 case Intrinsic::x86_sse2_psrl_d:
12040 case Intrinsic::x86_sse2_psrl_q:
12041 case Intrinsic::x86_avx2_psrl_w:
12042 case Intrinsic::x86_avx2_psrl_d:
12043 case Intrinsic::x86_avx2_psrl_q:
12044 case Intrinsic::x86_sse2_psra_w:
12045 case Intrinsic::x86_sse2_psra_d:
12046 case Intrinsic::x86_avx2_psra_w:
12047 case Intrinsic::x86_avx2_psra_d: {
12050 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12051 case Intrinsic::x86_sse2_psll_w:
12052 case Intrinsic::x86_sse2_psll_d:
12053 case Intrinsic::x86_sse2_psll_q:
12054 case Intrinsic::x86_avx2_psll_w:
12055 case Intrinsic::x86_avx2_psll_d:
12056 case Intrinsic::x86_avx2_psll_q:
12057 Opcode = X86ISD::VSHL;
12059 case Intrinsic::x86_sse2_psrl_w:
12060 case Intrinsic::x86_sse2_psrl_d:
12061 case Intrinsic::x86_sse2_psrl_q:
12062 case Intrinsic::x86_avx2_psrl_w:
12063 case Intrinsic::x86_avx2_psrl_d:
12064 case Intrinsic::x86_avx2_psrl_q:
12065 Opcode = X86ISD::VSRL;
12067 case Intrinsic::x86_sse2_psra_w:
12068 case Intrinsic::x86_sse2_psra_d:
12069 case Intrinsic::x86_avx2_psra_w:
12070 case Intrinsic::x86_avx2_psra_d:
12071 Opcode = X86ISD::VSRA;
12074 return DAG.getNode(Opcode, dl, Op.getValueType(),
12075 Op.getOperand(1), Op.getOperand(2));
12078 // SSE/AVX immediate shift intrinsics
12079 case Intrinsic::x86_sse2_pslli_w:
12080 case Intrinsic::x86_sse2_pslli_d:
12081 case Intrinsic::x86_sse2_pslli_q:
12082 case Intrinsic::x86_avx2_pslli_w:
12083 case Intrinsic::x86_avx2_pslli_d:
12084 case Intrinsic::x86_avx2_pslli_q:
12085 case Intrinsic::x86_sse2_psrli_w:
12086 case Intrinsic::x86_sse2_psrli_d:
12087 case Intrinsic::x86_sse2_psrli_q:
12088 case Intrinsic::x86_avx2_psrli_w:
12089 case Intrinsic::x86_avx2_psrli_d:
12090 case Intrinsic::x86_avx2_psrli_q:
12091 case Intrinsic::x86_sse2_psrai_w:
12092 case Intrinsic::x86_sse2_psrai_d:
12093 case Intrinsic::x86_avx2_psrai_w:
12094 case Intrinsic::x86_avx2_psrai_d: {
12097 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12098 case Intrinsic::x86_sse2_pslli_w:
12099 case Intrinsic::x86_sse2_pslli_d:
12100 case Intrinsic::x86_sse2_pslli_q:
12101 case Intrinsic::x86_avx2_pslli_w:
12102 case Intrinsic::x86_avx2_pslli_d:
12103 case Intrinsic::x86_avx2_pslli_q:
12104 Opcode = X86ISD::VSHLI;
12106 case Intrinsic::x86_sse2_psrli_w:
12107 case Intrinsic::x86_sse2_psrli_d:
12108 case Intrinsic::x86_sse2_psrli_q:
12109 case Intrinsic::x86_avx2_psrli_w:
12110 case Intrinsic::x86_avx2_psrli_d:
12111 case Intrinsic::x86_avx2_psrli_q:
12112 Opcode = X86ISD::VSRLI;
12114 case Intrinsic::x86_sse2_psrai_w:
12115 case Intrinsic::x86_sse2_psrai_d:
12116 case Intrinsic::x86_avx2_psrai_w:
12117 case Intrinsic::x86_avx2_psrai_d:
12118 Opcode = X86ISD::VSRAI;
12121 return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
12122 Op.getOperand(1), Op.getOperand(2), DAG);
12125 case Intrinsic::x86_sse42_pcmpistria128:
12126 case Intrinsic::x86_sse42_pcmpestria128:
12127 case Intrinsic::x86_sse42_pcmpistric128:
12128 case Intrinsic::x86_sse42_pcmpestric128:
12129 case Intrinsic::x86_sse42_pcmpistrio128:
12130 case Intrinsic::x86_sse42_pcmpestrio128:
12131 case Intrinsic::x86_sse42_pcmpistris128:
12132 case Intrinsic::x86_sse42_pcmpestris128:
12133 case Intrinsic::x86_sse42_pcmpistriz128:
12134 case Intrinsic::x86_sse42_pcmpestriz128: {
12138 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12139 case Intrinsic::x86_sse42_pcmpistria128:
12140 Opcode = X86ISD::PCMPISTRI;
12141 X86CC = X86::COND_A;
12143 case Intrinsic::x86_sse42_pcmpestria128:
12144 Opcode = X86ISD::PCMPESTRI;
12145 X86CC = X86::COND_A;
12147 case Intrinsic::x86_sse42_pcmpistric128:
12148 Opcode = X86ISD::PCMPISTRI;
12149 X86CC = X86::COND_B;
12151 case Intrinsic::x86_sse42_pcmpestric128:
12152 Opcode = X86ISD::PCMPESTRI;
12153 X86CC = X86::COND_B;
12155 case Intrinsic::x86_sse42_pcmpistrio128:
12156 Opcode = X86ISD::PCMPISTRI;
12157 X86CC = X86::COND_O;
12159 case Intrinsic::x86_sse42_pcmpestrio128:
12160 Opcode = X86ISD::PCMPESTRI;
12161 X86CC = X86::COND_O;
12163 case Intrinsic::x86_sse42_pcmpistris128:
12164 Opcode = X86ISD::PCMPISTRI;
12165 X86CC = X86::COND_S;
12167 case Intrinsic::x86_sse42_pcmpestris128:
12168 Opcode = X86ISD::PCMPESTRI;
12169 X86CC = X86::COND_S;
12171 case Intrinsic::x86_sse42_pcmpistriz128:
12172 Opcode = X86ISD::PCMPISTRI;
12173 X86CC = X86::COND_E;
12175 case Intrinsic::x86_sse42_pcmpestriz128:
12176 Opcode = X86ISD::PCMPESTRI;
12177 X86CC = X86::COND_E;
12180 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12181 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12182 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
12183 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12184 DAG.getConstant(X86CC, MVT::i8),
12185 SDValue(PCMP.getNode(), 1));
12186 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12189 case Intrinsic::x86_sse42_pcmpistri128:
12190 case Intrinsic::x86_sse42_pcmpestri128: {
12192 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
12193 Opcode = X86ISD::PCMPISTRI;
12195 Opcode = X86ISD::PCMPESTRI;
12197 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12198 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12199 return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
12201 case Intrinsic::x86_fma_vfmadd_ps:
12202 case Intrinsic::x86_fma_vfmadd_pd:
12203 case Intrinsic::x86_fma_vfmsub_ps:
12204 case Intrinsic::x86_fma_vfmsub_pd:
12205 case Intrinsic::x86_fma_vfnmadd_ps:
12206 case Intrinsic::x86_fma_vfnmadd_pd:
12207 case Intrinsic::x86_fma_vfnmsub_ps:
12208 case Intrinsic::x86_fma_vfnmsub_pd:
12209 case Intrinsic::x86_fma_vfmaddsub_ps:
12210 case Intrinsic::x86_fma_vfmaddsub_pd:
12211 case Intrinsic::x86_fma_vfmsubadd_ps:
12212 case Intrinsic::x86_fma_vfmsubadd_pd:
12213 case Intrinsic::x86_fma_vfmadd_ps_256:
12214 case Intrinsic::x86_fma_vfmadd_pd_256:
12215 case Intrinsic::x86_fma_vfmsub_ps_256:
12216 case Intrinsic::x86_fma_vfmsub_pd_256:
12217 case Intrinsic::x86_fma_vfnmadd_ps_256:
12218 case Intrinsic::x86_fma_vfnmadd_pd_256:
12219 case Intrinsic::x86_fma_vfnmsub_ps_256:
12220 case Intrinsic::x86_fma_vfnmsub_pd_256:
12221 case Intrinsic::x86_fma_vfmaddsub_ps_256:
12222 case Intrinsic::x86_fma_vfmaddsub_pd_256:
12223 case Intrinsic::x86_fma_vfmsubadd_ps_256:
12224 case Intrinsic::x86_fma_vfmsubadd_pd_256:
12225 case Intrinsic::x86_fma_vfmadd_ps_512:
12226 case Intrinsic::x86_fma_vfmadd_pd_512:
12227 case Intrinsic::x86_fma_vfmsub_ps_512:
12228 case Intrinsic::x86_fma_vfmsub_pd_512:
12229 case Intrinsic::x86_fma_vfnmadd_ps_512:
12230 case Intrinsic::x86_fma_vfnmadd_pd_512:
12231 case Intrinsic::x86_fma_vfnmsub_ps_512:
12232 case Intrinsic::x86_fma_vfnmsub_pd_512:
12233 case Intrinsic::x86_fma_vfmaddsub_ps_512:
12234 case Intrinsic::x86_fma_vfmaddsub_pd_512:
12235 case Intrinsic::x86_fma_vfmsubadd_ps_512:
12236 case Intrinsic::x86_fma_vfmsubadd_pd_512: {
12239 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12240 case Intrinsic::x86_fma_vfmadd_ps:
12241 case Intrinsic::x86_fma_vfmadd_pd:
12242 case Intrinsic::x86_fma_vfmadd_ps_256:
12243 case Intrinsic::x86_fma_vfmadd_pd_256:
12244 case Intrinsic::x86_fma_vfmadd_ps_512:
12245 case Intrinsic::x86_fma_vfmadd_pd_512:
12246 Opc = X86ISD::FMADD;
12248 case Intrinsic::x86_fma_vfmsub_ps:
12249 case Intrinsic::x86_fma_vfmsub_pd:
12250 case Intrinsic::x86_fma_vfmsub_ps_256:
12251 case Intrinsic::x86_fma_vfmsub_pd_256:
12252 case Intrinsic::x86_fma_vfmsub_ps_512:
12253 case Intrinsic::x86_fma_vfmsub_pd_512:
12254 Opc = X86ISD::FMSUB;
12256 case Intrinsic::x86_fma_vfnmadd_ps:
12257 case Intrinsic::x86_fma_vfnmadd_pd:
12258 case Intrinsic::x86_fma_vfnmadd_ps_256:
12259 case Intrinsic::x86_fma_vfnmadd_pd_256:
12260 case Intrinsic::x86_fma_vfnmadd_ps_512:
12261 case Intrinsic::x86_fma_vfnmadd_pd_512:
12262 Opc = X86ISD::FNMADD;
12264 case Intrinsic::x86_fma_vfnmsub_ps:
12265 case Intrinsic::x86_fma_vfnmsub_pd:
12266 case Intrinsic::x86_fma_vfnmsub_ps_256:
12267 case Intrinsic::x86_fma_vfnmsub_pd_256:
12268 case Intrinsic::x86_fma_vfnmsub_ps_512:
12269 case Intrinsic::x86_fma_vfnmsub_pd_512:
12270 Opc = X86ISD::FNMSUB;
12272 case Intrinsic::x86_fma_vfmaddsub_ps:
12273 case Intrinsic::x86_fma_vfmaddsub_pd:
12274 case Intrinsic::x86_fma_vfmaddsub_ps_256:
12275 case Intrinsic::x86_fma_vfmaddsub_pd_256:
12276 case Intrinsic::x86_fma_vfmaddsub_ps_512:
12277 case Intrinsic::x86_fma_vfmaddsub_pd_512:
12278 Opc = X86ISD::FMADDSUB;
12280 case Intrinsic::x86_fma_vfmsubadd_ps:
12281 case Intrinsic::x86_fma_vfmsubadd_pd:
12282 case Intrinsic::x86_fma_vfmsubadd_ps_256:
12283 case Intrinsic::x86_fma_vfmsubadd_pd_256:
12284 case Intrinsic::x86_fma_vfmsubadd_ps_512:
12285 case Intrinsic::x86_fma_vfmsubadd_pd_512:
12286 Opc = X86ISD::FMSUBADD;
12290 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
12291 Op.getOperand(2), Op.getOperand(3));
12296 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12297 SDValue Base, SDValue Index,
12298 SDValue ScaleOp, SDValue Chain,
12299 const X86Subtarget * Subtarget) {
12301 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12302 assert(C && "Invalid scale type");
12303 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12304 SDValue Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12305 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12306 Index.getSimpleValueType().getVectorNumElements());
12307 SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12308 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12309 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12310 SDValue Segment = DAG.getRegister(0, MVT::i32);
12311 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12312 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12313 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12314 return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
12317 static SDValue getMGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12318 SDValue Src, SDValue Mask, SDValue Base,
12319 SDValue Index, SDValue ScaleOp, SDValue Chain,
12320 const X86Subtarget * Subtarget) {
12322 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12323 assert(C && "Invalid scale type");
12324 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12325 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12326 Index.getSimpleValueType().getVectorNumElements());
12327 SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12328 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12329 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12330 SDValue Segment = DAG.getRegister(0, MVT::i32);
12331 if (Src.getOpcode() == ISD::UNDEF)
12332 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12333 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12334 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12335 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12336 return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
12339 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12340 SDValue Src, SDValue Base, SDValue Index,
12341 SDValue ScaleOp, SDValue Chain) {
12343 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12344 assert(C && "Invalid scale type");
12345 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12346 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12347 SDValue Segment = DAG.getRegister(0, MVT::i32);
12348 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12349 Index.getSimpleValueType().getVectorNumElements());
12350 SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12351 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12352 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12353 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12354 return SDValue(Res, 1);
12357 static SDValue getMScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12358 SDValue Src, SDValue Mask, SDValue Base,
12359 SDValue Index, SDValue ScaleOp, SDValue Chain) {
12361 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12362 assert(C && "Invalid scale type");
12363 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12364 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12365 SDValue Segment = DAG.getRegister(0, MVT::i32);
12366 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12367 Index.getSimpleValueType().getVectorNumElements());
12368 SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12369 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12370 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12371 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12372 return SDValue(Res, 1);
12375 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
12376 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
12377 // also used to custom lower READCYCLECOUNTER nodes.
12378 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
12379 SelectionDAG &DAG, const X86Subtarget *Subtarget,
12380 SmallVectorImpl<SDValue> &Results) {
12381 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12382 SDValue TheChain = N->getOperand(0);
12383 SDValue rd = DAG.getNode(Opcode, DL, Tys, &TheChain, 1);
12386 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
12387 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
12388 // and the EAX register is loaded with the low-order 32 bits.
12389 if (Subtarget->is64Bit()) {
12390 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
12391 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
12394 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
12395 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
12398 SDValue Chain = HI.getValue(1);
12400 if (Opcode == X86ISD::RDTSCP_DAG) {
12401 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
12403 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
12404 // the ECX register. Add 'ecx' explicitly to the chain.
12405 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
12407 // Explicitly store the content of ECX at the location passed in input
12408 // to the 'rdtscp' intrinsic.
12409 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
12410 MachinePointerInfo(), false, false, 0);
12413 if (Subtarget->is64Bit()) {
12414 // The EDX register is loaded with the high-order 32 bits of the MSR, and
12415 // the EAX register is loaded with the low-order 32 bits.
12416 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
12417 DAG.getConstant(32, MVT::i8));
12418 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
12419 Results.push_back(Chain);
12423 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12424 SDValue Ops[] = { LO, HI };
12425 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops,
12426 array_lengthof(Ops));
12427 Results.push_back(Pair);
12428 Results.push_back(Chain);
12431 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12432 SelectionDAG &DAG) {
12433 SmallVector<SDValue, 2> Results;
12435 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
12437 return DAG.getMergeValues(&Results[0], Results.size(), DL);
12440 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
12441 SelectionDAG &DAG) {
12443 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12445 default: return SDValue(); // Don't custom lower most intrinsics.
12447 // RDRAND/RDSEED intrinsics.
12448 case Intrinsic::x86_rdrand_16:
12449 case Intrinsic::x86_rdrand_32:
12450 case Intrinsic::x86_rdrand_64:
12451 case Intrinsic::x86_rdseed_16:
12452 case Intrinsic::x86_rdseed_32:
12453 case Intrinsic::x86_rdseed_64: {
12454 unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
12455 IntNo == Intrinsic::x86_rdseed_32 ||
12456 IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
12458 // Emit the node with the right value type.
12459 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
12460 SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
12462 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
12463 // Otherwise return the value from Rand, which is always 0, casted to i32.
12464 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
12465 DAG.getConstant(1, Op->getValueType(1)),
12466 DAG.getConstant(X86::COND_B, MVT::i32),
12467 SDValue(Result.getNode(), 1) };
12468 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
12469 DAG.getVTList(Op->getValueType(1), MVT::Glue),
12470 Ops, array_lengthof(Ops));
12472 // Return { result, isValid, chain }.
12473 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
12474 SDValue(Result.getNode(), 2));
12476 //int_gather(index, base, scale);
12477 case Intrinsic::x86_avx512_gather_qpd_512:
12478 case Intrinsic::x86_avx512_gather_qps_512:
12479 case Intrinsic::x86_avx512_gather_dpd_512:
12480 case Intrinsic::x86_avx512_gather_qpi_512:
12481 case Intrinsic::x86_avx512_gather_qpq_512:
12482 case Intrinsic::x86_avx512_gather_dpq_512:
12483 case Intrinsic::x86_avx512_gather_dps_512:
12484 case Intrinsic::x86_avx512_gather_dpi_512: {
12487 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12488 case Intrinsic::x86_avx512_gather_qps_512: Opc = X86::VGATHERQPSZrm; break;
12489 case Intrinsic::x86_avx512_gather_qpd_512: Opc = X86::VGATHERQPDZrm; break;
12490 case Intrinsic::x86_avx512_gather_dpd_512: Opc = X86::VGATHERDPDZrm; break;
12491 case Intrinsic::x86_avx512_gather_dps_512: Opc = X86::VGATHERDPSZrm; break;
12492 case Intrinsic::x86_avx512_gather_qpi_512: Opc = X86::VPGATHERQDZrm; break;
12493 case Intrinsic::x86_avx512_gather_qpq_512: Opc = X86::VPGATHERQQZrm; break;
12494 case Intrinsic::x86_avx512_gather_dpi_512: Opc = X86::VPGATHERDDZrm; break;
12495 case Intrinsic::x86_avx512_gather_dpq_512: Opc = X86::VPGATHERDQZrm; break;
12497 SDValue Chain = Op.getOperand(0);
12498 SDValue Index = Op.getOperand(2);
12499 SDValue Base = Op.getOperand(3);
12500 SDValue Scale = Op.getOperand(4);
12501 return getGatherNode(Opc, Op, DAG, Base, Index, Scale, Chain, Subtarget);
12503 //int_gather_mask(v1, mask, index, base, scale);
12504 case Intrinsic::x86_avx512_gather_qps_mask_512:
12505 case Intrinsic::x86_avx512_gather_qpd_mask_512:
12506 case Intrinsic::x86_avx512_gather_dpd_mask_512:
12507 case Intrinsic::x86_avx512_gather_dps_mask_512:
12508 case Intrinsic::x86_avx512_gather_qpi_mask_512:
12509 case Intrinsic::x86_avx512_gather_qpq_mask_512:
12510 case Intrinsic::x86_avx512_gather_dpi_mask_512:
12511 case Intrinsic::x86_avx512_gather_dpq_mask_512: {
12514 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12515 case Intrinsic::x86_avx512_gather_qps_mask_512:
12516 Opc = X86::VGATHERQPSZrm; break;
12517 case Intrinsic::x86_avx512_gather_qpd_mask_512:
12518 Opc = X86::VGATHERQPDZrm; break;
12519 case Intrinsic::x86_avx512_gather_dpd_mask_512:
12520 Opc = X86::VGATHERDPDZrm; break;
12521 case Intrinsic::x86_avx512_gather_dps_mask_512:
12522 Opc = X86::VGATHERDPSZrm; break;
12523 case Intrinsic::x86_avx512_gather_qpi_mask_512:
12524 Opc = X86::VPGATHERQDZrm; break;
12525 case Intrinsic::x86_avx512_gather_qpq_mask_512:
12526 Opc = X86::VPGATHERQQZrm; break;
12527 case Intrinsic::x86_avx512_gather_dpi_mask_512:
12528 Opc = X86::VPGATHERDDZrm; break;
12529 case Intrinsic::x86_avx512_gather_dpq_mask_512:
12530 Opc = X86::VPGATHERDQZrm; break;
12532 SDValue Chain = Op.getOperand(0);
12533 SDValue Src = Op.getOperand(2);
12534 SDValue Mask = Op.getOperand(3);
12535 SDValue Index = Op.getOperand(4);
12536 SDValue Base = Op.getOperand(5);
12537 SDValue Scale = Op.getOperand(6);
12538 return getMGatherNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
12541 //int_scatter(base, index, v1, scale);
12542 case Intrinsic::x86_avx512_scatter_qpd_512:
12543 case Intrinsic::x86_avx512_scatter_qps_512:
12544 case Intrinsic::x86_avx512_scatter_dpd_512:
12545 case Intrinsic::x86_avx512_scatter_qpi_512:
12546 case Intrinsic::x86_avx512_scatter_qpq_512:
12547 case Intrinsic::x86_avx512_scatter_dpq_512:
12548 case Intrinsic::x86_avx512_scatter_dps_512:
12549 case Intrinsic::x86_avx512_scatter_dpi_512: {
12552 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12553 case Intrinsic::x86_avx512_scatter_qpd_512:
12554 Opc = X86::VSCATTERQPDZmr; break;
12555 case Intrinsic::x86_avx512_scatter_qps_512:
12556 Opc = X86::VSCATTERQPSZmr; break;
12557 case Intrinsic::x86_avx512_scatter_dpd_512:
12558 Opc = X86::VSCATTERDPDZmr; break;
12559 case Intrinsic::x86_avx512_scatter_dps_512:
12560 Opc = X86::VSCATTERDPSZmr; break;
12561 case Intrinsic::x86_avx512_scatter_qpi_512:
12562 Opc = X86::VPSCATTERQDZmr; break;
12563 case Intrinsic::x86_avx512_scatter_qpq_512:
12564 Opc = X86::VPSCATTERQQZmr; break;
12565 case Intrinsic::x86_avx512_scatter_dpq_512:
12566 Opc = X86::VPSCATTERDQZmr; break;
12567 case Intrinsic::x86_avx512_scatter_dpi_512:
12568 Opc = X86::VPSCATTERDDZmr; break;
12570 SDValue Chain = Op.getOperand(0);
12571 SDValue Base = Op.getOperand(2);
12572 SDValue Index = Op.getOperand(3);
12573 SDValue Src = Op.getOperand(4);
12574 SDValue Scale = Op.getOperand(5);
12575 return getScatterNode(Opc, Op, DAG, Src, Base, Index, Scale, Chain);
12577 //int_scatter_mask(base, mask, index, v1, scale);
12578 case Intrinsic::x86_avx512_scatter_qps_mask_512:
12579 case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12580 case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12581 case Intrinsic::x86_avx512_scatter_dps_mask_512:
12582 case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12583 case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12584 case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12585 case Intrinsic::x86_avx512_scatter_dpq_mask_512: {
12588 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12589 case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12590 Opc = X86::VSCATTERQPDZmr; break;
12591 case Intrinsic::x86_avx512_scatter_qps_mask_512:
12592 Opc = X86::VSCATTERQPSZmr; break;
12593 case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12594 Opc = X86::VSCATTERDPDZmr; break;
12595 case Intrinsic::x86_avx512_scatter_dps_mask_512:
12596 Opc = X86::VSCATTERDPSZmr; break;
12597 case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12598 Opc = X86::VPSCATTERQDZmr; break;
12599 case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12600 Opc = X86::VPSCATTERQQZmr; break;
12601 case Intrinsic::x86_avx512_scatter_dpq_mask_512:
12602 Opc = X86::VPSCATTERDQZmr; break;
12603 case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12604 Opc = X86::VPSCATTERDDZmr; break;
12606 SDValue Chain = Op.getOperand(0);
12607 SDValue Base = Op.getOperand(2);
12608 SDValue Mask = Op.getOperand(3);
12609 SDValue Index = Op.getOperand(4);
12610 SDValue Src = Op.getOperand(5);
12611 SDValue Scale = Op.getOperand(6);
12612 return getMScatterNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
12614 // Read Time Stamp Counter (RDTSC).
12615 case Intrinsic::x86_rdtsc:
12616 // Read Time Stamp Counter and Processor ID (RDTSCP).
12617 case Intrinsic::x86_rdtscp: {
12620 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12621 case Intrinsic::x86_rdtsc:
12622 Opc = X86ISD::RDTSC_DAG; break;
12623 case Intrinsic::x86_rdtscp:
12624 Opc = X86ISD::RDTSCP_DAG; break;
12626 SmallVector<SDValue, 2> Results;
12627 getReadTimeStampCounter(Op.getNode(), dl, Opc, DAG, Subtarget, Results);
12628 return DAG.getMergeValues(&Results[0], Results.size(), dl);
12630 // XTEST intrinsics.
12631 case Intrinsic::x86_xtest: {
12632 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
12633 SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
12634 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12635 DAG.getConstant(X86::COND_NE, MVT::i8),
12637 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
12638 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
12639 Ret, SDValue(InTrans.getNode(), 1));
12644 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
12645 SelectionDAG &DAG) const {
12646 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12647 MFI->setReturnAddressIsTaken(true);
12649 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
12652 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12654 EVT PtrVT = getPointerTy();
12657 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12658 const X86RegisterInfo *RegInfo =
12659 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12660 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
12661 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12662 DAG.getNode(ISD::ADD, dl, PtrVT,
12663 FrameAddr, Offset),
12664 MachinePointerInfo(), false, false, false, 0);
12667 // Just load the return address.
12668 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
12669 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12670 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
12673 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
12674 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12675 MFI->setFrameAddressIsTaken(true);
12677 EVT VT = Op.getValueType();
12678 SDLoc dl(Op); // FIXME probably not meaningful
12679 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12680 const X86RegisterInfo *RegInfo =
12681 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12682 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12683 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
12684 (FrameReg == X86::EBP && VT == MVT::i32)) &&
12685 "Invalid Frame Register!");
12686 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
12688 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
12689 MachinePointerInfo(),
12690 false, false, false, 0);
12694 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
12695 SelectionDAG &DAG) const {
12696 const X86RegisterInfo *RegInfo =
12697 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12698 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
12701 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
12702 SDValue Chain = Op.getOperand(0);
12703 SDValue Offset = Op.getOperand(1);
12704 SDValue Handler = Op.getOperand(2);
12707 EVT PtrVT = getPointerTy();
12708 const X86RegisterInfo *RegInfo =
12709 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12710 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12711 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
12712 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
12713 "Invalid Frame Register!");
12714 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
12715 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
12717 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
12718 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
12719 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
12720 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
12722 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
12724 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
12725 DAG.getRegister(StoreAddrReg, PtrVT));
12728 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
12729 SelectionDAG &DAG) const {
12731 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
12732 DAG.getVTList(MVT::i32, MVT::Other),
12733 Op.getOperand(0), Op.getOperand(1));
12736 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
12737 SelectionDAG &DAG) const {
12739 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
12740 Op.getOperand(0), Op.getOperand(1));
12743 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
12744 return Op.getOperand(0);
12747 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
12748 SelectionDAG &DAG) const {
12749 SDValue Root = Op.getOperand(0);
12750 SDValue Trmp = Op.getOperand(1); // trampoline
12751 SDValue FPtr = Op.getOperand(2); // nested function
12752 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
12755 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
12756 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12758 if (Subtarget->is64Bit()) {
12759 SDValue OutChains[6];
12761 // Large code-model.
12762 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
12763 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
12765 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
12766 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
12768 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
12770 // Load the pointer to the nested function into R11.
12771 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
12772 SDValue Addr = Trmp;
12773 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12774 Addr, MachinePointerInfo(TrmpAddr),
12777 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12778 DAG.getConstant(2, MVT::i64));
12779 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
12780 MachinePointerInfo(TrmpAddr, 2),
12783 // Load the 'nest' parameter value into R10.
12784 // R10 is specified in X86CallingConv.td
12785 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
12786 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12787 DAG.getConstant(10, MVT::i64));
12788 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12789 Addr, MachinePointerInfo(TrmpAddr, 10),
12792 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12793 DAG.getConstant(12, MVT::i64));
12794 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
12795 MachinePointerInfo(TrmpAddr, 12),
12798 // Jump to the nested function.
12799 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
12800 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12801 DAG.getConstant(20, MVT::i64));
12802 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12803 Addr, MachinePointerInfo(TrmpAddr, 20),
12806 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
12807 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12808 DAG.getConstant(22, MVT::i64));
12809 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
12810 MachinePointerInfo(TrmpAddr, 22),
12813 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
12815 const Function *Func =
12816 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
12817 CallingConv::ID CC = Func->getCallingConv();
12822 llvm_unreachable("Unsupported calling convention");
12823 case CallingConv::C:
12824 case CallingConv::X86_StdCall: {
12825 // Pass 'nest' parameter in ECX.
12826 // Must be kept in sync with X86CallingConv.td
12827 NestReg = X86::ECX;
12829 // Check that ECX wasn't needed by an 'inreg' parameter.
12830 FunctionType *FTy = Func->getFunctionType();
12831 const AttributeSet &Attrs = Func->getAttributes();
12833 if (!Attrs.isEmpty() && !Func->isVarArg()) {
12834 unsigned InRegCount = 0;
12837 for (FunctionType::param_iterator I = FTy->param_begin(),
12838 E = FTy->param_end(); I != E; ++I, ++Idx)
12839 if (Attrs.hasAttribute(Idx, Attribute::InReg))
12840 // FIXME: should only count parameters that are lowered to integers.
12841 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
12843 if (InRegCount > 2) {
12844 report_fatal_error("Nest register in use - reduce number of inreg"
12850 case CallingConv::X86_FastCall:
12851 case CallingConv::X86_ThisCall:
12852 case CallingConv::Fast:
12853 // Pass 'nest' parameter in EAX.
12854 // Must be kept in sync with X86CallingConv.td
12855 NestReg = X86::EAX;
12859 SDValue OutChains[4];
12860 SDValue Addr, Disp;
12862 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12863 DAG.getConstant(10, MVT::i32));
12864 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
12866 // This is storing the opcode for MOV32ri.
12867 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
12868 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
12869 OutChains[0] = DAG.getStore(Root, dl,
12870 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
12871 Trmp, MachinePointerInfo(TrmpAddr),
12874 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12875 DAG.getConstant(1, MVT::i32));
12876 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
12877 MachinePointerInfo(TrmpAddr, 1),
12880 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
12881 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12882 DAG.getConstant(5, MVT::i32));
12883 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
12884 MachinePointerInfo(TrmpAddr, 5),
12887 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12888 DAG.getConstant(6, MVT::i32));
12889 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
12890 MachinePointerInfo(TrmpAddr, 6),
12893 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
12897 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
12898 SelectionDAG &DAG) const {
12900 The rounding mode is in bits 11:10 of FPSR, and has the following
12902 00 Round to nearest
12907 FLT_ROUNDS, on the other hand, expects the following:
12914 To perform the conversion, we do:
12915 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
12918 MachineFunction &MF = DAG.getMachineFunction();
12919 const TargetMachine &TM = MF.getTarget();
12920 const TargetFrameLowering &TFI = *TM.getFrameLowering();
12921 unsigned StackAlignment = TFI.getStackAlignment();
12922 MVT VT = Op.getSimpleValueType();
12925 // Save FP Control Word to stack slot
12926 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
12927 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12929 MachineMemOperand *MMO =
12930 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12931 MachineMemOperand::MOStore, 2, 2);
12933 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
12934 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
12935 DAG.getVTList(MVT::Other),
12936 Ops, array_lengthof(Ops), MVT::i16,
12939 // Load FP Control Word from stack slot
12940 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
12941 MachinePointerInfo(), false, false, false, 0);
12943 // Transform as necessary
12945 DAG.getNode(ISD::SRL, DL, MVT::i16,
12946 DAG.getNode(ISD::AND, DL, MVT::i16,
12947 CWD, DAG.getConstant(0x800, MVT::i16)),
12948 DAG.getConstant(11, MVT::i8));
12950 DAG.getNode(ISD::SRL, DL, MVT::i16,
12951 DAG.getNode(ISD::AND, DL, MVT::i16,
12952 CWD, DAG.getConstant(0x400, MVT::i16)),
12953 DAG.getConstant(9, MVT::i8));
12956 DAG.getNode(ISD::AND, DL, MVT::i16,
12957 DAG.getNode(ISD::ADD, DL, MVT::i16,
12958 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
12959 DAG.getConstant(1, MVT::i16)),
12960 DAG.getConstant(3, MVT::i16));
12962 return DAG.getNode((VT.getSizeInBits() < 16 ?
12963 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
12966 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
12967 MVT VT = Op.getSimpleValueType();
12969 unsigned NumBits = VT.getSizeInBits();
12972 Op = Op.getOperand(0);
12973 if (VT == MVT::i8) {
12974 // Zero extend to i32 since there is not an i8 bsr.
12976 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
12979 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
12980 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12981 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
12983 // If src is zero (i.e. bsr sets ZF), returns NumBits.
12986 DAG.getConstant(NumBits+NumBits-1, OpVT),
12987 DAG.getConstant(X86::COND_E, MVT::i8),
12990 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
12992 // Finally xor with NumBits-1.
12993 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
12996 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13000 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
13001 MVT VT = Op.getSimpleValueType();
13003 unsigned NumBits = VT.getSizeInBits();
13006 Op = Op.getOperand(0);
13007 if (VT == MVT::i8) {
13008 // Zero extend to i32 since there is not an i8 bsr.
13010 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13013 // Issue a bsr (scan bits in reverse).
13014 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13015 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13017 // And xor with NumBits-1.
13018 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13021 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13025 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
13026 MVT VT = Op.getSimpleValueType();
13027 unsigned NumBits = VT.getSizeInBits();
13029 Op = Op.getOperand(0);
13031 // Issue a bsf (scan bits forward) which also sets EFLAGS.
13032 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13033 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
13035 // If src is zero (i.e. bsf sets ZF), returns NumBits.
13038 DAG.getConstant(NumBits, VT),
13039 DAG.getConstant(X86::COND_E, MVT::i8),
13042 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
13045 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
13046 // ones, and then concatenate the result back.
13047 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
13048 MVT VT = Op.getSimpleValueType();
13050 assert(VT.is256BitVector() && VT.isInteger() &&
13051 "Unsupported value type for operation");
13053 unsigned NumElems = VT.getVectorNumElements();
13056 // Extract the LHS vectors
13057 SDValue LHS = Op.getOperand(0);
13058 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13059 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13061 // Extract the RHS vectors
13062 SDValue RHS = Op.getOperand(1);
13063 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13064 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13066 MVT EltVT = VT.getVectorElementType();
13067 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13069 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13070 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
13071 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
13074 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
13075 assert(Op.getSimpleValueType().is256BitVector() &&
13076 Op.getSimpleValueType().isInteger() &&
13077 "Only handle AVX 256-bit vector integer operation");
13078 return Lower256IntArith(Op, DAG);
13081 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
13082 assert(Op.getSimpleValueType().is256BitVector() &&
13083 Op.getSimpleValueType().isInteger() &&
13084 "Only handle AVX 256-bit vector integer operation");
13085 return Lower256IntArith(Op, DAG);
13088 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
13089 SelectionDAG &DAG) {
13091 MVT VT = Op.getSimpleValueType();
13093 // Decompose 256-bit ops into smaller 128-bit ops.
13094 if (VT.is256BitVector() && !Subtarget->hasInt256())
13095 return Lower256IntArith(Op, DAG);
13097 SDValue A = Op.getOperand(0);
13098 SDValue B = Op.getOperand(1);
13100 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
13101 if (VT == MVT::v4i32) {
13102 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
13103 "Should not custom lower when pmuldq is available!");
13105 // Extract the odd parts.
13106 static const int UnpackMask[] = { 1, -1, 3, -1 };
13107 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
13108 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
13110 // Multiply the even parts.
13111 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
13112 // Now multiply odd parts.
13113 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
13115 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
13116 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
13118 // Merge the two vectors back together with a shuffle. This expands into 2
13120 static const int ShufMask[] = { 0, 4, 2, 6 };
13121 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
13124 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
13125 "Only know how to lower V2I64/V4I64/V8I64 multiply");
13127 // Ahi = psrlqi(a, 32);
13128 // Bhi = psrlqi(b, 32);
13130 // AloBlo = pmuludq(a, b);
13131 // AloBhi = pmuludq(a, Bhi);
13132 // AhiBlo = pmuludq(Ahi, b);
13134 // AloBhi = psllqi(AloBhi, 32);
13135 // AhiBlo = psllqi(AhiBlo, 32);
13136 // return AloBlo + AloBhi + AhiBlo;
13138 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
13139 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
13141 // Bit cast to 32-bit vectors for MULUDQ
13142 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
13143 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
13144 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
13145 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
13146 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
13147 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
13149 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
13150 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
13151 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
13153 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
13154 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
13156 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
13157 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
13160 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
13161 MVT VT = Op.getSimpleValueType();
13162 MVT EltTy = VT.getVectorElementType();
13163 unsigned NumElts = VT.getVectorNumElements();
13164 SDValue N0 = Op.getOperand(0);
13167 // Lower sdiv X, pow2-const.
13168 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
13172 APInt SplatValue, SplatUndef;
13173 unsigned SplatBitSize;
13175 if (!C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
13177 EltTy.getSizeInBits() < SplatBitSize)
13180 if ((SplatValue != 0) &&
13181 (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
13182 unsigned Lg2 = SplatValue.countTrailingZeros();
13183 // Splat the sign bit.
13184 SmallVector<SDValue, 16> Sz(NumElts,
13185 DAG.getConstant(EltTy.getSizeInBits() - 1,
13187 SDValue SGN = DAG.getNode(ISD::SRA, dl, VT, N0,
13188 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Sz[0],
13190 // Add (N0 < 0) ? abs2 - 1 : 0;
13191 SmallVector<SDValue, 16> Amt(NumElts,
13192 DAG.getConstant(EltTy.getSizeInBits() - Lg2,
13194 SDValue SRL = DAG.getNode(ISD::SRL, dl, VT, SGN,
13195 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Amt[0],
13197 SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
13198 SmallVector<SDValue, 16> Lg2Amt(NumElts, DAG.getConstant(Lg2, EltTy));
13199 SDValue SRA = DAG.getNode(ISD::SRA, dl, VT, ADD,
13200 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Lg2Amt[0],
13203 // If we're dividing by a positive value, we're done. Otherwise, we must
13204 // negate the result.
13205 if (SplatValue.isNonNegative())
13208 SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
13209 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
13210 return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
13215 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
13216 const X86Subtarget *Subtarget) {
13217 MVT VT = Op.getSimpleValueType();
13219 SDValue R = Op.getOperand(0);
13220 SDValue Amt = Op.getOperand(1);
13222 // Optimize shl/srl/sra with constant shift amount.
13223 if (isSplatVector(Amt.getNode())) {
13224 SDValue SclrAmt = Amt->getOperand(0);
13225 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
13226 uint64_t ShiftAmt = C->getZExtValue();
13228 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
13229 (Subtarget->hasInt256() &&
13230 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13231 (Subtarget->hasAVX512() &&
13232 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13233 if (Op.getOpcode() == ISD::SHL)
13234 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13236 if (Op.getOpcode() == ISD::SRL)
13237 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13239 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
13240 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13244 if (VT == MVT::v16i8) {
13245 if (Op.getOpcode() == ISD::SHL) {
13246 // Make a large shift.
13247 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13248 MVT::v8i16, R, ShiftAmt,
13250 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13251 // Zero out the rightmost bits.
13252 SmallVector<SDValue, 16> V(16,
13253 DAG.getConstant(uint8_t(-1U << ShiftAmt),
13255 return DAG.getNode(ISD::AND, dl, VT, SHL,
13256 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
13258 if (Op.getOpcode() == ISD::SRL) {
13259 // Make a large shift.
13260 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13261 MVT::v8i16, R, ShiftAmt,
13263 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13264 // Zero out the leftmost bits.
13265 SmallVector<SDValue, 16> V(16,
13266 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13268 return DAG.getNode(ISD::AND, dl, VT, SRL,
13269 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
13271 if (Op.getOpcode() == ISD::SRA) {
13272 if (ShiftAmt == 7) {
13273 // R s>> 7 === R s< 0
13274 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13275 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13278 // R s>> a === ((R u>> a) ^ m) - m
13279 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13280 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
13282 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
13283 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13284 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13287 llvm_unreachable("Unknown shift opcode.");
13290 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
13291 if (Op.getOpcode() == ISD::SHL) {
13292 // Make a large shift.
13293 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13294 MVT::v16i16, R, ShiftAmt,
13296 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13297 // Zero out the rightmost bits.
13298 SmallVector<SDValue, 32> V(32,
13299 DAG.getConstant(uint8_t(-1U << ShiftAmt),
13301 return DAG.getNode(ISD::AND, dl, VT, SHL,
13302 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
13304 if (Op.getOpcode() == ISD::SRL) {
13305 // Make a large shift.
13306 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13307 MVT::v16i16, R, ShiftAmt,
13309 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13310 // Zero out the leftmost bits.
13311 SmallVector<SDValue, 32> V(32,
13312 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13314 return DAG.getNode(ISD::AND, dl, VT, SRL,
13315 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
13317 if (Op.getOpcode() == ISD::SRA) {
13318 if (ShiftAmt == 7) {
13319 // R s>> 7 === R s< 0
13320 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13321 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13324 // R s>> a === ((R u>> a) ^ m) - m
13325 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13326 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
13328 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
13329 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13330 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13333 llvm_unreachable("Unknown shift opcode.");
13338 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13339 if (!Subtarget->is64Bit() &&
13340 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
13341 Amt.getOpcode() == ISD::BITCAST &&
13342 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13343 Amt = Amt.getOperand(0);
13344 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13345 VT.getVectorNumElements();
13346 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
13347 uint64_t ShiftAmt = 0;
13348 for (unsigned i = 0; i != Ratio; ++i) {
13349 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
13353 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
13355 // Check remaining shift amounts.
13356 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13357 uint64_t ShAmt = 0;
13358 for (unsigned j = 0; j != Ratio; ++j) {
13359 ConstantSDNode *C =
13360 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
13364 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
13366 if (ShAmt != ShiftAmt)
13369 switch (Op.getOpcode()) {
13371 llvm_unreachable("Unknown shift opcode!");
13373 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13376 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13379 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13387 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
13388 const X86Subtarget* Subtarget) {
13389 MVT VT = Op.getSimpleValueType();
13391 SDValue R = Op.getOperand(0);
13392 SDValue Amt = Op.getOperand(1);
13394 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
13395 VT == MVT::v4i32 || VT == MVT::v8i16 ||
13396 (Subtarget->hasInt256() &&
13397 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
13398 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13399 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13401 EVT EltVT = VT.getVectorElementType();
13403 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13404 unsigned NumElts = VT.getVectorNumElements();
13406 for (i = 0; i != NumElts; ++i) {
13407 if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
13411 for (j = i; j != NumElts; ++j) {
13412 SDValue Arg = Amt.getOperand(j);
13413 if (Arg.getOpcode() == ISD::UNDEF) continue;
13414 if (Arg != Amt.getOperand(i))
13417 if (i != NumElts && j == NumElts)
13418 BaseShAmt = Amt.getOperand(i);
13420 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13421 Amt = Amt.getOperand(0);
13422 if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
13423 cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
13424 SDValue InVec = Amt.getOperand(0);
13425 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13426 unsigned NumElts = InVec.getValueType().getVectorNumElements();
13428 for (; i != NumElts; ++i) {
13429 SDValue Arg = InVec.getOperand(i);
13430 if (Arg.getOpcode() == ISD::UNDEF) continue;
13434 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13435 if (ConstantSDNode *C =
13436 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13437 unsigned SplatIdx =
13438 cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
13439 if (C->getZExtValue() == SplatIdx)
13440 BaseShAmt = InVec.getOperand(1);
13443 if (!BaseShAmt.getNode())
13444 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
13445 DAG.getIntPtrConstant(0));
13449 if (BaseShAmt.getNode()) {
13450 if (EltVT.bitsGT(MVT::i32))
13451 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
13452 else if (EltVT.bitsLT(MVT::i32))
13453 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
13455 switch (Op.getOpcode()) {
13457 llvm_unreachable("Unknown shift opcode!");
13459 switch (VT.SimpleTy) {
13460 default: return SDValue();
13469 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
13472 switch (VT.SimpleTy) {
13473 default: return SDValue();
13480 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
13483 switch (VT.SimpleTy) {
13484 default: return SDValue();
13493 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
13499 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13500 if (!Subtarget->is64Bit() &&
13501 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
13502 (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
13503 Amt.getOpcode() == ISD::BITCAST &&
13504 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13505 Amt = Amt.getOperand(0);
13506 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13507 VT.getVectorNumElements();
13508 std::vector<SDValue> Vals(Ratio);
13509 for (unsigned i = 0; i != Ratio; ++i)
13510 Vals[i] = Amt.getOperand(i);
13511 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13512 for (unsigned j = 0; j != Ratio; ++j)
13513 if (Vals[j] != Amt.getOperand(i + j))
13516 switch (Op.getOpcode()) {
13518 llvm_unreachable("Unknown shift opcode!");
13520 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
13522 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
13524 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
13531 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
13532 SelectionDAG &DAG) {
13534 MVT VT = Op.getSimpleValueType();
13536 SDValue R = Op.getOperand(0);
13537 SDValue Amt = Op.getOperand(1);
13540 if (!Subtarget->hasSSE2())
13543 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
13547 V = LowerScalarVariableShift(Op, DAG, Subtarget);
13551 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
13553 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
13554 if (Subtarget->hasInt256()) {
13555 if (Op.getOpcode() == ISD::SRL &&
13556 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13557 VT == MVT::v4i64 || VT == MVT::v8i32))
13559 if (Op.getOpcode() == ISD::SHL &&
13560 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13561 VT == MVT::v4i64 || VT == MVT::v8i32))
13563 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
13567 // If possible, lower this packed shift into a vector multiply instead of
13568 // expanding it into a sequence of scalar shifts.
13569 // Do this only if the vector shift count is a constant build_vector.
13570 if (Op.getOpcode() == ISD::SHL &&
13571 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
13572 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
13573 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13574 SmallVector<SDValue, 8> Elts;
13575 EVT SVT = VT.getScalarType();
13576 unsigned SVTBits = SVT.getSizeInBits();
13577 const APInt &One = APInt(SVTBits, 1);
13578 unsigned NumElems = VT.getVectorNumElements();
13580 for (unsigned i=0; i !=NumElems; ++i) {
13581 SDValue Op = Amt->getOperand(i);
13582 if (Op->getOpcode() == ISD::UNDEF) {
13583 Elts.push_back(Op);
13587 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
13588 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
13589 uint64_t ShAmt = C.getZExtValue();
13590 if (ShAmt >= SVTBits) {
13591 Elts.push_back(DAG.getUNDEF(SVT));
13594 Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
13596 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Elts[0], NumElems);
13597 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
13600 // Lower SHL with variable shift amount.
13601 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
13602 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
13604 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
13605 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
13606 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
13607 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
13610 // If possible, lower this shift as a sequence of two shifts by
13611 // constant plus a MOVSS/MOVSD instead of scalarizing it.
13613 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
13615 // Could be rewritten as:
13616 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
13618 // The advantage is that the two shifts from the example would be
13619 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
13620 // the vector shift into four scalar shifts plus four pairs of vector
13622 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
13623 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13624 unsigned TargetOpcode = X86ISD::MOVSS;
13625 bool CanBeSimplified;
13626 // The splat value for the first packed shift (the 'X' from the example).
13627 SDValue Amt1 = Amt->getOperand(0);
13628 // The splat value for the second packed shift (the 'Y' from the example).
13629 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
13630 Amt->getOperand(2);
13632 // See if it is possible to replace this node with a sequence of
13633 // two shifts followed by a MOVSS/MOVSD
13634 if (VT == MVT::v4i32) {
13635 // Check if it is legal to use a MOVSS.
13636 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
13637 Amt2 == Amt->getOperand(3);
13638 if (!CanBeSimplified) {
13639 // Otherwise, check if we can still simplify this node using a MOVSD.
13640 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
13641 Amt->getOperand(2) == Amt->getOperand(3);
13642 TargetOpcode = X86ISD::MOVSD;
13643 Amt2 = Amt->getOperand(2);
13646 // Do similar checks for the case where the machine value type
13648 CanBeSimplified = Amt1 == Amt->getOperand(1);
13649 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
13650 CanBeSimplified = Amt2 == Amt->getOperand(i);
13652 if (!CanBeSimplified) {
13653 TargetOpcode = X86ISD::MOVSD;
13654 CanBeSimplified = true;
13655 Amt2 = Amt->getOperand(4);
13656 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
13657 CanBeSimplified = Amt1 == Amt->getOperand(i);
13658 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
13659 CanBeSimplified = Amt2 == Amt->getOperand(j);
13663 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
13664 isa<ConstantSDNode>(Amt2)) {
13665 // Replace this node with two shifts followed by a MOVSS/MOVSD.
13666 EVT CastVT = MVT::v4i32;
13668 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
13669 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
13671 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
13672 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
13673 if (TargetOpcode == X86ISD::MOVSD)
13674 CastVT = MVT::v2i64;
13675 SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
13676 SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
13677 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
13679 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13683 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
13684 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
13687 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
13688 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
13690 // Turn 'a' into a mask suitable for VSELECT
13691 SDValue VSelM = DAG.getConstant(0x80, VT);
13692 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13693 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13695 SDValue CM1 = DAG.getConstant(0x0f, VT);
13696 SDValue CM2 = DAG.getConstant(0x3f, VT);
13698 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
13699 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
13700 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
13701 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13702 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13705 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13706 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13707 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13709 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
13710 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
13711 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
13712 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13713 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13716 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13717 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13718 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13720 // return VSELECT(r, r+r, a);
13721 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
13722 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
13726 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
13727 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
13728 // solution better.
13729 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
13730 MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
13732 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
13733 R = DAG.getNode(ExtOpc, dl, NewVT, R);
13734 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
13735 return DAG.getNode(ISD::TRUNCATE, dl, VT,
13736 DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
13739 // Decompose 256-bit shifts into smaller 128-bit shifts.
13740 if (VT.is256BitVector()) {
13741 unsigned NumElems = VT.getVectorNumElements();
13742 MVT EltVT = VT.getVectorElementType();
13743 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13745 // Extract the two vectors
13746 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
13747 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
13749 // Recreate the shift amount vectors
13750 SDValue Amt1, Amt2;
13751 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13752 // Constant shift amount
13753 SmallVector<SDValue, 4> Amt1Csts;
13754 SmallVector<SDValue, 4> Amt2Csts;
13755 for (unsigned i = 0; i != NumElems/2; ++i)
13756 Amt1Csts.push_back(Amt->getOperand(i));
13757 for (unsigned i = NumElems/2; i != NumElems; ++i)
13758 Amt2Csts.push_back(Amt->getOperand(i));
13760 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
13761 &Amt1Csts[0], NumElems/2);
13762 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
13763 &Amt2Csts[0], NumElems/2);
13765 // Variable shift amount
13766 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
13767 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
13770 // Issue new vector shifts for the smaller types
13771 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
13772 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
13774 // Concatenate the result back
13775 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
13781 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
13782 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
13783 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
13784 // looks for this combo and may remove the "setcc" instruction if the "setcc"
13785 // has only one use.
13786 SDNode *N = Op.getNode();
13787 SDValue LHS = N->getOperand(0);
13788 SDValue RHS = N->getOperand(1);
13789 unsigned BaseOp = 0;
13792 switch (Op.getOpcode()) {
13793 default: llvm_unreachable("Unknown ovf instruction!");
13795 // A subtract of one will be selected as a INC. Note that INC doesn't
13796 // set CF, so we can't do this for UADDO.
13797 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13799 BaseOp = X86ISD::INC;
13800 Cond = X86::COND_O;
13803 BaseOp = X86ISD::ADD;
13804 Cond = X86::COND_O;
13807 BaseOp = X86ISD::ADD;
13808 Cond = X86::COND_B;
13811 // A subtract of one will be selected as a DEC. Note that DEC doesn't
13812 // set CF, so we can't do this for USUBO.
13813 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13815 BaseOp = X86ISD::DEC;
13816 Cond = X86::COND_O;
13819 BaseOp = X86ISD::SUB;
13820 Cond = X86::COND_O;
13823 BaseOp = X86ISD::SUB;
13824 Cond = X86::COND_B;
13827 BaseOp = X86ISD::SMUL;
13828 Cond = X86::COND_O;
13830 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
13831 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
13833 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
13836 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13837 DAG.getConstant(X86::COND_O, MVT::i32),
13838 SDValue(Sum.getNode(), 2));
13840 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13844 // Also sets EFLAGS.
13845 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
13846 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
13849 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
13850 DAG.getConstant(Cond, MVT::i32),
13851 SDValue(Sum.getNode(), 1));
13853 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13856 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
13857 SelectionDAG &DAG) const {
13859 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
13860 MVT VT = Op.getSimpleValueType();
13862 if (!Subtarget->hasSSE2() || !VT.isVector())
13865 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
13866 ExtraVT.getScalarType().getSizeInBits();
13868 switch (VT.SimpleTy) {
13869 default: return SDValue();
13872 if (!Subtarget->hasFp256())
13874 if (!Subtarget->hasInt256()) {
13875 // needs to be split
13876 unsigned NumElems = VT.getVectorNumElements();
13878 // Extract the LHS vectors
13879 SDValue LHS = Op.getOperand(0);
13880 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13881 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13883 MVT EltVT = VT.getVectorElementType();
13884 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13886 EVT ExtraEltVT = ExtraVT.getVectorElementType();
13887 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
13888 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
13890 SDValue Extra = DAG.getValueType(ExtraVT);
13892 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
13893 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
13895 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
13900 SDValue Op0 = Op.getOperand(0);
13901 SDValue Op00 = Op0.getOperand(0);
13903 // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
13904 if (Op0.getOpcode() == ISD::BITCAST &&
13905 Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
13906 // (sext (vzext x)) -> (vsext x)
13907 Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
13908 if (Tmp1.getNode()) {
13909 EVT ExtraEltVT = ExtraVT.getVectorElementType();
13910 // This folding is only valid when the in-reg type is a vector of i8,
13912 if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
13913 ExtraEltVT == MVT::i32) {
13914 SDValue Tmp1Op0 = Tmp1.getOperand(0);
13915 assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
13916 "This optimization is invalid without a VZEXT.");
13917 return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
13923 // If the above didn't work, then just use Shift-Left + Shift-Right.
13924 Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
13926 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
13932 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
13933 SelectionDAG &DAG) {
13935 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
13936 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
13937 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
13938 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
13940 // The only fence that needs an instruction is a sequentially-consistent
13941 // cross-thread fence.
13942 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
13943 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
13944 // no-sse2). There isn't any reason to disable it if the target processor
13946 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
13947 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
13949 SDValue Chain = Op.getOperand(0);
13950 SDValue Zero = DAG.getConstant(0, MVT::i32);
13952 DAG.getRegister(X86::ESP, MVT::i32), // Base
13953 DAG.getTargetConstant(1, MVT::i8), // Scale
13954 DAG.getRegister(0, MVT::i32), // Index
13955 DAG.getTargetConstant(0, MVT::i32), // Disp
13956 DAG.getRegister(0, MVT::i32), // Segment.
13960 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
13961 return SDValue(Res, 0);
13964 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
13965 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
13968 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
13969 SelectionDAG &DAG) {
13970 MVT T = Op.getSimpleValueType();
13974 switch(T.SimpleTy) {
13975 default: llvm_unreachable("Invalid value type!");
13976 case MVT::i8: Reg = X86::AL; size = 1; break;
13977 case MVT::i16: Reg = X86::AX; size = 2; break;
13978 case MVT::i32: Reg = X86::EAX; size = 4; break;
13980 assert(Subtarget->is64Bit() && "Node not type legal!");
13981 Reg = X86::RAX; size = 8;
13984 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
13985 Op.getOperand(2), SDValue());
13986 SDValue Ops[] = { cpIn.getValue(0),
13989 DAG.getTargetConstant(size, MVT::i8),
13990 cpIn.getValue(1) };
13991 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13992 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
13993 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
13994 Ops, array_lengthof(Ops), T, MMO);
13996 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
14000 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
14001 SelectionDAG &DAG) {
14002 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
14003 MVT DstVT = Op.getSimpleValueType();
14004 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
14005 Subtarget->hasMMX() && "Unexpected custom BITCAST");
14006 assert((DstVT == MVT::i64 ||
14007 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
14008 "Unexpected custom BITCAST");
14009 // i64 <=> MMX conversions are Legal.
14010 if (SrcVT==MVT::i64 && DstVT.isVector())
14012 if (DstVT==MVT::i64 && SrcVT.isVector())
14014 // MMX <=> MMX conversions are Legal.
14015 if (SrcVT.isVector() && DstVT.isVector())
14017 // All other conversions need to be expanded.
14021 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
14022 SDNode *Node = Op.getNode();
14024 EVT T = Node->getValueType(0);
14025 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
14026 DAG.getConstant(0, T), Node->getOperand(2));
14027 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
14028 cast<AtomicSDNode>(Node)->getMemoryVT(),
14029 Node->getOperand(0),
14030 Node->getOperand(1), negOp,
14031 cast<AtomicSDNode>(Node)->getMemOperand(),
14032 cast<AtomicSDNode>(Node)->getOrdering(),
14033 cast<AtomicSDNode>(Node)->getSynchScope());
14036 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
14037 SDNode *Node = Op.getNode();
14039 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14041 // Convert seq_cst store -> xchg
14042 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
14043 // FIXME: On 32-bit, store -> fist or movq would be more efficient
14044 // (The only way to get a 16-byte store is cmpxchg16b)
14045 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
14046 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
14047 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14048 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
14049 cast<AtomicSDNode>(Node)->getMemoryVT(),
14050 Node->getOperand(0),
14051 Node->getOperand(1), Node->getOperand(2),
14052 cast<AtomicSDNode>(Node)->getMemOperand(),
14053 cast<AtomicSDNode>(Node)->getOrdering(),
14054 cast<AtomicSDNode>(Node)->getSynchScope());
14055 return Swap.getValue(1);
14057 // Other atomic stores have a simple pattern.
14061 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
14062 EVT VT = Op.getNode()->getSimpleValueType(0);
14064 // Let legalize expand this if it isn't a legal type yet.
14065 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14068 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14071 bool ExtraOp = false;
14072 switch (Op.getOpcode()) {
14073 default: llvm_unreachable("Invalid code");
14074 case ISD::ADDC: Opc = X86ISD::ADD; break;
14075 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
14076 case ISD::SUBC: Opc = X86ISD::SUB; break;
14077 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
14081 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14083 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14084 Op.getOperand(1), Op.getOperand(2));
14087 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
14088 SelectionDAG &DAG) {
14089 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
14091 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
14092 // which returns the values as { float, float } (in XMM0) or
14093 // { double, double } (which is returned in XMM0, XMM1).
14095 SDValue Arg = Op.getOperand(0);
14096 EVT ArgVT = Arg.getValueType();
14097 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14099 TargetLowering::ArgListTy Args;
14100 TargetLowering::ArgListEntry Entry;
14104 Entry.isSExt = false;
14105 Entry.isZExt = false;
14106 Args.push_back(Entry);
14108 bool isF64 = ArgVT == MVT::f64;
14109 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
14110 // the small struct {f32, f32} is returned in (eax, edx). For f64,
14111 // the results are returned via SRet in memory.
14112 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
14113 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14114 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
14116 Type *RetTy = isF64
14117 ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
14118 : (Type*)VectorType::get(ArgTy, 4);
14120 CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
14121 false, false, false, false, 0,
14122 CallingConv::C, /*isTaillCall=*/false,
14123 /*doesNotRet=*/false, /*isReturnValueUsed*/true,
14124 Callee, Args, DAG, dl);
14125 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
14128 // Returned in xmm0 and xmm1.
14129 return CallResult.first;
14131 // Returned in bits 0:31 and 32:64 xmm0.
14132 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14133 CallResult.first, DAG.getIntPtrConstant(0));
14134 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14135 CallResult.first, DAG.getIntPtrConstant(1));
14136 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
14137 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
14140 /// LowerOperation - Provide custom lowering hooks for some operations.
14142 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
14143 switch (Op.getOpcode()) {
14144 default: llvm_unreachable("Should not custom lower this!");
14145 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
14146 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
14147 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op, Subtarget, DAG);
14148 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
14149 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
14150 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
14151 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
14152 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
14153 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
14154 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
14155 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
14156 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
14157 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
14158 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
14159 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
14160 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
14161 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
14162 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
14163 case ISD::SHL_PARTS:
14164 case ISD::SRA_PARTS:
14165 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
14166 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
14167 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
14168 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
14169 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
14170 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
14171 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
14172 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
14173 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
14174 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
14175 case ISD::FABS: return LowerFABS(Op, DAG);
14176 case ISD::FNEG: return LowerFNEG(Op, DAG);
14177 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
14178 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
14179 case ISD::SETCC: return LowerSETCC(Op, DAG);
14180 case ISD::SELECT: return LowerSELECT(Op, DAG);
14181 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
14182 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
14183 case ISD::VASTART: return LowerVASTART(Op, DAG);
14184 case ISD::VAARG: return LowerVAARG(Op, DAG);
14185 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
14186 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
14187 case ISD::INTRINSIC_VOID:
14188 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
14189 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
14190 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
14191 case ISD::FRAME_TO_ARGS_OFFSET:
14192 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
14193 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
14194 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
14195 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
14196 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
14197 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
14198 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
14199 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
14200 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
14201 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
14202 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
14203 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
14206 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
14212 case ISD::UMULO: return LowerXALUO(Op, DAG);
14213 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
14214 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
14218 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
14219 case ISD::ADD: return LowerADD(Op, DAG);
14220 case ISD::SUB: return LowerSUB(Op, DAG);
14221 case ISD::SDIV: return LowerSDIV(Op, DAG);
14222 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
14226 static void ReplaceATOMIC_LOAD(SDNode *Node,
14227 SmallVectorImpl<SDValue> &Results,
14228 SelectionDAG &DAG) {
14230 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14232 // Convert wide load -> cmpxchg8b/cmpxchg16b
14233 // FIXME: On 32-bit, load -> fild or movq would be more efficient
14234 // (The only way to get a 16-byte load is cmpxchg16b)
14235 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
14236 SDValue Zero = DAG.getConstant(0, VT);
14237 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
14238 Node->getOperand(0),
14239 Node->getOperand(1), Zero, Zero,
14240 cast<AtomicSDNode>(Node)->getMemOperand(),
14241 cast<AtomicSDNode>(Node)->getOrdering(),
14242 cast<AtomicSDNode>(Node)->getOrdering(),
14243 cast<AtomicSDNode>(Node)->getSynchScope());
14244 Results.push_back(Swap.getValue(0));
14245 Results.push_back(Swap.getValue(1));
14249 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
14250 SelectionDAG &DAG, unsigned NewOp) {
14252 assert (Node->getValueType(0) == MVT::i64 &&
14253 "Only know how to expand i64 atomics");
14255 SDValue Chain = Node->getOperand(0);
14256 SDValue In1 = Node->getOperand(1);
14257 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14258 Node->getOperand(2), DAG.getIntPtrConstant(0));
14259 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14260 Node->getOperand(2), DAG.getIntPtrConstant(1));
14261 SDValue Ops[] = { Chain, In1, In2L, In2H };
14262 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
14264 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, array_lengthof(Ops), MVT::i64,
14265 cast<MemSDNode>(Node)->getMemOperand());
14266 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
14267 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
14268 Results.push_back(Result.getValue(2));
14271 /// ReplaceNodeResults - Replace a node with an illegal result type
14272 /// with a new node built out of custom code.
14273 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
14274 SmallVectorImpl<SDValue>&Results,
14275 SelectionDAG &DAG) const {
14277 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14278 switch (N->getOpcode()) {
14280 llvm_unreachable("Do not know how to custom type legalize this operation!");
14281 case ISD::SIGN_EXTEND_INREG:
14286 // We don't want to expand or promote these.
14288 case ISD::FP_TO_SINT:
14289 case ISD::FP_TO_UINT: {
14290 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
14292 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
14295 std::pair<SDValue,SDValue> Vals =
14296 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
14297 SDValue FIST = Vals.first, StackSlot = Vals.second;
14298 if (FIST.getNode()) {
14299 EVT VT = N->getValueType(0);
14300 // Return a load from the stack slot.
14301 if (StackSlot.getNode())
14302 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
14303 MachinePointerInfo(),
14304 false, false, false, 0));
14306 Results.push_back(FIST);
14310 case ISD::UINT_TO_FP: {
14311 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14312 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
14313 N->getValueType(0) != MVT::v2f32)
14315 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
14317 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
14319 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
14320 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
14321 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
14322 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
14323 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
14324 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
14327 case ISD::FP_ROUND: {
14328 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
14330 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
14331 Results.push_back(V);
14334 case ISD::INTRINSIC_W_CHAIN: {
14335 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
14337 default : llvm_unreachable("Do not know how to custom type "
14338 "legalize this intrinsic operation!");
14339 case Intrinsic::x86_rdtsc:
14340 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14342 case Intrinsic::x86_rdtscp:
14343 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
14347 case ISD::READCYCLECOUNTER: {
14348 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14351 case ISD::ATOMIC_CMP_SWAP: {
14352 EVT T = N->getValueType(0);
14353 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
14354 bool Regs64bit = T == MVT::i128;
14355 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
14356 SDValue cpInL, cpInH;
14357 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14358 DAG.getConstant(0, HalfT));
14359 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14360 DAG.getConstant(1, HalfT));
14361 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
14362 Regs64bit ? X86::RAX : X86::EAX,
14364 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
14365 Regs64bit ? X86::RDX : X86::EDX,
14366 cpInH, cpInL.getValue(1));
14367 SDValue swapInL, swapInH;
14368 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14369 DAG.getConstant(0, HalfT));
14370 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14371 DAG.getConstant(1, HalfT));
14372 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
14373 Regs64bit ? X86::RBX : X86::EBX,
14374 swapInL, cpInH.getValue(1));
14375 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
14376 Regs64bit ? X86::RCX : X86::ECX,
14377 swapInH, swapInL.getValue(1));
14378 SDValue Ops[] = { swapInH.getValue(0),
14380 swapInH.getValue(1) };
14381 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14382 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
14383 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
14384 X86ISD::LCMPXCHG8_DAG;
14385 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
14386 Ops, array_lengthof(Ops), T, MMO);
14387 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
14388 Regs64bit ? X86::RAX : X86::EAX,
14389 HalfT, Result.getValue(1));
14390 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
14391 Regs64bit ? X86::RDX : X86::EDX,
14392 HalfT, cpOutL.getValue(2));
14393 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
14394 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
14395 Results.push_back(cpOutH.getValue(1));
14398 case ISD::ATOMIC_LOAD_ADD:
14399 case ISD::ATOMIC_LOAD_AND:
14400 case ISD::ATOMIC_LOAD_NAND:
14401 case ISD::ATOMIC_LOAD_OR:
14402 case ISD::ATOMIC_LOAD_SUB:
14403 case ISD::ATOMIC_LOAD_XOR:
14404 case ISD::ATOMIC_LOAD_MAX:
14405 case ISD::ATOMIC_LOAD_MIN:
14406 case ISD::ATOMIC_LOAD_UMAX:
14407 case ISD::ATOMIC_LOAD_UMIN:
14408 case ISD::ATOMIC_SWAP: {
14410 switch (N->getOpcode()) {
14411 default: llvm_unreachable("Unexpected opcode");
14412 case ISD::ATOMIC_LOAD_ADD:
14413 Opc = X86ISD::ATOMADD64_DAG;
14415 case ISD::ATOMIC_LOAD_AND:
14416 Opc = X86ISD::ATOMAND64_DAG;
14418 case ISD::ATOMIC_LOAD_NAND:
14419 Opc = X86ISD::ATOMNAND64_DAG;
14421 case ISD::ATOMIC_LOAD_OR:
14422 Opc = X86ISD::ATOMOR64_DAG;
14424 case ISD::ATOMIC_LOAD_SUB:
14425 Opc = X86ISD::ATOMSUB64_DAG;
14427 case ISD::ATOMIC_LOAD_XOR:
14428 Opc = X86ISD::ATOMXOR64_DAG;
14430 case ISD::ATOMIC_LOAD_MAX:
14431 Opc = X86ISD::ATOMMAX64_DAG;
14433 case ISD::ATOMIC_LOAD_MIN:
14434 Opc = X86ISD::ATOMMIN64_DAG;
14436 case ISD::ATOMIC_LOAD_UMAX:
14437 Opc = X86ISD::ATOMUMAX64_DAG;
14439 case ISD::ATOMIC_LOAD_UMIN:
14440 Opc = X86ISD::ATOMUMIN64_DAG;
14442 case ISD::ATOMIC_SWAP:
14443 Opc = X86ISD::ATOMSWAP64_DAG;
14446 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
14449 case ISD::ATOMIC_LOAD:
14450 ReplaceATOMIC_LOAD(N, Results, DAG);
14454 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
14456 default: return nullptr;
14457 case X86ISD::BSF: return "X86ISD::BSF";
14458 case X86ISD::BSR: return "X86ISD::BSR";
14459 case X86ISD::SHLD: return "X86ISD::SHLD";
14460 case X86ISD::SHRD: return "X86ISD::SHRD";
14461 case X86ISD::FAND: return "X86ISD::FAND";
14462 case X86ISD::FANDN: return "X86ISD::FANDN";
14463 case X86ISD::FOR: return "X86ISD::FOR";
14464 case X86ISD::FXOR: return "X86ISD::FXOR";
14465 case X86ISD::FSRL: return "X86ISD::FSRL";
14466 case X86ISD::FILD: return "X86ISD::FILD";
14467 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
14468 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
14469 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
14470 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
14471 case X86ISD::FLD: return "X86ISD::FLD";
14472 case X86ISD::FST: return "X86ISD::FST";
14473 case X86ISD::CALL: return "X86ISD::CALL";
14474 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
14475 case X86ISD::BT: return "X86ISD::BT";
14476 case X86ISD::CMP: return "X86ISD::CMP";
14477 case X86ISD::COMI: return "X86ISD::COMI";
14478 case X86ISD::UCOMI: return "X86ISD::UCOMI";
14479 case X86ISD::CMPM: return "X86ISD::CMPM";
14480 case X86ISD::CMPMU: return "X86ISD::CMPMU";
14481 case X86ISD::SETCC: return "X86ISD::SETCC";
14482 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
14483 case X86ISD::FSETCC: return "X86ISD::FSETCC";
14484 case X86ISD::CMOV: return "X86ISD::CMOV";
14485 case X86ISD::BRCOND: return "X86ISD::BRCOND";
14486 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
14487 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
14488 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
14489 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
14490 case X86ISD::Wrapper: return "X86ISD::Wrapper";
14491 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
14492 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
14493 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
14494 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
14495 case X86ISD::PINSRB: return "X86ISD::PINSRB";
14496 case X86ISD::PINSRW: return "X86ISD::PINSRW";
14497 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
14498 case X86ISD::ANDNP: return "X86ISD::ANDNP";
14499 case X86ISD::PSIGN: return "X86ISD::PSIGN";
14500 case X86ISD::BLENDV: return "X86ISD::BLENDV";
14501 case X86ISD::BLENDI: return "X86ISD::BLENDI";
14502 case X86ISD::SUBUS: return "X86ISD::SUBUS";
14503 case X86ISD::HADD: return "X86ISD::HADD";
14504 case X86ISD::HSUB: return "X86ISD::HSUB";
14505 case X86ISD::FHADD: return "X86ISD::FHADD";
14506 case X86ISD::FHSUB: return "X86ISD::FHSUB";
14507 case X86ISD::UMAX: return "X86ISD::UMAX";
14508 case X86ISD::UMIN: return "X86ISD::UMIN";
14509 case X86ISD::SMAX: return "X86ISD::SMAX";
14510 case X86ISD::SMIN: return "X86ISD::SMIN";
14511 case X86ISD::FMAX: return "X86ISD::FMAX";
14512 case X86ISD::FMIN: return "X86ISD::FMIN";
14513 case X86ISD::FMAXC: return "X86ISD::FMAXC";
14514 case X86ISD::FMINC: return "X86ISD::FMINC";
14515 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
14516 case X86ISD::FRCP: return "X86ISD::FRCP";
14517 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
14518 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
14519 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
14520 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
14521 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
14522 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
14523 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
14524 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
14525 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
14526 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
14527 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
14528 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
14529 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
14530 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
14531 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
14532 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
14533 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
14534 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
14535 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
14536 case X86ISD::VZEXT: return "X86ISD::VZEXT";
14537 case X86ISD::VSEXT: return "X86ISD::VSEXT";
14538 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
14539 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
14540 case X86ISD::VINSERT: return "X86ISD::VINSERT";
14541 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
14542 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
14543 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
14544 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
14545 case X86ISD::VSHL: return "X86ISD::VSHL";
14546 case X86ISD::VSRL: return "X86ISD::VSRL";
14547 case X86ISD::VSRA: return "X86ISD::VSRA";
14548 case X86ISD::VSHLI: return "X86ISD::VSHLI";
14549 case X86ISD::VSRLI: return "X86ISD::VSRLI";
14550 case X86ISD::VSRAI: return "X86ISD::VSRAI";
14551 case X86ISD::CMPP: return "X86ISD::CMPP";
14552 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
14553 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
14554 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
14555 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
14556 case X86ISD::ADD: return "X86ISD::ADD";
14557 case X86ISD::SUB: return "X86ISD::SUB";
14558 case X86ISD::ADC: return "X86ISD::ADC";
14559 case X86ISD::SBB: return "X86ISD::SBB";
14560 case X86ISD::SMUL: return "X86ISD::SMUL";
14561 case X86ISD::UMUL: return "X86ISD::UMUL";
14562 case X86ISD::INC: return "X86ISD::INC";
14563 case X86ISD::DEC: return "X86ISD::DEC";
14564 case X86ISD::OR: return "X86ISD::OR";
14565 case X86ISD::XOR: return "X86ISD::XOR";
14566 case X86ISD::AND: return "X86ISD::AND";
14567 case X86ISD::BEXTR: return "X86ISD::BEXTR";
14568 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
14569 case X86ISD::PTEST: return "X86ISD::PTEST";
14570 case X86ISD::TESTP: return "X86ISD::TESTP";
14571 case X86ISD::TESTM: return "X86ISD::TESTM";
14572 case X86ISD::TESTNM: return "X86ISD::TESTNM";
14573 case X86ISD::KORTEST: return "X86ISD::KORTEST";
14574 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
14575 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
14576 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
14577 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
14578 case X86ISD::SHUFP: return "X86ISD::SHUFP";
14579 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
14580 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
14581 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
14582 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
14583 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
14584 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
14585 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
14586 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
14587 case X86ISD::MOVSD: return "X86ISD::MOVSD";
14588 case X86ISD::MOVSS: return "X86ISD::MOVSS";
14589 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
14590 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
14591 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
14592 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
14593 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
14594 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
14595 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
14596 case X86ISD::VPERMV: return "X86ISD::VPERMV";
14597 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
14598 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
14599 case X86ISD::VPERMI: return "X86ISD::VPERMI";
14600 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
14601 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
14602 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
14603 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
14604 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
14605 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
14606 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
14607 case X86ISD::SAHF: return "X86ISD::SAHF";
14608 case X86ISD::RDRAND: return "X86ISD::RDRAND";
14609 case X86ISD::RDSEED: return "X86ISD::RDSEED";
14610 case X86ISD::FMADD: return "X86ISD::FMADD";
14611 case X86ISD::FMSUB: return "X86ISD::FMSUB";
14612 case X86ISD::FNMADD: return "X86ISD::FNMADD";
14613 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
14614 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
14615 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
14616 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
14617 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
14618 case X86ISD::XTEST: return "X86ISD::XTEST";
14622 // isLegalAddressingMode - Return true if the addressing mode represented
14623 // by AM is legal for this target, for a load/store of the specified type.
14624 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
14626 // X86 supports extremely general addressing modes.
14627 CodeModel::Model M = getTargetMachine().getCodeModel();
14628 Reloc::Model R = getTargetMachine().getRelocationModel();
14630 // X86 allows a sign-extended 32-bit immediate field as a displacement.
14631 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
14636 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
14638 // If a reference to this global requires an extra load, we can't fold it.
14639 if (isGlobalStubReference(GVFlags))
14642 // If BaseGV requires a register for the PIC base, we cannot also have a
14643 // BaseReg specified.
14644 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
14647 // If lower 4G is not available, then we must use rip-relative addressing.
14648 if ((M != CodeModel::Small || R != Reloc::Static) &&
14649 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
14653 switch (AM.Scale) {
14659 // These scales always work.
14664 // These scales are formed with basereg+scalereg. Only accept if there is
14669 default: // Other stuff never works.
14676 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
14677 unsigned Bits = Ty->getScalarSizeInBits();
14679 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
14680 // particularly cheaper than those without.
14684 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
14685 // variable shifts just as cheap as scalar ones.
14686 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
14689 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
14690 // fully general vector.
14694 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
14695 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14697 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
14698 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
14699 return NumBits1 > NumBits2;
14702 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
14703 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14706 if (!isTypeLegal(EVT::getEVT(Ty1)))
14709 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
14711 // Assuming the caller doesn't have a zeroext or signext return parameter,
14712 // truncation all the way down to i1 is valid.
14716 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
14717 return isInt<32>(Imm);
14720 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
14721 // Can also use sub to handle negated immediates.
14722 return isInt<32>(Imm);
14725 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
14726 if (!VT1.isInteger() || !VT2.isInteger())
14728 unsigned NumBits1 = VT1.getSizeInBits();
14729 unsigned NumBits2 = VT2.getSizeInBits();
14730 return NumBits1 > NumBits2;
14733 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
14734 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14735 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
14738 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
14739 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14740 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
14743 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14744 EVT VT1 = Val.getValueType();
14745 if (isZExtFree(VT1, VT2))
14748 if (Val.getOpcode() != ISD::LOAD)
14751 if (!VT1.isSimple() || !VT1.isInteger() ||
14752 !VT2.isSimple() || !VT2.isInteger())
14755 switch (VT1.getSimpleVT().SimpleTy) {
14760 // X86 has 8, 16, and 32-bit zero-extending loads.
14768 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
14769 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
14772 VT = VT.getScalarType();
14774 if (!VT.isSimple())
14777 switch (VT.getSimpleVT().SimpleTy) {
14788 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
14789 // i16 instructions are longer (0x66 prefix) and potentially slower.
14790 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
14793 /// isShuffleMaskLegal - Targets can use this to indicate that they only
14794 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
14795 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
14796 /// are assumed to be legal.
14798 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
14800 if (!VT.isSimple())
14803 MVT SVT = VT.getSimpleVT();
14805 // Very little shuffling can be done for 64-bit vectors right now.
14806 if (VT.getSizeInBits() == 64)
14809 // FIXME: pshufb, blends, shifts.
14810 return (SVT.getVectorNumElements() == 2 ||
14811 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
14812 isMOVLMask(M, SVT) ||
14813 isSHUFPMask(M, SVT) ||
14814 isPSHUFDMask(M, SVT) ||
14815 isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
14816 isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
14817 isPALIGNRMask(M, SVT, Subtarget) ||
14818 isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
14819 isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
14820 isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
14821 isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()));
14825 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
14827 if (!VT.isSimple())
14830 MVT SVT = VT.getSimpleVT();
14831 unsigned NumElts = SVT.getVectorNumElements();
14832 // FIXME: This collection of masks seems suspect.
14835 if (NumElts == 4 && SVT.is128BitVector()) {
14836 return (isMOVLMask(Mask, SVT) ||
14837 isCommutedMOVLMask(Mask, SVT, true) ||
14838 isSHUFPMask(Mask, SVT) ||
14839 isSHUFPMask(Mask, SVT, /* Commuted */ true));
14844 //===----------------------------------------------------------------------===//
14845 // X86 Scheduler Hooks
14846 //===----------------------------------------------------------------------===//
14848 /// Utility function to emit xbegin specifying the start of an RTM region.
14849 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
14850 const TargetInstrInfo *TII) {
14851 DebugLoc DL = MI->getDebugLoc();
14853 const BasicBlock *BB = MBB->getBasicBlock();
14854 MachineFunction::iterator I = MBB;
14857 // For the v = xbegin(), we generate
14868 MachineBasicBlock *thisMBB = MBB;
14869 MachineFunction *MF = MBB->getParent();
14870 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14871 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14872 MF->insert(I, mainMBB);
14873 MF->insert(I, sinkMBB);
14875 // Transfer the remainder of BB and its successor edges to sinkMBB.
14876 sinkMBB->splice(sinkMBB->begin(), MBB,
14877 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
14878 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14882 // # fallthrough to mainMBB
14883 // # abortion to sinkMBB
14884 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
14885 thisMBB->addSuccessor(mainMBB);
14886 thisMBB->addSuccessor(sinkMBB);
14890 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
14891 mainMBB->addSuccessor(sinkMBB);
14894 // EAX is live into the sinkMBB
14895 sinkMBB->addLiveIn(X86::EAX);
14896 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14897 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14900 MI->eraseFromParent();
14904 // Get CMPXCHG opcode for the specified data type.
14905 static unsigned getCmpXChgOpcode(EVT VT) {
14906 switch (VT.getSimpleVT().SimpleTy) {
14907 case MVT::i8: return X86::LCMPXCHG8;
14908 case MVT::i16: return X86::LCMPXCHG16;
14909 case MVT::i32: return X86::LCMPXCHG32;
14910 case MVT::i64: return X86::LCMPXCHG64;
14914 llvm_unreachable("Invalid operand size!");
14917 // Get LOAD opcode for the specified data type.
14918 static unsigned getLoadOpcode(EVT VT) {
14919 switch (VT.getSimpleVT().SimpleTy) {
14920 case MVT::i8: return X86::MOV8rm;
14921 case MVT::i16: return X86::MOV16rm;
14922 case MVT::i32: return X86::MOV32rm;
14923 case MVT::i64: return X86::MOV64rm;
14927 llvm_unreachable("Invalid operand size!");
14930 // Get opcode of the non-atomic one from the specified atomic instruction.
14931 static unsigned getNonAtomicOpcode(unsigned Opc) {
14933 case X86::ATOMAND8: return X86::AND8rr;
14934 case X86::ATOMAND16: return X86::AND16rr;
14935 case X86::ATOMAND32: return X86::AND32rr;
14936 case X86::ATOMAND64: return X86::AND64rr;
14937 case X86::ATOMOR8: return X86::OR8rr;
14938 case X86::ATOMOR16: return X86::OR16rr;
14939 case X86::ATOMOR32: return X86::OR32rr;
14940 case X86::ATOMOR64: return X86::OR64rr;
14941 case X86::ATOMXOR8: return X86::XOR8rr;
14942 case X86::ATOMXOR16: return X86::XOR16rr;
14943 case X86::ATOMXOR32: return X86::XOR32rr;
14944 case X86::ATOMXOR64: return X86::XOR64rr;
14946 llvm_unreachable("Unhandled atomic-load-op opcode!");
14949 // Get opcode of the non-atomic one from the specified atomic instruction with
14951 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
14952 unsigned &ExtraOpc) {
14954 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr;
14955 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr;
14956 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr;
14957 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr;
14958 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr;
14959 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
14960 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
14961 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
14962 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr;
14963 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
14964 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
14965 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
14966 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr;
14967 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
14968 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
14969 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
14970 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr;
14971 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
14972 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
14973 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
14975 llvm_unreachable("Unhandled atomic-load-op opcode!");
14978 // Get opcode of the non-atomic one from the specified atomic instruction for
14979 // 64-bit data type on 32-bit target.
14980 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
14982 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr;
14983 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr;
14984 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr;
14985 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr;
14986 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr;
14987 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
14988 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr;
14989 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr;
14990 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr;
14991 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr;
14993 llvm_unreachable("Unhandled atomic-load-op opcode!");
14996 // Get opcode of the non-atomic one from the specified atomic instruction for
14997 // 64-bit data type on 32-bit target with extra opcode.
14998 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
15000 unsigned &ExtraOpc) {
15002 case X86::ATOMNAND6432:
15003 ExtraOpc = X86::NOT32r;
15004 HiOpc = X86::AND32rr;
15005 return X86::AND32rr;
15007 llvm_unreachable("Unhandled atomic-load-op opcode!");
15010 // Get pseudo CMOV opcode from the specified data type.
15011 static unsigned getPseudoCMOVOpc(EVT VT) {
15012 switch (VT.getSimpleVT().SimpleTy) {
15013 case MVT::i8: return X86::CMOV_GR8;
15014 case MVT::i16: return X86::CMOV_GR16;
15015 case MVT::i32: return X86::CMOV_GR32;
15019 llvm_unreachable("Unknown CMOV opcode!");
15022 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
15023 // They will be translated into a spin-loop or compare-exchange loop from
15026 // dst = atomic-fetch-op MI.addr, MI.val
15032 // t1 = LOAD MI.addr
15034 // t4 = phi(t1, t3 / loop)
15035 // t2 = OP MI.val, t4
15037 // LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
15043 MachineBasicBlock *
15044 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
15045 MachineBasicBlock *MBB) const {
15046 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15047 DebugLoc DL = MI->getDebugLoc();
15049 MachineFunction *MF = MBB->getParent();
15050 MachineRegisterInfo &MRI = MF->getRegInfo();
15052 const BasicBlock *BB = MBB->getBasicBlock();
15053 MachineFunction::iterator I = MBB;
15056 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
15057 "Unexpected number of operands");
15059 assert(MI->hasOneMemOperand() &&
15060 "Expected atomic-load-op to have one memoperand");
15062 // Memory Reference
15063 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15064 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15066 unsigned DstReg, SrcReg;
15067 unsigned MemOpndSlot;
15069 unsigned CurOp = 0;
15071 DstReg = MI->getOperand(CurOp++).getReg();
15072 MemOpndSlot = CurOp;
15073 CurOp += X86::AddrNumOperands;
15074 SrcReg = MI->getOperand(CurOp++).getReg();
15076 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15077 MVT::SimpleValueType VT = *RC->vt_begin();
15078 unsigned t1 = MRI.createVirtualRegister(RC);
15079 unsigned t2 = MRI.createVirtualRegister(RC);
15080 unsigned t3 = MRI.createVirtualRegister(RC);
15081 unsigned t4 = MRI.createVirtualRegister(RC);
15082 unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
15084 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
15085 unsigned LOADOpc = getLoadOpcode(VT);
15087 // For the atomic load-arith operator, we generate
15090 // t1 = LOAD [MI.addr]
15092 // t4 = phi(t1 / thisMBB, t3 / mainMBB)
15093 // t1 = OP MI.val, EAX
15095 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
15101 MachineBasicBlock *thisMBB = MBB;
15102 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15103 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15104 MF->insert(I, mainMBB);
15105 MF->insert(I, sinkMBB);
15107 MachineInstrBuilder MIB;
15109 // Transfer the remainder of BB and its successor edges to sinkMBB.
15110 sinkMBB->splice(sinkMBB->begin(), MBB,
15111 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15112 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15115 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
15116 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15117 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15119 NewMO.setIsKill(false);
15120 MIB.addOperand(NewMO);
15122 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15123 unsigned flags = (*MMOI)->getFlags();
15124 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15125 MachineMemOperand *MMO =
15126 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15127 (*MMOI)->getSize(),
15128 (*MMOI)->getBaseAlignment(),
15129 (*MMOI)->getTBAAInfo(),
15130 (*MMOI)->getRanges());
15131 MIB.addMemOperand(MMO);
15134 thisMBB->addSuccessor(mainMBB);
15137 MachineBasicBlock *origMainMBB = mainMBB;
15140 MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
15141 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15143 unsigned Opc = MI->getOpcode();
15146 llvm_unreachable("Unhandled atomic-load-op opcode!");
15147 case X86::ATOMAND8:
15148 case X86::ATOMAND16:
15149 case X86::ATOMAND32:
15150 case X86::ATOMAND64:
15152 case X86::ATOMOR16:
15153 case X86::ATOMOR32:
15154 case X86::ATOMOR64:
15155 case X86::ATOMXOR8:
15156 case X86::ATOMXOR16:
15157 case X86::ATOMXOR32:
15158 case X86::ATOMXOR64: {
15159 unsigned ARITHOpc = getNonAtomicOpcode(Opc);
15160 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
15164 case X86::ATOMNAND8:
15165 case X86::ATOMNAND16:
15166 case X86::ATOMNAND32:
15167 case X86::ATOMNAND64: {
15168 unsigned Tmp = MRI.createVirtualRegister(RC);
15170 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
15171 BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
15173 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
15176 case X86::ATOMMAX8:
15177 case X86::ATOMMAX16:
15178 case X86::ATOMMAX32:
15179 case X86::ATOMMAX64:
15180 case X86::ATOMMIN8:
15181 case X86::ATOMMIN16:
15182 case X86::ATOMMIN32:
15183 case X86::ATOMMIN64:
15184 case X86::ATOMUMAX8:
15185 case X86::ATOMUMAX16:
15186 case X86::ATOMUMAX32:
15187 case X86::ATOMUMAX64:
15188 case X86::ATOMUMIN8:
15189 case X86::ATOMUMIN16:
15190 case X86::ATOMUMIN32:
15191 case X86::ATOMUMIN64: {
15193 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
15195 BuildMI(mainMBB, DL, TII->get(CMPOpc))
15199 if (Subtarget->hasCMov()) {
15200 if (VT != MVT::i8) {
15202 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
15206 // Promote i8 to i32 to use CMOV32
15207 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15208 const TargetRegisterClass *RC32 =
15209 TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
15210 unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
15211 unsigned AccReg32 = MRI.createVirtualRegister(RC32);
15212 unsigned Tmp = MRI.createVirtualRegister(RC32);
15214 unsigned Undef = MRI.createVirtualRegister(RC32);
15215 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
15217 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
15220 .addImm(X86::sub_8bit);
15221 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
15224 .addImm(X86::sub_8bit);
15226 BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
15230 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
15231 .addReg(Tmp, 0, X86::sub_8bit);
15234 // Use pseudo select and lower them.
15235 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
15236 "Invalid atomic-load-op transformation!");
15237 unsigned SelOpc = getPseudoCMOVOpc(VT);
15238 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
15239 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
15240 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
15241 .addReg(SrcReg).addReg(t4)
15243 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15244 // Replace the original PHI node as mainMBB is changed after CMOV
15246 BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
15247 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15248 Phi->eraseFromParent();
15254 // Copy PhyReg back from virtual register.
15255 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
15258 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15259 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15260 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15262 NewMO.setIsKill(false);
15263 MIB.addOperand(NewMO);
15266 MIB.setMemRefs(MMOBegin, MMOEnd);
15268 // Copy PhyReg back to virtual register.
15269 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
15272 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15274 mainMBB->addSuccessor(origMainMBB);
15275 mainMBB->addSuccessor(sinkMBB);
15278 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15279 TII->get(TargetOpcode::COPY), DstReg)
15282 MI->eraseFromParent();
15286 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
15287 // instructions. They will be translated into a spin-loop or compare-exchange
15291 // dst = atomic-fetch-op MI.addr, MI.val
15297 // t1L = LOAD [MI.addr + 0]
15298 // t1H = LOAD [MI.addr + 4]
15300 // t4L = phi(t1L, t3L / loop)
15301 // t4H = phi(t1H, t3H / loop)
15302 // t2L = OP MI.val.lo, t4L
15303 // t2H = OP MI.val.hi, t4H
15308 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15316 MachineBasicBlock *
15317 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
15318 MachineBasicBlock *MBB) const {
15319 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15320 DebugLoc DL = MI->getDebugLoc();
15322 MachineFunction *MF = MBB->getParent();
15323 MachineRegisterInfo &MRI = MF->getRegInfo();
15325 const BasicBlock *BB = MBB->getBasicBlock();
15326 MachineFunction::iterator I = MBB;
15329 assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
15330 "Unexpected number of operands");
15332 assert(MI->hasOneMemOperand() &&
15333 "Expected atomic-load-op32 to have one memoperand");
15335 // Memory Reference
15336 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15337 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15339 unsigned DstLoReg, DstHiReg;
15340 unsigned SrcLoReg, SrcHiReg;
15341 unsigned MemOpndSlot;
15343 unsigned CurOp = 0;
15345 DstLoReg = MI->getOperand(CurOp++).getReg();
15346 DstHiReg = MI->getOperand(CurOp++).getReg();
15347 MemOpndSlot = CurOp;
15348 CurOp += X86::AddrNumOperands;
15349 SrcLoReg = MI->getOperand(CurOp++).getReg();
15350 SrcHiReg = MI->getOperand(CurOp++).getReg();
15352 const TargetRegisterClass *RC = &X86::GR32RegClass;
15353 const TargetRegisterClass *RC8 = &X86::GR8RegClass;
15355 unsigned t1L = MRI.createVirtualRegister(RC);
15356 unsigned t1H = MRI.createVirtualRegister(RC);
15357 unsigned t2L = MRI.createVirtualRegister(RC);
15358 unsigned t2H = MRI.createVirtualRegister(RC);
15359 unsigned t3L = MRI.createVirtualRegister(RC);
15360 unsigned t3H = MRI.createVirtualRegister(RC);
15361 unsigned t4L = MRI.createVirtualRegister(RC);
15362 unsigned t4H = MRI.createVirtualRegister(RC);
15364 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
15365 unsigned LOADOpc = X86::MOV32rm;
15367 // For the atomic load-arith operator, we generate
15370 // t1L = LOAD [MI.addr + 0]
15371 // t1H = LOAD [MI.addr + 4]
15373 // t4L = phi(t1L / thisMBB, t3L / mainMBB)
15374 // t4H = phi(t1H / thisMBB, t3H / mainMBB)
15375 // t2L = OP MI.val.lo, t4L
15376 // t2H = OP MI.val.hi, t4H
15379 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15387 MachineBasicBlock *thisMBB = MBB;
15388 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15389 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15390 MF->insert(I, mainMBB);
15391 MF->insert(I, sinkMBB);
15393 MachineInstrBuilder MIB;
15395 // Transfer the remainder of BB and its successor edges to sinkMBB.
15396 sinkMBB->splice(sinkMBB->begin(), MBB,
15397 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15398 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15402 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
15403 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15404 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15406 NewMO.setIsKill(false);
15407 MIB.addOperand(NewMO);
15409 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15410 unsigned flags = (*MMOI)->getFlags();
15411 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15412 MachineMemOperand *MMO =
15413 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15414 (*MMOI)->getSize(),
15415 (*MMOI)->getBaseAlignment(),
15416 (*MMOI)->getTBAAInfo(),
15417 (*MMOI)->getRanges());
15418 MIB.addMemOperand(MMO);
15420 MachineInstr *LowMI = MIB;
15423 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
15424 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15425 if (i == X86::AddrDisp) {
15426 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
15428 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15430 NewMO.setIsKill(false);
15431 MIB.addOperand(NewMO);
15434 MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
15436 thisMBB->addSuccessor(mainMBB);
15439 MachineBasicBlock *origMainMBB = mainMBB;
15442 MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
15443 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15444 MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
15445 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15447 unsigned Opc = MI->getOpcode();
15450 llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
15451 case X86::ATOMAND6432:
15452 case X86::ATOMOR6432:
15453 case X86::ATOMXOR6432:
15454 case X86::ATOMADD6432:
15455 case X86::ATOMSUB6432: {
15457 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15458 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
15460 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
15464 case X86::ATOMNAND6432: {
15465 unsigned HiOpc, NOTOpc;
15466 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
15467 unsigned TmpL = MRI.createVirtualRegister(RC);
15468 unsigned TmpH = MRI.createVirtualRegister(RC);
15469 BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
15471 BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
15473 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
15474 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
15477 case X86::ATOMMAX6432:
15478 case X86::ATOMMIN6432:
15479 case X86::ATOMUMAX6432:
15480 case X86::ATOMUMIN6432: {
15482 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15483 unsigned cL = MRI.createVirtualRegister(RC8);
15484 unsigned cH = MRI.createVirtualRegister(RC8);
15485 unsigned cL32 = MRI.createVirtualRegister(RC);
15486 unsigned cH32 = MRI.createVirtualRegister(RC);
15487 unsigned cc = MRI.createVirtualRegister(RC);
15488 // cl := cmp src_lo, lo
15489 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15490 .addReg(SrcLoReg).addReg(t4L);
15491 BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
15492 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
15493 // ch := cmp src_hi, hi
15494 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15495 .addReg(SrcHiReg).addReg(t4H);
15496 BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
15497 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
15498 // cc := if (src_hi == hi) ? cl : ch;
15499 if (Subtarget->hasCMov()) {
15500 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
15501 .addReg(cH32).addReg(cL32);
15503 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
15504 .addReg(cH32).addReg(cL32)
15505 .addImm(X86::COND_E);
15506 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15508 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
15509 if (Subtarget->hasCMov()) {
15510 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
15511 .addReg(SrcLoReg).addReg(t4L);
15512 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
15513 .addReg(SrcHiReg).addReg(t4H);
15515 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
15516 .addReg(SrcLoReg).addReg(t4L)
15517 .addImm(X86::COND_NE);
15518 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15519 // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
15520 // 2nd CMOV lowering.
15521 mainMBB->addLiveIn(X86::EFLAGS);
15522 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
15523 .addReg(SrcHiReg).addReg(t4H)
15524 .addImm(X86::COND_NE);
15525 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15526 // Replace the original PHI node as mainMBB is changed after CMOV
15528 BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
15529 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15530 BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
15531 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15532 PhiL->eraseFromParent();
15533 PhiH->eraseFromParent();
15537 case X86::ATOMSWAP6432: {
15539 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15540 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
15541 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
15546 // Copy EDX:EAX back from HiReg:LoReg
15547 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
15548 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
15549 // Copy ECX:EBX from t1H:t1L
15550 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
15551 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
15553 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15554 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15555 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15557 NewMO.setIsKill(false);
15558 MIB.addOperand(NewMO);
15560 MIB.setMemRefs(MMOBegin, MMOEnd);
15562 // Copy EDX:EAX back to t3H:t3L
15563 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
15564 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
15566 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15568 mainMBB->addSuccessor(origMainMBB);
15569 mainMBB->addSuccessor(sinkMBB);
15572 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15573 TII->get(TargetOpcode::COPY), DstLoReg)
15575 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15576 TII->get(TargetOpcode::COPY), DstHiReg)
15579 MI->eraseFromParent();
15583 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
15584 // or XMM0_V32I8 in AVX all of this code can be replaced with that
15585 // in the .td file.
15586 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
15587 const TargetInstrInfo *TII) {
15589 switch (MI->getOpcode()) {
15590 default: llvm_unreachable("illegal opcode!");
15591 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
15592 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
15593 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
15594 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
15595 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
15596 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
15597 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
15598 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
15601 DebugLoc dl = MI->getDebugLoc();
15602 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15604 unsigned NumArgs = MI->getNumOperands();
15605 for (unsigned i = 1; i < NumArgs; ++i) {
15606 MachineOperand &Op = MI->getOperand(i);
15607 if (!(Op.isReg() && Op.isImplicit()))
15608 MIB.addOperand(Op);
15610 if (MI->hasOneMemOperand())
15611 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15613 BuildMI(*BB, MI, dl,
15614 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15615 .addReg(X86::XMM0);
15617 MI->eraseFromParent();
15621 // FIXME: Custom handling because TableGen doesn't support multiple implicit
15622 // defs in an instruction pattern
15623 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
15624 const TargetInstrInfo *TII) {
15626 switch (MI->getOpcode()) {
15627 default: llvm_unreachable("illegal opcode!");
15628 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
15629 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
15630 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
15631 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
15632 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
15633 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
15634 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
15635 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
15638 DebugLoc dl = MI->getDebugLoc();
15639 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15641 unsigned NumArgs = MI->getNumOperands(); // remove the results
15642 for (unsigned i = 1; i < NumArgs; ++i) {
15643 MachineOperand &Op = MI->getOperand(i);
15644 if (!(Op.isReg() && Op.isImplicit()))
15645 MIB.addOperand(Op);
15647 if (MI->hasOneMemOperand())
15648 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15650 BuildMI(*BB, MI, dl,
15651 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15654 MI->eraseFromParent();
15658 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
15659 const TargetInstrInfo *TII,
15660 const X86Subtarget* Subtarget) {
15661 DebugLoc dl = MI->getDebugLoc();
15663 // Address into RAX/EAX, other two args into ECX, EDX.
15664 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
15665 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
15666 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
15667 for (int i = 0; i < X86::AddrNumOperands; ++i)
15668 MIB.addOperand(MI->getOperand(i));
15670 unsigned ValOps = X86::AddrNumOperands;
15671 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
15672 .addReg(MI->getOperand(ValOps).getReg());
15673 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
15674 .addReg(MI->getOperand(ValOps+1).getReg());
15676 // The instruction doesn't actually take any operands though.
15677 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
15679 MI->eraseFromParent(); // The pseudo is gone now.
15683 MachineBasicBlock *
15684 X86TargetLowering::EmitVAARG64WithCustomInserter(
15686 MachineBasicBlock *MBB) const {
15687 // Emit va_arg instruction on X86-64.
15689 // Operands to this pseudo-instruction:
15690 // 0 ) Output : destination address (reg)
15691 // 1-5) Input : va_list address (addr, i64mem)
15692 // 6 ) ArgSize : Size (in bytes) of vararg type
15693 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
15694 // 8 ) Align : Alignment of type
15695 // 9 ) EFLAGS (implicit-def)
15697 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
15698 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
15700 unsigned DestReg = MI->getOperand(0).getReg();
15701 MachineOperand &Base = MI->getOperand(1);
15702 MachineOperand &Scale = MI->getOperand(2);
15703 MachineOperand &Index = MI->getOperand(3);
15704 MachineOperand &Disp = MI->getOperand(4);
15705 MachineOperand &Segment = MI->getOperand(5);
15706 unsigned ArgSize = MI->getOperand(6).getImm();
15707 unsigned ArgMode = MI->getOperand(7).getImm();
15708 unsigned Align = MI->getOperand(8).getImm();
15710 // Memory Reference
15711 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
15712 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15713 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15715 // Machine Information
15716 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15717 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
15718 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
15719 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
15720 DebugLoc DL = MI->getDebugLoc();
15722 // struct va_list {
15725 // i64 overflow_area (address)
15726 // i64 reg_save_area (address)
15728 // sizeof(va_list) = 24
15729 // alignment(va_list) = 8
15731 unsigned TotalNumIntRegs = 6;
15732 unsigned TotalNumXMMRegs = 8;
15733 bool UseGPOffset = (ArgMode == 1);
15734 bool UseFPOffset = (ArgMode == 2);
15735 unsigned MaxOffset = TotalNumIntRegs * 8 +
15736 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
15738 /* Align ArgSize to a multiple of 8 */
15739 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
15740 bool NeedsAlign = (Align > 8);
15742 MachineBasicBlock *thisMBB = MBB;
15743 MachineBasicBlock *overflowMBB;
15744 MachineBasicBlock *offsetMBB;
15745 MachineBasicBlock *endMBB;
15747 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
15748 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
15749 unsigned OffsetReg = 0;
15751 if (!UseGPOffset && !UseFPOffset) {
15752 // If we only pull from the overflow region, we don't create a branch.
15753 // We don't need to alter control flow.
15754 OffsetDestReg = 0; // unused
15755 OverflowDestReg = DestReg;
15757 offsetMBB = nullptr;
15758 overflowMBB = thisMBB;
15761 // First emit code to check if gp_offset (or fp_offset) is below the bound.
15762 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
15763 // If not, pull from overflow_area. (branch to overflowMBB)
15768 // offsetMBB overflowMBB
15773 // Registers for the PHI in endMBB
15774 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
15775 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
15777 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15778 MachineFunction *MF = MBB->getParent();
15779 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15780 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15781 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15783 MachineFunction::iterator MBBIter = MBB;
15786 // Insert the new basic blocks
15787 MF->insert(MBBIter, offsetMBB);
15788 MF->insert(MBBIter, overflowMBB);
15789 MF->insert(MBBIter, endMBB);
15791 // Transfer the remainder of MBB and its successor edges to endMBB.
15792 endMBB->splice(endMBB->begin(), thisMBB,
15793 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
15794 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
15796 // Make offsetMBB and overflowMBB successors of thisMBB
15797 thisMBB->addSuccessor(offsetMBB);
15798 thisMBB->addSuccessor(overflowMBB);
15800 // endMBB is a successor of both offsetMBB and overflowMBB
15801 offsetMBB->addSuccessor(endMBB);
15802 overflowMBB->addSuccessor(endMBB);
15804 // Load the offset value into a register
15805 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15806 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
15810 .addDisp(Disp, UseFPOffset ? 4 : 0)
15811 .addOperand(Segment)
15812 .setMemRefs(MMOBegin, MMOEnd);
15814 // Check if there is enough room left to pull this argument.
15815 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
15817 .addImm(MaxOffset + 8 - ArgSizeA8);
15819 // Branch to "overflowMBB" if offset >= max
15820 // Fall through to "offsetMBB" otherwise
15821 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
15822 .addMBB(overflowMBB);
15825 // In offsetMBB, emit code to use the reg_save_area.
15827 assert(OffsetReg != 0);
15829 // Read the reg_save_area address.
15830 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
15831 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
15836 .addOperand(Segment)
15837 .setMemRefs(MMOBegin, MMOEnd);
15839 // Zero-extend the offset
15840 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
15841 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
15844 .addImm(X86::sub_32bit);
15846 // Add the offset to the reg_save_area to get the final address.
15847 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
15848 .addReg(OffsetReg64)
15849 .addReg(RegSaveReg);
15851 // Compute the offset for the next argument
15852 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15853 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
15855 .addImm(UseFPOffset ? 16 : 8);
15857 // Store it back into the va_list.
15858 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
15862 .addDisp(Disp, UseFPOffset ? 4 : 0)
15863 .addOperand(Segment)
15864 .addReg(NextOffsetReg)
15865 .setMemRefs(MMOBegin, MMOEnd);
15868 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
15873 // Emit code to use overflow area
15876 // Load the overflow_area address into a register.
15877 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
15878 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
15883 .addOperand(Segment)
15884 .setMemRefs(MMOBegin, MMOEnd);
15886 // If we need to align it, do so. Otherwise, just copy the address
15887 // to OverflowDestReg.
15889 // Align the overflow address
15890 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
15891 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
15893 // aligned_addr = (addr + (align-1)) & ~(align-1)
15894 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
15895 .addReg(OverflowAddrReg)
15898 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
15900 .addImm(~(uint64_t)(Align-1));
15902 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
15903 .addReg(OverflowAddrReg);
15906 // Compute the next overflow address after this argument.
15907 // (the overflow address should be kept 8-byte aligned)
15908 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
15909 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
15910 .addReg(OverflowDestReg)
15911 .addImm(ArgSizeA8);
15913 // Store the new overflow address.
15914 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
15919 .addOperand(Segment)
15920 .addReg(NextAddrReg)
15921 .setMemRefs(MMOBegin, MMOEnd);
15923 // If we branched, emit the PHI to the front of endMBB.
15925 BuildMI(*endMBB, endMBB->begin(), DL,
15926 TII->get(X86::PHI), DestReg)
15927 .addReg(OffsetDestReg).addMBB(offsetMBB)
15928 .addReg(OverflowDestReg).addMBB(overflowMBB);
15931 // Erase the pseudo instruction
15932 MI->eraseFromParent();
15937 MachineBasicBlock *
15938 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
15940 MachineBasicBlock *MBB) const {
15941 // Emit code to save XMM registers to the stack. The ABI says that the
15942 // number of registers to save is given in %al, so it's theoretically
15943 // possible to do an indirect jump trick to avoid saving all of them,
15944 // however this code takes a simpler approach and just executes all
15945 // of the stores if %al is non-zero. It's less code, and it's probably
15946 // easier on the hardware branch predictor, and stores aren't all that
15947 // expensive anyway.
15949 // Create the new basic blocks. One block contains all the XMM stores,
15950 // and one block is the final destination regardless of whether any
15951 // stores were performed.
15952 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15953 MachineFunction *F = MBB->getParent();
15954 MachineFunction::iterator MBBIter = MBB;
15956 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
15957 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
15958 F->insert(MBBIter, XMMSaveMBB);
15959 F->insert(MBBIter, EndMBB);
15961 // Transfer the remainder of MBB and its successor edges to EndMBB.
15962 EndMBB->splice(EndMBB->begin(), MBB,
15963 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15964 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
15966 // The original block will now fall through to the XMM save block.
15967 MBB->addSuccessor(XMMSaveMBB);
15968 // The XMMSaveMBB will fall through to the end block.
15969 XMMSaveMBB->addSuccessor(EndMBB);
15971 // Now add the instructions.
15972 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15973 DebugLoc DL = MI->getDebugLoc();
15975 unsigned CountReg = MI->getOperand(0).getReg();
15976 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
15977 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
15979 if (!Subtarget->isTargetWin64()) {
15980 // If %al is 0, branch around the XMM save block.
15981 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
15982 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
15983 MBB->addSuccessor(EndMBB);
15986 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
15987 // that was just emitted, but clearly shouldn't be "saved".
15988 assert((MI->getNumOperands() <= 3 ||
15989 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
15990 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
15991 && "Expected last argument to be EFLAGS");
15992 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
15993 // In the XMM save block, save all the XMM argument registers.
15994 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
15995 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
15996 MachineMemOperand *MMO =
15997 F->getMachineMemOperand(
15998 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
15999 MachineMemOperand::MOStore,
16000 /*Size=*/16, /*Align=*/16);
16001 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
16002 .addFrameIndex(RegSaveFrameIndex)
16003 .addImm(/*Scale=*/1)
16004 .addReg(/*IndexReg=*/0)
16005 .addImm(/*Disp=*/Offset)
16006 .addReg(/*Segment=*/0)
16007 .addReg(MI->getOperand(i).getReg())
16008 .addMemOperand(MMO);
16011 MI->eraseFromParent(); // The pseudo instruction is gone now.
16016 // The EFLAGS operand of SelectItr might be missing a kill marker
16017 // because there were multiple uses of EFLAGS, and ISel didn't know
16018 // which to mark. Figure out whether SelectItr should have had a
16019 // kill marker, and set it if it should. Returns the correct kill
16021 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
16022 MachineBasicBlock* BB,
16023 const TargetRegisterInfo* TRI) {
16024 // Scan forward through BB for a use/def of EFLAGS.
16025 MachineBasicBlock::iterator miI(std::next(SelectItr));
16026 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
16027 const MachineInstr& mi = *miI;
16028 if (mi.readsRegister(X86::EFLAGS))
16030 if (mi.definesRegister(X86::EFLAGS))
16031 break; // Should have kill-flag - update below.
16034 // If we hit the end of the block, check whether EFLAGS is live into a
16036 if (miI == BB->end()) {
16037 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
16038 sEnd = BB->succ_end();
16039 sItr != sEnd; ++sItr) {
16040 MachineBasicBlock* succ = *sItr;
16041 if (succ->isLiveIn(X86::EFLAGS))
16046 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
16047 // out. SelectMI should have a kill flag on EFLAGS.
16048 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
16052 MachineBasicBlock *
16053 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
16054 MachineBasicBlock *BB) const {
16055 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16056 DebugLoc DL = MI->getDebugLoc();
16058 // To "insert" a SELECT_CC instruction, we actually have to insert the
16059 // diamond control-flow pattern. The incoming instruction knows the
16060 // destination vreg to set, the condition code register to branch on, the
16061 // true/false values to select between, and a branch opcode to use.
16062 const BasicBlock *LLVM_BB = BB->getBasicBlock();
16063 MachineFunction::iterator It = BB;
16069 // cmpTY ccX, r1, r2
16071 // fallthrough --> copy0MBB
16072 MachineBasicBlock *thisMBB = BB;
16073 MachineFunction *F = BB->getParent();
16074 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
16075 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
16076 F->insert(It, copy0MBB);
16077 F->insert(It, sinkMBB);
16079 // If the EFLAGS register isn't dead in the terminator, then claim that it's
16080 // live into the sink and copy blocks.
16081 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
16082 if (!MI->killsRegister(X86::EFLAGS) &&
16083 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
16084 copy0MBB->addLiveIn(X86::EFLAGS);
16085 sinkMBB->addLiveIn(X86::EFLAGS);
16088 // Transfer the remainder of BB and its successor edges to sinkMBB.
16089 sinkMBB->splice(sinkMBB->begin(), BB,
16090 std::next(MachineBasicBlock::iterator(MI)), BB->end());
16091 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
16093 // Add the true and fallthrough blocks as its successors.
16094 BB->addSuccessor(copy0MBB);
16095 BB->addSuccessor(sinkMBB);
16097 // Create the conditional branch instruction.
16099 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
16100 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
16103 // %FalseValue = ...
16104 // # fallthrough to sinkMBB
16105 copy0MBB->addSuccessor(sinkMBB);
16108 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
16110 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16111 TII->get(X86::PHI), MI->getOperand(0).getReg())
16112 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
16113 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
16115 MI->eraseFromParent(); // The pseudo instruction is gone now.
16119 MachineBasicBlock *
16120 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
16121 bool Is64Bit) const {
16122 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16123 DebugLoc DL = MI->getDebugLoc();
16124 MachineFunction *MF = BB->getParent();
16125 const BasicBlock *LLVM_BB = BB->getBasicBlock();
16127 assert(MF->shouldSplitStack());
16129 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
16130 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
16133 // ... [Till the alloca]
16134 // If stacklet is not large enough, jump to mallocMBB
16137 // Allocate by subtracting from RSP
16138 // Jump to continueMBB
16141 // Allocate by call to runtime
16145 // [rest of original BB]
16148 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16149 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16150 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16152 MachineRegisterInfo &MRI = MF->getRegInfo();
16153 const TargetRegisterClass *AddrRegClass =
16154 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
16156 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16157 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16158 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
16159 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
16160 sizeVReg = MI->getOperand(1).getReg(),
16161 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
16163 MachineFunction::iterator MBBIter = BB;
16166 MF->insert(MBBIter, bumpMBB);
16167 MF->insert(MBBIter, mallocMBB);
16168 MF->insert(MBBIter, continueMBB);
16170 continueMBB->splice(continueMBB->begin(), BB,
16171 std::next(MachineBasicBlock::iterator(MI)), BB->end());
16172 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
16174 // Add code to the main basic block to check if the stack limit has been hit,
16175 // and if so, jump to mallocMBB otherwise to bumpMBB.
16176 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
16177 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
16178 .addReg(tmpSPVReg).addReg(sizeVReg);
16179 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
16180 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
16181 .addReg(SPLimitVReg);
16182 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
16184 // bumpMBB simply decreases the stack pointer, since we know the current
16185 // stacklet has enough space.
16186 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
16187 .addReg(SPLimitVReg);
16188 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
16189 .addReg(SPLimitVReg);
16190 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16192 // Calls into a routine in libgcc to allocate more space from the heap.
16193 const uint32_t *RegMask =
16194 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16196 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
16198 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
16199 .addExternalSymbol("__morestack_allocate_stack_space")
16200 .addRegMask(RegMask)
16201 .addReg(X86::RDI, RegState::Implicit)
16202 .addReg(X86::RAX, RegState::ImplicitDefine);
16204 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
16206 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
16207 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
16208 .addExternalSymbol("__morestack_allocate_stack_space")
16209 .addRegMask(RegMask)
16210 .addReg(X86::EAX, RegState::ImplicitDefine);
16214 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
16217 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
16218 .addReg(Is64Bit ? X86::RAX : X86::EAX);
16219 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16221 // Set up the CFG correctly.
16222 BB->addSuccessor(bumpMBB);
16223 BB->addSuccessor(mallocMBB);
16224 mallocMBB->addSuccessor(continueMBB);
16225 bumpMBB->addSuccessor(continueMBB);
16227 // Take care of the PHI nodes.
16228 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
16229 MI->getOperand(0).getReg())
16230 .addReg(mallocPtrVReg).addMBB(mallocMBB)
16231 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
16233 // Delete the original pseudo instruction.
16234 MI->eraseFromParent();
16237 return continueMBB;
16240 MachineBasicBlock *
16241 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
16242 MachineBasicBlock *BB) const {
16243 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16244 DebugLoc DL = MI->getDebugLoc();
16246 assert(!Subtarget->isTargetMacho());
16248 // The lowering is pretty easy: we're just emitting the call to _alloca. The
16249 // non-trivial part is impdef of ESP.
16251 if (Subtarget->isTargetWin64()) {
16252 if (Subtarget->isTargetCygMing()) {
16253 // ___chkstk(Mingw64):
16254 // Clobbers R10, R11, RAX and EFLAGS.
16256 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16257 .addExternalSymbol("___chkstk")
16258 .addReg(X86::RAX, RegState::Implicit)
16259 .addReg(X86::RSP, RegState::Implicit)
16260 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
16261 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
16262 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16264 // __chkstk(MSVCRT): does not update stack pointer.
16265 // Clobbers R10, R11 and EFLAGS.
16266 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16267 .addExternalSymbol("__chkstk")
16268 .addReg(X86::RAX, RegState::Implicit)
16269 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16270 // RAX has the offset to be subtracted from RSP.
16271 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
16276 const char *StackProbeSymbol =
16277 Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
16279 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
16280 .addExternalSymbol(StackProbeSymbol)
16281 .addReg(X86::EAX, RegState::Implicit)
16282 .addReg(X86::ESP, RegState::Implicit)
16283 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
16284 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
16285 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16288 MI->eraseFromParent(); // The pseudo instruction is gone now.
16292 MachineBasicBlock *
16293 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
16294 MachineBasicBlock *BB) const {
16295 // This is pretty easy. We're taking the value that we received from
16296 // our load from the relocation, sticking it in either RDI (x86-64)
16297 // or EAX and doing an indirect call. The return value will then
16298 // be in the normal return register.
16299 const X86InstrInfo *TII
16300 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
16301 DebugLoc DL = MI->getDebugLoc();
16302 MachineFunction *F = BB->getParent();
16304 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
16305 assert(MI->getOperand(3).isGlobal() && "This should be a global");
16307 // Get a register mask for the lowered call.
16308 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
16309 // proper register mask.
16310 const uint32_t *RegMask =
16311 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16312 if (Subtarget->is64Bit()) {
16313 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16314 TII->get(X86::MOV64rm), X86::RDI)
16316 .addImm(0).addReg(0)
16317 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16318 MI->getOperand(3).getTargetFlags())
16320 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
16321 addDirectMem(MIB, X86::RDI);
16322 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
16323 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
16324 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16325 TII->get(X86::MOV32rm), X86::EAX)
16327 .addImm(0).addReg(0)
16328 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16329 MI->getOperand(3).getTargetFlags())
16331 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16332 addDirectMem(MIB, X86::EAX);
16333 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16335 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16336 TII->get(X86::MOV32rm), X86::EAX)
16337 .addReg(TII->getGlobalBaseReg(F))
16338 .addImm(0).addReg(0)
16339 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16340 MI->getOperand(3).getTargetFlags())
16342 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16343 addDirectMem(MIB, X86::EAX);
16344 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16347 MI->eraseFromParent(); // The pseudo instruction is gone now.
16351 MachineBasicBlock *
16352 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
16353 MachineBasicBlock *MBB) const {
16354 DebugLoc DL = MI->getDebugLoc();
16355 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16357 MachineFunction *MF = MBB->getParent();
16358 MachineRegisterInfo &MRI = MF->getRegInfo();
16360 const BasicBlock *BB = MBB->getBasicBlock();
16361 MachineFunction::iterator I = MBB;
16364 // Memory Reference
16365 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16366 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16369 unsigned MemOpndSlot = 0;
16371 unsigned CurOp = 0;
16373 DstReg = MI->getOperand(CurOp++).getReg();
16374 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
16375 assert(RC->hasType(MVT::i32) && "Invalid destination!");
16376 unsigned mainDstReg = MRI.createVirtualRegister(RC);
16377 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
16379 MemOpndSlot = CurOp;
16381 MVT PVT = getPointerTy();
16382 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16383 "Invalid Pointer Size!");
16385 // For v = setjmp(buf), we generate
16388 // buf[LabelOffset] = restoreMBB
16389 // SjLjSetup restoreMBB
16395 // v = phi(main, restore)
16400 MachineBasicBlock *thisMBB = MBB;
16401 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16402 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16403 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
16404 MF->insert(I, mainMBB);
16405 MF->insert(I, sinkMBB);
16406 MF->push_back(restoreMBB);
16408 MachineInstrBuilder MIB;
16410 // Transfer the remainder of BB and its successor edges to sinkMBB.
16411 sinkMBB->splice(sinkMBB->begin(), MBB,
16412 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16413 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16416 unsigned PtrStoreOpc = 0;
16417 unsigned LabelReg = 0;
16418 const int64_t LabelOffset = 1 * PVT.getStoreSize();
16419 Reloc::Model RM = getTargetMachine().getRelocationModel();
16420 bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
16421 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
16423 // Prepare IP either in reg or imm.
16424 if (!UseImmLabel) {
16425 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
16426 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
16427 LabelReg = MRI.createVirtualRegister(PtrRC);
16428 if (Subtarget->is64Bit()) {
16429 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
16433 .addMBB(restoreMBB)
16436 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
16437 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
16438 .addReg(XII->getGlobalBaseReg(MF))
16441 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
16445 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
16447 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
16448 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16449 if (i == X86::AddrDisp)
16450 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
16452 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
16455 MIB.addReg(LabelReg);
16457 MIB.addMBB(restoreMBB);
16458 MIB.setMemRefs(MMOBegin, MMOEnd);
16460 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
16461 .addMBB(restoreMBB);
16463 const X86RegisterInfo *RegInfo =
16464 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16465 MIB.addRegMask(RegInfo->getNoPreservedMask());
16466 thisMBB->addSuccessor(mainMBB);
16467 thisMBB->addSuccessor(restoreMBB);
16471 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
16472 mainMBB->addSuccessor(sinkMBB);
16475 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16476 TII->get(X86::PHI), DstReg)
16477 .addReg(mainDstReg).addMBB(mainMBB)
16478 .addReg(restoreDstReg).addMBB(restoreMBB);
16481 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
16482 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
16483 restoreMBB->addSuccessor(sinkMBB);
16485 MI->eraseFromParent();
16489 MachineBasicBlock *
16490 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
16491 MachineBasicBlock *MBB) const {
16492 DebugLoc DL = MI->getDebugLoc();
16493 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16495 MachineFunction *MF = MBB->getParent();
16496 MachineRegisterInfo &MRI = MF->getRegInfo();
16498 // Memory Reference
16499 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16500 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16502 MVT PVT = getPointerTy();
16503 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16504 "Invalid Pointer Size!");
16506 const TargetRegisterClass *RC =
16507 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
16508 unsigned Tmp = MRI.createVirtualRegister(RC);
16509 // Since FP is only updated here but NOT referenced, it's treated as GPR.
16510 const X86RegisterInfo *RegInfo =
16511 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16512 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
16513 unsigned SP = RegInfo->getStackRegister();
16515 MachineInstrBuilder MIB;
16517 const int64_t LabelOffset = 1 * PVT.getStoreSize();
16518 const int64_t SPOffset = 2 * PVT.getStoreSize();
16520 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
16521 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
16524 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
16525 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
16526 MIB.addOperand(MI->getOperand(i));
16527 MIB.setMemRefs(MMOBegin, MMOEnd);
16529 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
16530 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16531 if (i == X86::AddrDisp)
16532 MIB.addDisp(MI->getOperand(i), LabelOffset);
16534 MIB.addOperand(MI->getOperand(i));
16536 MIB.setMemRefs(MMOBegin, MMOEnd);
16538 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
16539 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16540 if (i == X86::AddrDisp)
16541 MIB.addDisp(MI->getOperand(i), SPOffset);
16543 MIB.addOperand(MI->getOperand(i));
16545 MIB.setMemRefs(MMOBegin, MMOEnd);
16547 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
16549 MI->eraseFromParent();
16553 // Replace 213-type (isel default) FMA3 instructions with 231-type for
16554 // accumulator loops. Writing back to the accumulator allows the coalescer
16555 // to remove extra copies in the loop.
16556 MachineBasicBlock *
16557 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
16558 MachineBasicBlock *MBB) const {
16559 MachineOperand &AddendOp = MI->getOperand(3);
16561 // Bail out early if the addend isn't a register - we can't switch these.
16562 if (!AddendOp.isReg())
16565 MachineFunction &MF = *MBB->getParent();
16566 MachineRegisterInfo &MRI = MF.getRegInfo();
16568 // Check whether the addend is defined by a PHI:
16569 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
16570 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
16571 if (!AddendDef.isPHI())
16574 // Look for the following pattern:
16576 // %addend = phi [%entry, 0], [%loop, %result]
16578 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
16582 // %addend = phi [%entry, 0], [%loop, %result]
16584 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
16586 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
16587 assert(AddendDef.getOperand(i).isReg());
16588 MachineOperand PHISrcOp = AddendDef.getOperand(i);
16589 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
16590 if (&PHISrcInst == MI) {
16591 // Found a matching instruction.
16592 unsigned NewFMAOpc = 0;
16593 switch (MI->getOpcode()) {
16594 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
16595 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
16596 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
16597 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
16598 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
16599 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
16600 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
16601 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
16602 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
16603 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
16604 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
16605 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
16606 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
16607 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
16608 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
16609 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
16610 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
16611 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
16612 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
16613 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
16614 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
16615 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
16616 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
16617 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
16618 default: llvm_unreachable("Unrecognized FMA variant.");
16621 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
16622 MachineInstrBuilder MIB =
16623 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
16624 .addOperand(MI->getOperand(0))
16625 .addOperand(MI->getOperand(3))
16626 .addOperand(MI->getOperand(2))
16627 .addOperand(MI->getOperand(1));
16628 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
16629 MI->eraseFromParent();
16636 MachineBasicBlock *
16637 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
16638 MachineBasicBlock *BB) const {
16639 switch (MI->getOpcode()) {
16640 default: llvm_unreachable("Unexpected instr type to insert");
16641 case X86::TAILJMPd64:
16642 case X86::TAILJMPr64:
16643 case X86::TAILJMPm64:
16644 llvm_unreachable("TAILJMP64 would not be touched here.");
16645 case X86::TCRETURNdi64:
16646 case X86::TCRETURNri64:
16647 case X86::TCRETURNmi64:
16649 case X86::WIN_ALLOCA:
16650 return EmitLoweredWinAlloca(MI, BB);
16651 case X86::SEG_ALLOCA_32:
16652 return EmitLoweredSegAlloca(MI, BB, false);
16653 case X86::SEG_ALLOCA_64:
16654 return EmitLoweredSegAlloca(MI, BB, true);
16655 case X86::TLSCall_32:
16656 case X86::TLSCall_64:
16657 return EmitLoweredTLSCall(MI, BB);
16658 case X86::CMOV_GR8:
16659 case X86::CMOV_FR32:
16660 case X86::CMOV_FR64:
16661 case X86::CMOV_V4F32:
16662 case X86::CMOV_V2F64:
16663 case X86::CMOV_V2I64:
16664 case X86::CMOV_V8F32:
16665 case X86::CMOV_V4F64:
16666 case X86::CMOV_V4I64:
16667 case X86::CMOV_V16F32:
16668 case X86::CMOV_V8F64:
16669 case X86::CMOV_V8I64:
16670 case X86::CMOV_GR16:
16671 case X86::CMOV_GR32:
16672 case X86::CMOV_RFP32:
16673 case X86::CMOV_RFP64:
16674 case X86::CMOV_RFP80:
16675 return EmitLoweredSelect(MI, BB);
16677 case X86::FP32_TO_INT16_IN_MEM:
16678 case X86::FP32_TO_INT32_IN_MEM:
16679 case X86::FP32_TO_INT64_IN_MEM:
16680 case X86::FP64_TO_INT16_IN_MEM:
16681 case X86::FP64_TO_INT32_IN_MEM:
16682 case X86::FP64_TO_INT64_IN_MEM:
16683 case X86::FP80_TO_INT16_IN_MEM:
16684 case X86::FP80_TO_INT32_IN_MEM:
16685 case X86::FP80_TO_INT64_IN_MEM: {
16686 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16687 DebugLoc DL = MI->getDebugLoc();
16689 // Change the floating point control register to use "round towards zero"
16690 // mode when truncating to an integer value.
16691 MachineFunction *F = BB->getParent();
16692 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
16693 addFrameReference(BuildMI(*BB, MI, DL,
16694 TII->get(X86::FNSTCW16m)), CWFrameIdx);
16696 // Load the old value of the high byte of the control word...
16698 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
16699 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
16702 // Set the high part to be round to zero...
16703 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
16706 // Reload the modified control word now...
16707 addFrameReference(BuildMI(*BB, MI, DL,
16708 TII->get(X86::FLDCW16m)), CWFrameIdx);
16710 // Restore the memory image of control word to original value
16711 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
16714 // Get the X86 opcode to use.
16716 switch (MI->getOpcode()) {
16717 default: llvm_unreachable("illegal opcode!");
16718 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
16719 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
16720 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
16721 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
16722 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
16723 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
16724 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
16725 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
16726 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
16730 MachineOperand &Op = MI->getOperand(0);
16732 AM.BaseType = X86AddressMode::RegBase;
16733 AM.Base.Reg = Op.getReg();
16735 AM.BaseType = X86AddressMode::FrameIndexBase;
16736 AM.Base.FrameIndex = Op.getIndex();
16738 Op = MI->getOperand(1);
16740 AM.Scale = Op.getImm();
16741 Op = MI->getOperand(2);
16743 AM.IndexReg = Op.getImm();
16744 Op = MI->getOperand(3);
16745 if (Op.isGlobal()) {
16746 AM.GV = Op.getGlobal();
16748 AM.Disp = Op.getImm();
16750 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
16751 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
16753 // Reload the original control word now.
16754 addFrameReference(BuildMI(*BB, MI, DL,
16755 TII->get(X86::FLDCW16m)), CWFrameIdx);
16757 MI->eraseFromParent(); // The pseudo instruction is gone now.
16760 // String/text processing lowering.
16761 case X86::PCMPISTRM128REG:
16762 case X86::VPCMPISTRM128REG:
16763 case X86::PCMPISTRM128MEM:
16764 case X86::VPCMPISTRM128MEM:
16765 case X86::PCMPESTRM128REG:
16766 case X86::VPCMPESTRM128REG:
16767 case X86::PCMPESTRM128MEM:
16768 case X86::VPCMPESTRM128MEM:
16769 assert(Subtarget->hasSSE42() &&
16770 "Target must have SSE4.2 or AVX features enabled");
16771 return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
16773 // String/text processing lowering.
16774 case X86::PCMPISTRIREG:
16775 case X86::VPCMPISTRIREG:
16776 case X86::PCMPISTRIMEM:
16777 case X86::VPCMPISTRIMEM:
16778 case X86::PCMPESTRIREG:
16779 case X86::VPCMPESTRIREG:
16780 case X86::PCMPESTRIMEM:
16781 case X86::VPCMPESTRIMEM:
16782 assert(Subtarget->hasSSE42() &&
16783 "Target must have SSE4.2 or AVX features enabled");
16784 return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
16786 // Thread synchronization.
16788 return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
16792 return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
16794 // Atomic Lowering.
16795 case X86::ATOMAND8:
16796 case X86::ATOMAND16:
16797 case X86::ATOMAND32:
16798 case X86::ATOMAND64:
16801 case X86::ATOMOR16:
16802 case X86::ATOMOR32:
16803 case X86::ATOMOR64:
16805 case X86::ATOMXOR16:
16806 case X86::ATOMXOR8:
16807 case X86::ATOMXOR32:
16808 case X86::ATOMXOR64:
16810 case X86::ATOMNAND8:
16811 case X86::ATOMNAND16:
16812 case X86::ATOMNAND32:
16813 case X86::ATOMNAND64:
16815 case X86::ATOMMAX8:
16816 case X86::ATOMMAX16:
16817 case X86::ATOMMAX32:
16818 case X86::ATOMMAX64:
16820 case X86::ATOMMIN8:
16821 case X86::ATOMMIN16:
16822 case X86::ATOMMIN32:
16823 case X86::ATOMMIN64:
16825 case X86::ATOMUMAX8:
16826 case X86::ATOMUMAX16:
16827 case X86::ATOMUMAX32:
16828 case X86::ATOMUMAX64:
16830 case X86::ATOMUMIN8:
16831 case X86::ATOMUMIN16:
16832 case X86::ATOMUMIN32:
16833 case X86::ATOMUMIN64:
16834 return EmitAtomicLoadArith(MI, BB);
16836 // This group does 64-bit operations on a 32-bit host.
16837 case X86::ATOMAND6432:
16838 case X86::ATOMOR6432:
16839 case X86::ATOMXOR6432:
16840 case X86::ATOMNAND6432:
16841 case X86::ATOMADD6432:
16842 case X86::ATOMSUB6432:
16843 case X86::ATOMMAX6432:
16844 case X86::ATOMMIN6432:
16845 case X86::ATOMUMAX6432:
16846 case X86::ATOMUMIN6432:
16847 case X86::ATOMSWAP6432:
16848 return EmitAtomicLoadArith6432(MI, BB);
16850 case X86::VASTART_SAVE_XMM_REGS:
16851 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
16853 case X86::VAARG_64:
16854 return EmitVAARG64WithCustomInserter(MI, BB);
16856 case X86::EH_SjLj_SetJmp32:
16857 case X86::EH_SjLj_SetJmp64:
16858 return emitEHSjLjSetJmp(MI, BB);
16860 case X86::EH_SjLj_LongJmp32:
16861 case X86::EH_SjLj_LongJmp64:
16862 return emitEHSjLjLongJmp(MI, BB);
16864 case TargetOpcode::STACKMAP:
16865 case TargetOpcode::PATCHPOINT:
16866 return emitPatchPoint(MI, BB);
16868 case X86::VFMADDPDr213r:
16869 case X86::VFMADDPSr213r:
16870 case X86::VFMADDSDr213r:
16871 case X86::VFMADDSSr213r:
16872 case X86::VFMSUBPDr213r:
16873 case X86::VFMSUBPSr213r:
16874 case X86::VFMSUBSDr213r:
16875 case X86::VFMSUBSSr213r:
16876 case X86::VFNMADDPDr213r:
16877 case X86::VFNMADDPSr213r:
16878 case X86::VFNMADDSDr213r:
16879 case X86::VFNMADDSSr213r:
16880 case X86::VFNMSUBPDr213r:
16881 case X86::VFNMSUBPSr213r:
16882 case X86::VFNMSUBSDr213r:
16883 case X86::VFNMSUBSSr213r:
16884 case X86::VFMADDPDr213rY:
16885 case X86::VFMADDPSr213rY:
16886 case X86::VFMSUBPDr213rY:
16887 case X86::VFMSUBPSr213rY:
16888 case X86::VFNMADDPDr213rY:
16889 case X86::VFNMADDPSr213rY:
16890 case X86::VFNMSUBPDr213rY:
16891 case X86::VFNMSUBPSr213rY:
16892 return emitFMA3Instr(MI, BB);
16896 //===----------------------------------------------------------------------===//
16897 // X86 Optimization Hooks
16898 //===----------------------------------------------------------------------===//
16900 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
16903 const SelectionDAG &DAG,
16904 unsigned Depth) const {
16905 unsigned BitWidth = KnownZero.getBitWidth();
16906 unsigned Opc = Op.getOpcode();
16907 assert((Opc >= ISD::BUILTIN_OP_END ||
16908 Opc == ISD::INTRINSIC_WO_CHAIN ||
16909 Opc == ISD::INTRINSIC_W_CHAIN ||
16910 Opc == ISD::INTRINSIC_VOID) &&
16911 "Should use MaskedValueIsZero if you don't know whether Op"
16912 " is a target node!");
16914 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
16928 // These nodes' second result is a boolean.
16929 if (Op.getResNo() == 0)
16932 case X86ISD::SETCC:
16933 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
16935 case ISD::INTRINSIC_WO_CHAIN: {
16936 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16937 unsigned NumLoBits = 0;
16940 case Intrinsic::x86_sse_movmsk_ps:
16941 case Intrinsic::x86_avx_movmsk_ps_256:
16942 case Intrinsic::x86_sse2_movmsk_pd:
16943 case Intrinsic::x86_avx_movmsk_pd_256:
16944 case Intrinsic::x86_mmx_pmovmskb:
16945 case Intrinsic::x86_sse2_pmovmskb_128:
16946 case Intrinsic::x86_avx2_pmovmskb: {
16947 // High bits of movmskp{s|d}, pmovmskb are known zero.
16949 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
16950 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
16951 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
16952 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
16953 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
16954 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
16955 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
16956 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
16958 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
16967 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
16969 const SelectionDAG &,
16970 unsigned Depth) const {
16971 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
16972 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
16973 return Op.getValueType().getScalarType().getSizeInBits();
16979 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
16980 /// node is a GlobalAddress + offset.
16981 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
16982 const GlobalValue* &GA,
16983 int64_t &Offset) const {
16984 if (N->getOpcode() == X86ISD::Wrapper) {
16985 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
16986 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
16987 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
16991 return TargetLowering::isGAPlusOffset(N, GA, Offset);
16994 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
16995 /// same as extracting the high 128-bit part of 256-bit vector and then
16996 /// inserting the result into the low part of a new 256-bit vector
16997 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
16998 EVT VT = SVOp->getValueType(0);
16999 unsigned NumElems = VT.getVectorNumElements();
17001 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17002 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
17003 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17004 SVOp->getMaskElt(j) >= 0)
17010 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
17011 /// same as extracting the low 128-bit part of 256-bit vector and then
17012 /// inserting the result into the high part of a new 256-bit vector
17013 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
17014 EVT VT = SVOp->getValueType(0);
17015 unsigned NumElems = VT.getVectorNumElements();
17017 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17018 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
17019 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17020 SVOp->getMaskElt(j) >= 0)
17026 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
17027 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
17028 TargetLowering::DAGCombinerInfo &DCI,
17029 const X86Subtarget* Subtarget) {
17031 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17032 SDValue V1 = SVOp->getOperand(0);
17033 SDValue V2 = SVOp->getOperand(1);
17034 EVT VT = SVOp->getValueType(0);
17035 unsigned NumElems = VT.getVectorNumElements();
17037 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
17038 V2.getOpcode() == ISD::CONCAT_VECTORS) {
17042 // V UNDEF BUILD_VECTOR UNDEF
17044 // CONCAT_VECTOR CONCAT_VECTOR
17047 // RESULT: V + zero extended
17049 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
17050 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
17051 V1.getOperand(1).getOpcode() != ISD::UNDEF)
17054 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
17057 // To match the shuffle mask, the first half of the mask should
17058 // be exactly the first vector, and all the rest a splat with the
17059 // first element of the second one.
17060 for (unsigned i = 0; i != NumElems/2; ++i)
17061 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
17062 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
17065 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
17066 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
17067 if (Ld->hasNUsesOfValue(1, 0)) {
17068 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
17069 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
17071 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
17072 array_lengthof(Ops),
17074 Ld->getPointerInfo(),
17075 Ld->getAlignment(),
17076 false/*isVolatile*/, true/*ReadMem*/,
17077 false/*WriteMem*/);
17079 // Make sure the newly-created LOAD is in the same position as Ld in
17080 // terms of dependency. We create a TokenFactor for Ld and ResNode,
17081 // and update uses of Ld's output chain to use the TokenFactor.
17082 if (Ld->hasAnyUseOfValue(1)) {
17083 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17084 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
17085 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
17086 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
17087 SDValue(ResNode.getNode(), 1));
17090 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
17094 // Emit a zeroed vector and insert the desired subvector on its
17096 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17097 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
17098 return DCI.CombineTo(N, InsV);
17101 //===--------------------------------------------------------------------===//
17102 // Combine some shuffles into subvector extracts and inserts:
17105 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17106 if (isShuffleHigh128VectorInsertLow(SVOp)) {
17107 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
17108 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
17109 return DCI.CombineTo(N, InsV);
17112 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17113 if (isShuffleLow128VectorInsertHigh(SVOp)) {
17114 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
17115 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
17116 return DCI.CombineTo(N, InsV);
17122 /// PerformShuffleCombine - Performs several different shuffle combines.
17123 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
17124 TargetLowering::DAGCombinerInfo &DCI,
17125 const X86Subtarget *Subtarget) {
17127 EVT VT = N->getValueType(0);
17129 // Don't create instructions with illegal types after legalize types has run.
17130 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17131 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
17134 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
17135 if (Subtarget->hasFp256() && VT.is256BitVector() &&
17136 N->getOpcode() == ISD::VECTOR_SHUFFLE)
17137 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
17139 // Only handle 128 wide vector from here on.
17140 if (!VT.is128BitVector())
17143 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
17144 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
17145 // consecutive, non-overlapping, and in the right order.
17146 SmallVector<SDValue, 16> Elts;
17147 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
17148 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
17150 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
17153 /// PerformTruncateCombine - Converts truncate operation to
17154 /// a sequence of vector shuffle operations.
17155 /// It is possible when we truncate 256-bit vector to 128-bit vector
17156 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
17157 TargetLowering::DAGCombinerInfo &DCI,
17158 const X86Subtarget *Subtarget) {
17162 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
17163 /// specific shuffle of a load can be folded into a single element load.
17164 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
17165 /// shuffles have been customed lowered so we need to handle those here.
17166 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
17167 TargetLowering::DAGCombinerInfo &DCI) {
17168 if (DCI.isBeforeLegalizeOps())
17171 SDValue InVec = N->getOperand(0);
17172 SDValue EltNo = N->getOperand(1);
17174 if (!isa<ConstantSDNode>(EltNo))
17177 EVT VT = InVec.getValueType();
17179 bool HasShuffleIntoBitcast = false;
17180 if (InVec.getOpcode() == ISD::BITCAST) {
17181 // Don't duplicate a load with other uses.
17182 if (!InVec.hasOneUse())
17184 EVT BCVT = InVec.getOperand(0).getValueType();
17185 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
17187 InVec = InVec.getOperand(0);
17188 HasShuffleIntoBitcast = true;
17191 if (!isTargetShuffle(InVec.getOpcode()))
17194 // Don't duplicate a load with other uses.
17195 if (!InVec.hasOneUse())
17198 SmallVector<int, 16> ShuffleMask;
17200 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
17204 // Select the input vector, guarding against out of range extract vector.
17205 unsigned NumElems = VT.getVectorNumElements();
17206 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
17207 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
17208 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
17209 : InVec.getOperand(1);
17211 // If inputs to shuffle are the same for both ops, then allow 2 uses
17212 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
17214 if (LdNode.getOpcode() == ISD::BITCAST) {
17215 // Don't duplicate a load with other uses.
17216 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
17219 AllowedUses = 1; // only allow 1 load use if we have a bitcast
17220 LdNode = LdNode.getOperand(0);
17223 if (!ISD::isNormalLoad(LdNode.getNode()))
17226 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
17228 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
17231 if (HasShuffleIntoBitcast) {
17232 // If there's a bitcast before the shuffle, check if the load type and
17233 // alignment is valid.
17234 unsigned Align = LN0->getAlignment();
17235 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17236 unsigned NewAlign = TLI.getDataLayout()->
17237 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
17239 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
17243 // All checks match so transform back to vector_shuffle so that DAG combiner
17244 // can finish the job
17247 // Create shuffle node taking into account the case that its a unary shuffle
17248 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
17249 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
17250 InVec.getOperand(0), Shuffle,
17252 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
17253 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
17257 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
17258 /// generation and convert it from being a bunch of shuffles and extracts
17259 /// to a simple store and scalar loads to extract the elements.
17260 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
17261 TargetLowering::DAGCombinerInfo &DCI) {
17262 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
17263 if (NewOp.getNode())
17266 SDValue InputVector = N->getOperand(0);
17268 // Detect whether we are trying to convert from mmx to i32 and the bitcast
17269 // from mmx to v2i32 has a single usage.
17270 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
17271 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
17272 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
17273 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
17274 N->getValueType(0),
17275 InputVector.getNode()->getOperand(0));
17277 // Only operate on vectors of 4 elements, where the alternative shuffling
17278 // gets to be more expensive.
17279 if (InputVector.getValueType() != MVT::v4i32)
17282 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
17283 // single use which is a sign-extend or zero-extend, and all elements are
17285 SmallVector<SDNode *, 4> Uses;
17286 unsigned ExtractedElements = 0;
17287 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
17288 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
17289 if (UI.getUse().getResNo() != InputVector.getResNo())
17292 SDNode *Extract = *UI;
17293 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
17296 if (Extract->getValueType(0) != MVT::i32)
17298 if (!Extract->hasOneUse())
17300 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
17301 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
17303 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
17306 // Record which element was extracted.
17307 ExtractedElements |=
17308 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
17310 Uses.push_back(Extract);
17313 // If not all the elements were used, this may not be worthwhile.
17314 if (ExtractedElements != 15)
17317 // Ok, we've now decided to do the transformation.
17318 SDLoc dl(InputVector);
17320 // Store the value to a temporary stack slot.
17321 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
17322 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
17323 MachinePointerInfo(), false, false, 0);
17325 // Replace each use (extract) with a load of the appropriate element.
17326 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
17327 UE = Uses.end(); UI != UE; ++UI) {
17328 SDNode *Extract = *UI;
17330 // cOMpute the element's address.
17331 SDValue Idx = Extract->getOperand(1);
17333 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
17334 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
17335 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17336 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
17338 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
17339 StackPtr, OffsetVal);
17341 // Load the scalar.
17342 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
17343 ScalarAddr, MachinePointerInfo(),
17344 false, false, false, 0);
17346 // Replace the exact with the load.
17347 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
17350 // The replacement was made in place; don't return anything.
17354 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
17355 static std::pair<unsigned, bool>
17356 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
17357 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
17358 if (!VT.isVector())
17359 return std::make_pair(0, false);
17361 bool NeedSplit = false;
17362 switch (VT.getSimpleVT().SimpleTy) {
17363 default: return std::make_pair(0, false);
17367 if (!Subtarget->hasAVX2())
17369 if (!Subtarget->hasAVX())
17370 return std::make_pair(0, false);
17375 if (!Subtarget->hasSSE2())
17376 return std::make_pair(0, false);
17379 // SSE2 has only a small subset of the operations.
17380 bool hasUnsigned = Subtarget->hasSSE41() ||
17381 (Subtarget->hasSSE2() && VT == MVT::v16i8);
17382 bool hasSigned = Subtarget->hasSSE41() ||
17383 (Subtarget->hasSSE2() && VT == MVT::v8i16);
17385 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17388 // Check for x CC y ? x : y.
17389 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17390 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17395 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17398 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17401 Opc = hasSigned ? X86ISD::SMIN : 0; break;
17404 Opc = hasSigned ? X86ISD::SMAX : 0; break;
17406 // Check for x CC y ? y : x -- a min/max with reversed arms.
17407 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17408 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17413 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17416 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17419 Opc = hasSigned ? X86ISD::SMAX : 0; break;
17422 Opc = hasSigned ? X86ISD::SMIN : 0; break;
17426 return std::make_pair(Opc, NeedSplit);
17429 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
17431 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
17432 TargetLowering::DAGCombinerInfo &DCI,
17433 const X86Subtarget *Subtarget) {
17435 SDValue Cond = N->getOperand(0);
17436 // Get the LHS/RHS of the select.
17437 SDValue LHS = N->getOperand(1);
17438 SDValue RHS = N->getOperand(2);
17439 EVT VT = LHS.getValueType();
17440 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17442 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
17443 // instructions match the semantics of the common C idiom x<y?x:y but not
17444 // x<=y?x:y, because of how they handle negative zero (which can be
17445 // ignored in unsafe-math mode).
17446 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
17447 VT != MVT::f80 && TLI.isTypeLegal(VT) &&
17448 (Subtarget->hasSSE2() ||
17449 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
17450 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17452 unsigned Opcode = 0;
17453 // Check for x CC y ? x : y.
17454 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17455 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17459 // Converting this to a min would handle NaNs incorrectly, and swapping
17460 // the operands would cause it to handle comparisons between positive
17461 // and negative zero incorrectly.
17462 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17463 if (!DAG.getTarget().Options.UnsafeFPMath &&
17464 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17466 std::swap(LHS, RHS);
17468 Opcode = X86ISD::FMIN;
17471 // Converting this to a min would handle comparisons between positive
17472 // and negative zero incorrectly.
17473 if (!DAG.getTarget().Options.UnsafeFPMath &&
17474 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17476 Opcode = X86ISD::FMIN;
17479 // Converting this to a min would handle both negative zeros and NaNs
17480 // incorrectly, but we can swap the operands to fix both.
17481 std::swap(LHS, RHS);
17485 Opcode = X86ISD::FMIN;
17489 // Converting this to a max would handle comparisons between positive
17490 // and negative zero incorrectly.
17491 if (!DAG.getTarget().Options.UnsafeFPMath &&
17492 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17494 Opcode = X86ISD::FMAX;
17497 // Converting this to a max would handle NaNs incorrectly, and swapping
17498 // the operands would cause it to handle comparisons between positive
17499 // and negative zero incorrectly.
17500 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17501 if (!DAG.getTarget().Options.UnsafeFPMath &&
17502 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17504 std::swap(LHS, RHS);
17506 Opcode = X86ISD::FMAX;
17509 // Converting this to a max would handle both negative zeros and NaNs
17510 // incorrectly, but we can swap the operands to fix both.
17511 std::swap(LHS, RHS);
17515 Opcode = X86ISD::FMAX;
17518 // Check for x CC y ? y : x -- a min/max with reversed arms.
17519 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17520 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17524 // Converting this to a min would handle comparisons between positive
17525 // and negative zero incorrectly, and swapping the operands would
17526 // cause it to handle NaNs incorrectly.
17527 if (!DAG.getTarget().Options.UnsafeFPMath &&
17528 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
17529 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17531 std::swap(LHS, RHS);
17533 Opcode = X86ISD::FMIN;
17536 // Converting this to a min would handle NaNs incorrectly.
17537 if (!DAG.getTarget().Options.UnsafeFPMath &&
17538 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
17540 Opcode = X86ISD::FMIN;
17543 // Converting this to a min would handle both negative zeros and NaNs
17544 // incorrectly, but we can swap the operands to fix both.
17545 std::swap(LHS, RHS);
17549 Opcode = X86ISD::FMIN;
17553 // Converting this to a max would handle NaNs incorrectly.
17554 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17556 Opcode = X86ISD::FMAX;
17559 // Converting this to a max would handle comparisons between positive
17560 // and negative zero incorrectly, and swapping the operands would
17561 // cause it to handle NaNs incorrectly.
17562 if (!DAG.getTarget().Options.UnsafeFPMath &&
17563 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
17564 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17566 std::swap(LHS, RHS);
17568 Opcode = X86ISD::FMAX;
17571 // Converting this to a max would handle both negative zeros and NaNs
17572 // incorrectly, but we can swap the operands to fix both.
17573 std::swap(LHS, RHS);
17577 Opcode = X86ISD::FMAX;
17583 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
17586 EVT CondVT = Cond.getValueType();
17587 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
17588 CondVT.getVectorElementType() == MVT::i1) {
17589 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
17590 // lowering on AVX-512. In this case we convert it to
17591 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
17592 // The same situation for all 128 and 256-bit vectors of i8 and i16
17593 EVT OpVT = LHS.getValueType();
17594 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
17595 (OpVT.getVectorElementType() == MVT::i8 ||
17596 OpVT.getVectorElementType() == MVT::i16)) {
17597 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
17598 DCI.AddToWorklist(Cond.getNode());
17599 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
17602 // If this is a select between two integer constants, try to do some
17604 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
17605 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
17606 // Don't do this for crazy integer types.
17607 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
17608 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
17609 // so that TrueC (the true value) is larger than FalseC.
17610 bool NeedsCondInvert = false;
17612 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
17613 // Efficiently invertible.
17614 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
17615 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
17616 isa<ConstantSDNode>(Cond.getOperand(1))))) {
17617 NeedsCondInvert = true;
17618 std::swap(TrueC, FalseC);
17621 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
17622 if (FalseC->getAPIntValue() == 0 &&
17623 TrueC->getAPIntValue().isPowerOf2()) {
17624 if (NeedsCondInvert) // Invert the condition if needed.
17625 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17626 DAG.getConstant(1, Cond.getValueType()));
17628 // Zero extend the condition if needed.
17629 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
17631 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17632 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
17633 DAG.getConstant(ShAmt, MVT::i8));
17636 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
17637 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17638 if (NeedsCondInvert) // Invert the condition if needed.
17639 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17640 DAG.getConstant(1, Cond.getValueType()));
17642 // Zero extend the condition if needed.
17643 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17644 FalseC->getValueType(0), Cond);
17645 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17646 SDValue(FalseC, 0));
17649 // Optimize cases that will turn into an LEA instruction. This requires
17650 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17651 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17652 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17653 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17655 bool isFastMultiplier = false;
17657 switch ((unsigned char)Diff) {
17659 case 1: // result = add base, cond
17660 case 2: // result = lea base( , cond*2)
17661 case 3: // result = lea base(cond, cond*2)
17662 case 4: // result = lea base( , cond*4)
17663 case 5: // result = lea base(cond, cond*4)
17664 case 8: // result = lea base( , cond*8)
17665 case 9: // result = lea base(cond, cond*8)
17666 isFastMultiplier = true;
17671 if (isFastMultiplier) {
17672 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
17673 if (NeedsCondInvert) // Invert the condition if needed.
17674 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17675 DAG.getConstant(1, Cond.getValueType()));
17677 // Zero extend the condition if needed.
17678 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
17680 // Scale the condition by the difference.
17682 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
17683 DAG.getConstant(Diff, Cond.getValueType()));
17685 // Add the base if non-zero.
17686 if (FalseC->getAPIntValue() != 0)
17687 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17688 SDValue(FalseC, 0));
17695 // Canonicalize max and min:
17696 // (x > y) ? x : y -> (x >= y) ? x : y
17697 // (x < y) ? x : y -> (x <= y) ? x : y
17698 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
17699 // the need for an extra compare
17700 // against zero. e.g.
17701 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
17703 // testl %edi, %edi
17705 // cmovgl %edi, %eax
17709 // cmovsl %eax, %edi
17710 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
17711 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17712 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17713 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17718 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
17719 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
17720 Cond.getOperand(0), Cond.getOperand(1), NewCC);
17721 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
17726 // Early exit check
17727 if (!TLI.isTypeLegal(VT))
17730 // Match VSELECTs into subs with unsigned saturation.
17731 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17732 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
17733 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
17734 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
17735 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17737 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
17738 // left side invert the predicate to simplify logic below.
17740 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
17742 CC = ISD::getSetCCInverse(CC, true);
17743 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
17747 if (Other.getNode() && Other->getNumOperands() == 2 &&
17748 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
17749 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
17750 SDValue CondRHS = Cond->getOperand(1);
17752 // Look for a general sub with unsigned saturation first.
17753 // x >= y ? x-y : 0 --> subus x, y
17754 // x > y ? x-y : 0 --> subus x, y
17755 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
17756 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
17757 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17759 // If the RHS is a constant we have to reverse the const canonicalization.
17760 // x > C-1 ? x+-C : 0 --> subus x, C
17761 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
17762 isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
17763 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17764 if (CondRHS.getConstantOperandVal(0) == -A-1)
17765 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
17766 DAG.getConstant(-A, VT));
17769 // Another special case: If C was a sign bit, the sub has been
17770 // canonicalized into a xor.
17771 // FIXME: Would it be better to use ComputeMaskedBits to determine whether
17772 // it's safe to decanonicalize the xor?
17773 // x s< 0 ? x^C : 0 --> subus x, C
17774 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
17775 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
17776 isSplatVector(OpRHS.getNode())) {
17777 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17779 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17784 // Try to match a min/max vector operation.
17785 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
17786 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
17787 unsigned Opc = ret.first;
17788 bool NeedSplit = ret.second;
17790 if (Opc && NeedSplit) {
17791 unsigned NumElems = VT.getVectorNumElements();
17792 // Extract the LHS vectors
17793 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
17794 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
17796 // Extract the RHS vectors
17797 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
17798 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
17800 // Create min/max for each subvector
17801 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
17802 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
17804 // Merge the result
17805 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
17807 return DAG.getNode(Opc, DL, VT, LHS, RHS);
17810 // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
17811 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17812 // Check if SETCC has already been promoted
17813 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
17814 // Check that condition value type matches vselect operand type
17817 assert(Cond.getValueType().isVector() &&
17818 "vector select expects a vector selector!");
17820 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
17821 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
17823 if (!TValIsAllOnes && !FValIsAllZeros) {
17824 // Try invert the condition if true value is not all 1s and false value
17826 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
17827 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
17829 if (TValIsAllZeros || FValIsAllOnes) {
17830 SDValue CC = Cond.getOperand(2);
17831 ISD::CondCode NewCC =
17832 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
17833 Cond.getOperand(0).getValueType().isInteger());
17834 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
17835 std::swap(LHS, RHS);
17836 TValIsAllOnes = FValIsAllOnes;
17837 FValIsAllZeros = TValIsAllZeros;
17841 if (TValIsAllOnes || FValIsAllZeros) {
17844 if (TValIsAllOnes && FValIsAllZeros)
17846 else if (TValIsAllOnes)
17847 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
17848 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
17849 else if (FValIsAllZeros)
17850 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
17851 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
17853 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
17857 // Try to fold this VSELECT into a MOVSS/MOVSD
17858 if (N->getOpcode() == ISD::VSELECT &&
17859 Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
17860 if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
17861 (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
17862 bool CanFold = false;
17863 unsigned NumElems = Cond.getNumOperands();
17867 if (isZero(Cond.getOperand(0))) {
17870 // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
17871 // fold (vselect <0,-1> -> (movsd A, B)
17872 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17873 CanFold = isAllOnes(Cond.getOperand(i));
17874 } else if (isAllOnes(Cond.getOperand(0))) {
17878 // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
17879 // fold (vselect <-1,0> -> (movsd B, A)
17880 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17881 CanFold = isZero(Cond.getOperand(i));
17885 if (VT == MVT::v4i32 || VT == MVT::v4f32)
17886 return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
17887 return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
17890 if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
17891 // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
17892 // (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
17893 // (v2i64 (bitcast B)))))
17895 // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
17896 // (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
17897 // (v2f64 (bitcast B)))))
17899 // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
17900 // (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
17901 // (v2i64 (bitcast A)))))
17903 // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
17904 // (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
17905 // (v2f64 (bitcast A)))))
17907 CanFold = (isZero(Cond.getOperand(0)) &&
17908 isZero(Cond.getOperand(1)) &&
17909 isAllOnes(Cond.getOperand(2)) &&
17910 isAllOnes(Cond.getOperand(3)));
17912 if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
17913 isAllOnes(Cond.getOperand(1)) &&
17914 isZero(Cond.getOperand(2)) &&
17915 isZero(Cond.getOperand(3))) {
17917 std::swap(LHS, RHS);
17921 EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
17922 SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
17923 SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
17924 SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
17926 return DAG.getNode(ISD::BITCAST, DL, VT, Select);
17932 // If we know that this node is legal then we know that it is going to be
17933 // matched by one of the SSE/AVX BLEND instructions. These instructions only
17934 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
17935 // to simplify previous instructions.
17936 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
17937 !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
17938 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
17940 // Don't optimize vector selects that map to mask-registers.
17944 // Check all uses of that condition operand to check whether it will be
17945 // consumed by non-BLEND instructions, which may depend on all bits are set
17947 for (SDNode::use_iterator I = Cond->use_begin(),
17948 E = Cond->use_end(); I != E; ++I)
17949 if (I->getOpcode() != ISD::VSELECT)
17950 // TODO: Add other opcodes eventually lowered into BLEND.
17953 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
17954 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
17956 APInt KnownZero, KnownOne;
17957 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
17958 DCI.isBeforeLegalizeOps());
17959 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
17960 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
17961 DCI.CommitTargetLoweringOpt(TLO);
17967 // Check whether a boolean test is testing a boolean value generated by
17968 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
17971 // Simplify the following patterns:
17972 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
17973 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
17974 // to (Op EFLAGS Cond)
17976 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
17977 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
17978 // to (Op EFLAGS !Cond)
17980 // where Op could be BRCOND or CMOV.
17982 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
17983 // Quit if not CMP and SUB with its value result used.
17984 if (Cmp.getOpcode() != X86ISD::CMP &&
17985 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
17988 // Quit if not used as a boolean value.
17989 if (CC != X86::COND_E && CC != X86::COND_NE)
17992 // Check CMP operands. One of them should be 0 or 1 and the other should be
17993 // an SetCC or extended from it.
17994 SDValue Op1 = Cmp.getOperand(0);
17995 SDValue Op2 = Cmp.getOperand(1);
17998 const ConstantSDNode* C = nullptr;
17999 bool needOppositeCond = (CC == X86::COND_E);
18000 bool checkAgainstTrue = false; // Is it a comparison against 1?
18002 if ((C = dyn_cast<ConstantSDNode>(Op1)))
18004 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
18006 else // Quit if all operands are not constants.
18009 if (C->getZExtValue() == 1) {
18010 needOppositeCond = !needOppositeCond;
18011 checkAgainstTrue = true;
18012 } else if (C->getZExtValue() != 0)
18013 // Quit if the constant is neither 0 or 1.
18016 bool truncatedToBoolWithAnd = false;
18017 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
18018 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
18019 SetCC.getOpcode() == ISD::TRUNCATE ||
18020 SetCC.getOpcode() == ISD::AND) {
18021 if (SetCC.getOpcode() == ISD::AND) {
18023 ConstantSDNode *CS;
18024 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
18025 CS->getZExtValue() == 1)
18027 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
18028 CS->getZExtValue() == 1)
18032 SetCC = SetCC.getOperand(OpIdx);
18033 truncatedToBoolWithAnd = true;
18035 SetCC = SetCC.getOperand(0);
18038 switch (SetCC.getOpcode()) {
18039 case X86ISD::SETCC_CARRY:
18040 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
18041 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
18042 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
18043 // truncated to i1 using 'and'.
18044 if (checkAgainstTrue && !truncatedToBoolWithAnd)
18046 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
18047 "Invalid use of SETCC_CARRY!");
18049 case X86ISD::SETCC:
18050 // Set the condition code or opposite one if necessary.
18051 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
18052 if (needOppositeCond)
18053 CC = X86::GetOppositeBranchCondition(CC);
18054 return SetCC.getOperand(1);
18055 case X86ISD::CMOV: {
18056 // Check whether false/true value has canonical one, i.e. 0 or 1.
18057 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
18058 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
18059 // Quit if true value is not a constant.
18062 // Quit if false value is not a constant.
18064 SDValue Op = SetCC.getOperand(0);
18065 // Skip 'zext' or 'trunc' node.
18066 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
18067 Op.getOpcode() == ISD::TRUNCATE)
18068 Op = Op.getOperand(0);
18069 // A special case for rdrand/rdseed, where 0 is set if false cond is
18071 if ((Op.getOpcode() != X86ISD::RDRAND &&
18072 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
18075 // Quit if false value is not the constant 0 or 1.
18076 bool FValIsFalse = true;
18077 if (FVal && FVal->getZExtValue() != 0) {
18078 if (FVal->getZExtValue() != 1)
18080 // If FVal is 1, opposite cond is needed.
18081 needOppositeCond = !needOppositeCond;
18082 FValIsFalse = false;
18084 // Quit if TVal is not the constant opposite of FVal.
18085 if (FValIsFalse && TVal->getZExtValue() != 1)
18087 if (!FValIsFalse && TVal->getZExtValue() != 0)
18089 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
18090 if (needOppositeCond)
18091 CC = X86::GetOppositeBranchCondition(CC);
18092 return SetCC.getOperand(3);
18099 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
18100 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
18101 TargetLowering::DAGCombinerInfo &DCI,
18102 const X86Subtarget *Subtarget) {
18105 // If the flag operand isn't dead, don't touch this CMOV.
18106 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
18109 SDValue FalseOp = N->getOperand(0);
18110 SDValue TrueOp = N->getOperand(1);
18111 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
18112 SDValue Cond = N->getOperand(3);
18114 if (CC == X86::COND_E || CC == X86::COND_NE) {
18115 switch (Cond.getOpcode()) {
18119 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
18120 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
18121 return (CC == X86::COND_E) ? FalseOp : TrueOp;
18127 Flags = checkBoolTestSetCCCombine(Cond, CC);
18128 if (Flags.getNode() &&
18129 // Extra check as FCMOV only supports a subset of X86 cond.
18130 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
18131 SDValue Ops[] = { FalseOp, TrueOp,
18132 DAG.getConstant(CC, MVT::i8), Flags };
18133 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
18134 Ops, array_lengthof(Ops));
18137 // If this is a select between two integer constants, try to do some
18138 // optimizations. Note that the operands are ordered the opposite of SELECT
18140 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
18141 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
18142 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
18143 // larger than FalseC (the false value).
18144 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
18145 CC = X86::GetOppositeBranchCondition(CC);
18146 std::swap(TrueC, FalseC);
18147 std::swap(TrueOp, FalseOp);
18150 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
18151 // This is efficient for any integer data type (including i8/i16) and
18153 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
18154 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18155 DAG.getConstant(CC, MVT::i8), Cond);
18157 // Zero extend the condition if needed.
18158 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
18160 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18161 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
18162 DAG.getConstant(ShAmt, MVT::i8));
18163 if (N->getNumValues() == 2) // Dead flag value?
18164 return DCI.CombineTo(N, Cond, SDValue());
18168 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
18169 // for any integer data type, including i8/i16.
18170 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18171 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18172 DAG.getConstant(CC, MVT::i8), Cond);
18174 // Zero extend the condition if needed.
18175 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18176 FalseC->getValueType(0), Cond);
18177 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18178 SDValue(FalseC, 0));
18180 if (N->getNumValues() == 2) // Dead flag value?
18181 return DCI.CombineTo(N, Cond, SDValue());
18185 // Optimize cases that will turn into an LEA instruction. This requires
18186 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18187 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18188 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18189 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18191 bool isFastMultiplier = false;
18193 switch ((unsigned char)Diff) {
18195 case 1: // result = add base, cond
18196 case 2: // result = lea base( , cond*2)
18197 case 3: // result = lea base(cond, cond*2)
18198 case 4: // result = lea base( , cond*4)
18199 case 5: // result = lea base(cond, cond*4)
18200 case 8: // result = lea base( , cond*8)
18201 case 9: // result = lea base(cond, cond*8)
18202 isFastMultiplier = true;
18207 if (isFastMultiplier) {
18208 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18209 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18210 DAG.getConstant(CC, MVT::i8), Cond);
18211 // Zero extend the condition if needed.
18212 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18214 // Scale the condition by the difference.
18216 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18217 DAG.getConstant(Diff, Cond.getValueType()));
18219 // Add the base if non-zero.
18220 if (FalseC->getAPIntValue() != 0)
18221 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18222 SDValue(FalseC, 0));
18223 if (N->getNumValues() == 2) // Dead flag value?
18224 return DCI.CombineTo(N, Cond, SDValue());
18231 // Handle these cases:
18232 // (select (x != c), e, c) -> select (x != c), e, x),
18233 // (select (x == c), c, e) -> select (x == c), x, e)
18234 // where the c is an integer constant, and the "select" is the combination
18235 // of CMOV and CMP.
18237 // The rationale for this change is that the conditional-move from a constant
18238 // needs two instructions, however, conditional-move from a register needs
18239 // only one instruction.
18241 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
18242 // some instruction-combining opportunities. This opt needs to be
18243 // postponed as late as possible.
18245 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
18246 // the DCI.xxxx conditions are provided to postpone the optimization as
18247 // late as possible.
18249 ConstantSDNode *CmpAgainst = nullptr;
18250 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
18251 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
18252 !isa<ConstantSDNode>(Cond.getOperand(0))) {
18254 if (CC == X86::COND_NE &&
18255 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
18256 CC = X86::GetOppositeBranchCondition(CC);
18257 std::swap(TrueOp, FalseOp);
18260 if (CC == X86::COND_E &&
18261 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
18262 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
18263 DAG.getConstant(CC, MVT::i8), Cond };
18264 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
18265 array_lengthof(Ops));
18273 /// PerformMulCombine - Optimize a single multiply with constant into two
18274 /// in order to implement it with two cheaper instructions, e.g.
18275 /// LEA + SHL, LEA + LEA.
18276 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
18277 TargetLowering::DAGCombinerInfo &DCI) {
18278 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
18281 EVT VT = N->getValueType(0);
18282 if (VT != MVT::i64)
18285 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
18288 uint64_t MulAmt = C->getZExtValue();
18289 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
18292 uint64_t MulAmt1 = 0;
18293 uint64_t MulAmt2 = 0;
18294 if ((MulAmt % 9) == 0) {
18296 MulAmt2 = MulAmt / 9;
18297 } else if ((MulAmt % 5) == 0) {
18299 MulAmt2 = MulAmt / 5;
18300 } else if ((MulAmt % 3) == 0) {
18302 MulAmt2 = MulAmt / 3;
18305 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
18308 if (isPowerOf2_64(MulAmt2) &&
18309 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
18310 // If second multiplifer is pow2, issue it first. We want the multiply by
18311 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
18313 std::swap(MulAmt1, MulAmt2);
18316 if (isPowerOf2_64(MulAmt1))
18317 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
18318 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
18320 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
18321 DAG.getConstant(MulAmt1, VT));
18323 if (isPowerOf2_64(MulAmt2))
18324 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
18325 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
18327 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
18328 DAG.getConstant(MulAmt2, VT));
18330 // Do not add new nodes to DAG combiner worklist.
18331 DCI.CombineTo(N, NewMul, false);
18336 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
18337 SDValue N0 = N->getOperand(0);
18338 SDValue N1 = N->getOperand(1);
18339 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
18340 EVT VT = N0.getValueType();
18342 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
18343 // since the result of setcc_c is all zero's or all ones.
18344 if (VT.isInteger() && !VT.isVector() &&
18345 N1C && N0.getOpcode() == ISD::AND &&
18346 N0.getOperand(1).getOpcode() == ISD::Constant) {
18347 SDValue N00 = N0.getOperand(0);
18348 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
18349 ((N00.getOpcode() == ISD::ANY_EXTEND ||
18350 N00.getOpcode() == ISD::ZERO_EXTEND) &&
18351 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
18352 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
18353 APInt ShAmt = N1C->getAPIntValue();
18354 Mask = Mask.shl(ShAmt);
18356 return DAG.getNode(ISD::AND, SDLoc(N), VT,
18357 N00, DAG.getConstant(Mask, VT));
18361 // Hardware support for vector shifts is sparse which makes us scalarize the
18362 // vector operations in many cases. Also, on sandybridge ADD is faster than
18364 // (shl V, 1) -> add V,V
18365 if (isSplatVector(N1.getNode())) {
18366 assert(N0.getValueType().isVector() && "Invalid vector shift type");
18367 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
18368 // We shift all of the values by one. In many cases we do not have
18369 // hardware support for this operation. This is better expressed as an ADD
18371 if (N1C && (1 == N1C->getZExtValue())) {
18372 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
18379 /// \brief Returns a vector of 0s if the node in input is a vector logical
18380 /// shift by a constant amount which is known to be bigger than or equal
18381 /// to the vector element size in bits.
18382 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
18383 const X86Subtarget *Subtarget) {
18384 EVT VT = N->getValueType(0);
18386 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
18387 (!Subtarget->hasInt256() ||
18388 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
18391 SDValue Amt = N->getOperand(1);
18393 if (isSplatVector(Amt.getNode())) {
18394 SDValue SclrAmt = Amt->getOperand(0);
18395 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
18396 APInt ShiftAmt = C->getAPIntValue();
18397 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
18399 // SSE2/AVX2 logical shifts always return a vector of 0s
18400 // if the shift amount is bigger than or equal to
18401 // the element size. The constant shift amount will be
18402 // encoded as a 8-bit immediate.
18403 if (ShiftAmt.trunc(8).uge(MaxAmount))
18404 return getZeroVector(VT, Subtarget, DAG, DL);
18411 /// PerformShiftCombine - Combine shifts.
18412 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
18413 TargetLowering::DAGCombinerInfo &DCI,
18414 const X86Subtarget *Subtarget) {
18415 if (N->getOpcode() == ISD::SHL) {
18416 SDValue V = PerformSHLCombine(N, DAG);
18417 if (V.getNode()) return V;
18420 if (N->getOpcode() != ISD::SRA) {
18421 // Try to fold this logical shift into a zero vector.
18422 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
18423 if (V.getNode()) return V;
18429 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
18430 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
18431 // and friends. Likewise for OR -> CMPNEQSS.
18432 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
18433 TargetLowering::DAGCombinerInfo &DCI,
18434 const X86Subtarget *Subtarget) {
18437 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
18438 // we're requiring SSE2 for both.
18439 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
18440 SDValue N0 = N->getOperand(0);
18441 SDValue N1 = N->getOperand(1);
18442 SDValue CMP0 = N0->getOperand(1);
18443 SDValue CMP1 = N1->getOperand(1);
18446 // The SETCCs should both refer to the same CMP.
18447 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
18450 SDValue CMP00 = CMP0->getOperand(0);
18451 SDValue CMP01 = CMP0->getOperand(1);
18452 EVT VT = CMP00.getValueType();
18454 if (VT == MVT::f32 || VT == MVT::f64) {
18455 bool ExpectingFlags = false;
18456 // Check for any users that want flags:
18457 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
18458 !ExpectingFlags && UI != UE; ++UI)
18459 switch (UI->getOpcode()) {
18464 ExpectingFlags = true;
18466 case ISD::CopyToReg:
18467 case ISD::SIGN_EXTEND:
18468 case ISD::ZERO_EXTEND:
18469 case ISD::ANY_EXTEND:
18473 if (!ExpectingFlags) {
18474 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
18475 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
18477 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
18478 X86::CondCode tmp = cc0;
18483 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
18484 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
18485 // FIXME: need symbolic constants for these magic numbers.
18486 // See X86ATTInstPrinter.cpp:printSSECC().
18487 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
18488 if (Subtarget->hasAVX512()) {
18489 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
18490 CMP01, DAG.getConstant(x86cc, MVT::i8));
18491 if (N->getValueType(0) != MVT::i1)
18492 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
18496 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
18497 CMP00.getValueType(), CMP00, CMP01,
18498 DAG.getConstant(x86cc, MVT::i8));
18500 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
18501 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
18503 if (is64BitFP && !Subtarget->is64Bit()) {
18504 // On a 32-bit target, we cannot bitcast the 64-bit float to a
18505 // 64-bit integer, since that's not a legal type. Since
18506 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
18507 // bits, but can do this little dance to extract the lowest 32 bits
18508 // and work with those going forward.
18509 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
18511 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
18513 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
18514 Vector32, DAG.getIntPtrConstant(0));
18518 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
18519 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
18520 DAG.getConstant(1, IntVT));
18521 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
18522 return OneBitOfTruth;
18530 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
18531 /// so it can be folded inside ANDNP.
18532 static bool CanFoldXORWithAllOnes(const SDNode *N) {
18533 EVT VT = N->getValueType(0);
18535 // Match direct AllOnes for 128 and 256-bit vectors
18536 if (ISD::isBuildVectorAllOnes(N))
18539 // Look through a bit convert.
18540 if (N->getOpcode() == ISD::BITCAST)
18541 N = N->getOperand(0).getNode();
18543 // Sometimes the operand may come from a insert_subvector building a 256-bit
18545 if (VT.is256BitVector() &&
18546 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
18547 SDValue V1 = N->getOperand(0);
18548 SDValue V2 = N->getOperand(1);
18550 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
18551 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
18552 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
18553 ISD::isBuildVectorAllOnes(V2.getNode()))
18560 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
18561 // register. In most cases we actually compare or select YMM-sized registers
18562 // and mixing the two types creates horrible code. This method optimizes
18563 // some of the transition sequences.
18564 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
18565 TargetLowering::DAGCombinerInfo &DCI,
18566 const X86Subtarget *Subtarget) {
18567 EVT VT = N->getValueType(0);
18568 if (!VT.is256BitVector())
18571 assert((N->getOpcode() == ISD::ANY_EXTEND ||
18572 N->getOpcode() == ISD::ZERO_EXTEND ||
18573 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
18575 SDValue Narrow = N->getOperand(0);
18576 EVT NarrowVT = Narrow->getValueType(0);
18577 if (!NarrowVT.is128BitVector())
18580 if (Narrow->getOpcode() != ISD::XOR &&
18581 Narrow->getOpcode() != ISD::AND &&
18582 Narrow->getOpcode() != ISD::OR)
18585 SDValue N0 = Narrow->getOperand(0);
18586 SDValue N1 = Narrow->getOperand(1);
18589 // The Left side has to be a trunc.
18590 if (N0.getOpcode() != ISD::TRUNCATE)
18593 // The type of the truncated inputs.
18594 EVT WideVT = N0->getOperand(0)->getValueType(0);
18598 // The right side has to be a 'trunc' or a constant vector.
18599 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
18600 bool RHSConst = (isSplatVector(N1.getNode()) &&
18601 isa<ConstantSDNode>(N1->getOperand(0)));
18602 if (!RHSTrunc && !RHSConst)
18605 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18607 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
18610 // Set N0 and N1 to hold the inputs to the new wide operation.
18611 N0 = N0->getOperand(0);
18613 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
18614 N1->getOperand(0));
18615 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
18616 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
18617 } else if (RHSTrunc) {
18618 N1 = N1->getOperand(0);
18621 // Generate the wide operation.
18622 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
18623 unsigned Opcode = N->getOpcode();
18625 case ISD::ANY_EXTEND:
18627 case ISD::ZERO_EXTEND: {
18628 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
18629 APInt Mask = APInt::getAllOnesValue(InBits);
18630 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
18631 return DAG.getNode(ISD::AND, DL, VT,
18632 Op, DAG.getConstant(Mask, VT));
18634 case ISD::SIGN_EXTEND:
18635 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
18636 Op, DAG.getValueType(NarrowVT));
18638 llvm_unreachable("Unexpected opcode");
18642 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
18643 TargetLowering::DAGCombinerInfo &DCI,
18644 const X86Subtarget *Subtarget) {
18645 EVT VT = N->getValueType(0);
18646 if (DCI.isBeforeLegalizeOps())
18649 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18653 // Create BEXTR instructions
18654 // BEXTR is ((X >> imm) & (2**size-1))
18655 if (VT == MVT::i32 || VT == MVT::i64) {
18656 SDValue N0 = N->getOperand(0);
18657 SDValue N1 = N->getOperand(1);
18660 // Check for BEXTR.
18661 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
18662 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
18663 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
18664 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
18665 if (MaskNode && ShiftNode) {
18666 uint64_t Mask = MaskNode->getZExtValue();
18667 uint64_t Shift = ShiftNode->getZExtValue();
18668 if (isMask_64(Mask)) {
18669 uint64_t MaskSize = CountPopulation_64(Mask);
18670 if (Shift + MaskSize <= VT.getSizeInBits())
18671 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
18672 DAG.getConstant(Shift | (MaskSize << 8), VT));
18680 // Want to form ANDNP nodes:
18681 // 1) In the hopes of then easily combining them with OR and AND nodes
18682 // to form PBLEND/PSIGN.
18683 // 2) To match ANDN packed intrinsics
18684 if (VT != MVT::v2i64 && VT != MVT::v4i64)
18687 SDValue N0 = N->getOperand(0);
18688 SDValue N1 = N->getOperand(1);
18691 // Check LHS for vnot
18692 if (N0.getOpcode() == ISD::XOR &&
18693 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
18694 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
18695 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
18697 // Check RHS for vnot
18698 if (N1.getOpcode() == ISD::XOR &&
18699 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
18700 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
18701 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
18706 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
18707 TargetLowering::DAGCombinerInfo &DCI,
18708 const X86Subtarget *Subtarget) {
18709 if (DCI.isBeforeLegalizeOps())
18712 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18716 SDValue N0 = N->getOperand(0);
18717 SDValue N1 = N->getOperand(1);
18718 EVT VT = N->getValueType(0);
18720 // look for psign/blend
18721 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
18722 if (!Subtarget->hasSSSE3() ||
18723 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
18726 // Canonicalize pandn to RHS
18727 if (N0.getOpcode() == X86ISD::ANDNP)
18729 // or (and (m, y), (pandn m, x))
18730 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
18731 SDValue Mask = N1.getOperand(0);
18732 SDValue X = N1.getOperand(1);
18734 if (N0.getOperand(0) == Mask)
18735 Y = N0.getOperand(1);
18736 if (N0.getOperand(1) == Mask)
18737 Y = N0.getOperand(0);
18739 // Check to see if the mask appeared in both the AND and ANDNP and
18743 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
18744 // Look through mask bitcast.
18745 if (Mask.getOpcode() == ISD::BITCAST)
18746 Mask = Mask.getOperand(0);
18747 if (X.getOpcode() == ISD::BITCAST)
18748 X = X.getOperand(0);
18749 if (Y.getOpcode() == ISD::BITCAST)
18750 Y = Y.getOperand(0);
18752 EVT MaskVT = Mask.getValueType();
18754 // Validate that the Mask operand is a vector sra node.
18755 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
18756 // there is no psrai.b
18757 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
18758 unsigned SraAmt = ~0;
18759 if (Mask.getOpcode() == ISD::SRA) {
18760 SDValue Amt = Mask.getOperand(1);
18761 if (isSplatVector(Amt.getNode())) {
18762 SDValue SclrAmt = Amt->getOperand(0);
18763 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
18764 SraAmt = C->getZExtValue();
18766 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
18767 SDValue SraC = Mask.getOperand(1);
18768 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
18770 if ((SraAmt + 1) != EltBits)
18775 // Now we know we at least have a plendvb with the mask val. See if
18776 // we can form a psignb/w/d.
18777 // psign = x.type == y.type == mask.type && y = sub(0, x);
18778 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
18779 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
18780 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
18781 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
18782 "Unsupported VT for PSIGN");
18783 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
18784 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18786 // PBLENDVB only available on SSE 4.1
18787 if (!Subtarget->hasSSE41())
18790 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
18792 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
18793 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
18794 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
18795 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
18796 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18800 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
18803 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
18804 MachineFunction &MF = DAG.getMachineFunction();
18805 bool OptForSize = MF.getFunction()->getAttributes().
18806 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
18808 // SHLD/SHRD instructions have lower register pressure, but on some
18809 // platforms they have higher latency than the equivalent
18810 // series of shifts/or that would otherwise be generated.
18811 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
18812 // have higher latencies and we are not optimizing for size.
18813 if (!OptForSize && Subtarget->isSHLDSlow())
18816 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
18818 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
18820 if (!N0.hasOneUse() || !N1.hasOneUse())
18823 SDValue ShAmt0 = N0.getOperand(1);
18824 if (ShAmt0.getValueType() != MVT::i8)
18826 SDValue ShAmt1 = N1.getOperand(1);
18827 if (ShAmt1.getValueType() != MVT::i8)
18829 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
18830 ShAmt0 = ShAmt0.getOperand(0);
18831 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
18832 ShAmt1 = ShAmt1.getOperand(0);
18835 unsigned Opc = X86ISD::SHLD;
18836 SDValue Op0 = N0.getOperand(0);
18837 SDValue Op1 = N1.getOperand(0);
18838 if (ShAmt0.getOpcode() == ISD::SUB) {
18839 Opc = X86ISD::SHRD;
18840 std::swap(Op0, Op1);
18841 std::swap(ShAmt0, ShAmt1);
18844 unsigned Bits = VT.getSizeInBits();
18845 if (ShAmt1.getOpcode() == ISD::SUB) {
18846 SDValue Sum = ShAmt1.getOperand(0);
18847 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
18848 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
18849 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
18850 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
18851 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
18852 return DAG.getNode(Opc, DL, VT,
18854 DAG.getNode(ISD::TRUNCATE, DL,
18857 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
18858 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
18860 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
18861 return DAG.getNode(Opc, DL, VT,
18862 N0.getOperand(0), N1.getOperand(0),
18863 DAG.getNode(ISD::TRUNCATE, DL,
18870 // Generate NEG and CMOV for integer abs.
18871 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
18872 EVT VT = N->getValueType(0);
18874 // Since X86 does not have CMOV for 8-bit integer, we don't convert
18875 // 8-bit integer abs to NEG and CMOV.
18876 if (VT.isInteger() && VT.getSizeInBits() == 8)
18879 SDValue N0 = N->getOperand(0);
18880 SDValue N1 = N->getOperand(1);
18883 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
18884 // and change it to SUB and CMOV.
18885 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
18886 N0.getOpcode() == ISD::ADD &&
18887 N0.getOperand(1) == N1 &&
18888 N1.getOpcode() == ISD::SRA &&
18889 N1.getOperand(0) == N0.getOperand(0))
18890 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
18891 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
18892 // Generate SUB & CMOV.
18893 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
18894 DAG.getConstant(0, VT), N0.getOperand(0));
18896 SDValue Ops[] = { N0.getOperand(0), Neg,
18897 DAG.getConstant(X86::COND_GE, MVT::i8),
18898 SDValue(Neg.getNode(), 1) };
18899 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
18900 Ops, array_lengthof(Ops));
18905 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
18906 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
18907 TargetLowering::DAGCombinerInfo &DCI,
18908 const X86Subtarget *Subtarget) {
18909 if (DCI.isBeforeLegalizeOps())
18912 if (Subtarget->hasCMov()) {
18913 SDValue RV = performIntegerAbsCombine(N, DAG);
18921 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
18922 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
18923 TargetLowering::DAGCombinerInfo &DCI,
18924 const X86Subtarget *Subtarget) {
18925 LoadSDNode *Ld = cast<LoadSDNode>(N);
18926 EVT RegVT = Ld->getValueType(0);
18927 EVT MemVT = Ld->getMemoryVT();
18929 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18930 unsigned RegSz = RegVT.getSizeInBits();
18932 // On Sandybridge unaligned 256bit loads are inefficient.
18933 ISD::LoadExtType Ext = Ld->getExtensionType();
18934 unsigned Alignment = Ld->getAlignment();
18935 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
18936 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
18937 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
18938 unsigned NumElems = RegVT.getVectorNumElements();
18942 SDValue Ptr = Ld->getBasePtr();
18943 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
18945 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18947 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18948 Ld->getPointerInfo(), Ld->isVolatile(),
18949 Ld->isNonTemporal(), Ld->isInvariant(),
18951 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18952 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18953 Ld->getPointerInfo(), Ld->isVolatile(),
18954 Ld->isNonTemporal(), Ld->isInvariant(),
18955 std::min(16U, Alignment));
18956 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18958 Load2.getValue(1));
18960 SDValue NewVec = DAG.getUNDEF(RegVT);
18961 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
18962 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
18963 return DCI.CombineTo(N, NewVec, TF, true);
18966 // If this is a vector EXT Load then attempt to optimize it using a
18967 // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
18968 // expansion is still better than scalar code.
18969 // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
18970 // emit a shuffle and a arithmetic shift.
18971 // TODO: It is possible to support ZExt by zeroing the undef values
18972 // during the shuffle phase or after the shuffle.
18973 if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
18974 (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
18975 assert(MemVT != RegVT && "Cannot extend to the same type");
18976 assert(MemVT.isVector() && "Must load a vector from memory");
18978 unsigned NumElems = RegVT.getVectorNumElements();
18979 unsigned MemSz = MemVT.getSizeInBits();
18980 assert(RegSz > MemSz && "Register size must be greater than the mem size");
18982 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
18985 // All sizes must be a power of two.
18986 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
18989 // Attempt to load the original value using scalar loads.
18990 // Find the largest scalar type that divides the total loaded size.
18991 MVT SclrLoadTy = MVT::i8;
18992 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
18993 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
18994 MVT Tp = (MVT::SimpleValueType)tp;
18995 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
19000 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19001 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
19003 SclrLoadTy = MVT::f64;
19005 // Calculate the number of scalar loads that we need to perform
19006 // in order to load our vector from memory.
19007 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
19008 if (Ext == ISD::SEXTLOAD && NumLoads > 1)
19011 unsigned loadRegZize = RegSz;
19012 if (Ext == ISD::SEXTLOAD && RegSz == 256)
19015 // Represent our vector as a sequence of elements which are the
19016 // largest scalar that we can load.
19017 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
19018 loadRegZize/SclrLoadTy.getSizeInBits());
19020 // Represent the data using the same element type that is stored in
19021 // memory. In practice, we ''widen'' MemVT.
19023 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19024 loadRegZize/MemVT.getScalarType().getSizeInBits());
19026 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
19027 "Invalid vector type");
19029 // We can't shuffle using an illegal type.
19030 if (!TLI.isTypeLegal(WideVecVT))
19033 SmallVector<SDValue, 8> Chains;
19034 SDValue Ptr = Ld->getBasePtr();
19035 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
19036 TLI.getPointerTy());
19037 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
19039 for (unsigned i = 0; i < NumLoads; ++i) {
19040 // Perform a single load.
19041 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
19042 Ptr, Ld->getPointerInfo(),
19043 Ld->isVolatile(), Ld->isNonTemporal(),
19044 Ld->isInvariant(), Ld->getAlignment());
19045 Chains.push_back(ScalarLoad.getValue(1));
19046 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
19047 // another round of DAGCombining.
19049 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
19051 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
19052 ScalarLoad, DAG.getIntPtrConstant(i));
19054 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19057 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
19060 // Bitcast the loaded value to a vector of the original element type, in
19061 // the size of the target vector type.
19062 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
19063 unsigned SizeRatio = RegSz/MemSz;
19065 if (Ext == ISD::SEXTLOAD) {
19066 // If we have SSE4.1 we can directly emit a VSEXT node.
19067 if (Subtarget->hasSSE41()) {
19068 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
19069 return DCI.CombineTo(N, Sext, TF, true);
19072 // Otherwise we'll shuffle the small elements in the high bits of the
19073 // larger type and perform an arithmetic shift. If the shift is not legal
19074 // it's better to scalarize.
19075 if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
19078 // Redistribute the loaded elements into the different locations.
19079 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19080 for (unsigned i = 0; i != NumElems; ++i)
19081 ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
19083 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19084 DAG.getUNDEF(WideVecVT),
19087 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19089 // Build the arithmetic shift.
19090 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
19091 MemVT.getVectorElementType().getSizeInBits();
19092 Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
19093 DAG.getConstant(Amt, RegVT));
19095 return DCI.CombineTo(N, Shuff, TF, true);
19098 // Redistribute the loaded elements into the different locations.
19099 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19100 for (unsigned i = 0; i != NumElems; ++i)
19101 ShuffleVec[i*SizeRatio] = i;
19103 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19104 DAG.getUNDEF(WideVecVT),
19107 // Bitcast to the requested type.
19108 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19109 // Replace the original load with the new sequence
19110 // and return the new chain.
19111 return DCI.CombineTo(N, Shuff, TF, true);
19117 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
19118 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
19119 const X86Subtarget *Subtarget) {
19120 StoreSDNode *St = cast<StoreSDNode>(N);
19121 EVT VT = St->getValue().getValueType();
19122 EVT StVT = St->getMemoryVT();
19124 SDValue StoredVal = St->getOperand(1);
19125 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19127 // If we are saving a concatenation of two XMM registers, perform two stores.
19128 // On Sandy Bridge, 256-bit memory operations are executed by two
19129 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
19130 // memory operation.
19131 unsigned Alignment = St->getAlignment();
19132 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
19133 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
19134 StVT == VT && !IsAligned) {
19135 unsigned NumElems = VT.getVectorNumElements();
19139 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
19140 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
19142 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
19143 SDValue Ptr0 = St->getBasePtr();
19144 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
19146 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
19147 St->getPointerInfo(), St->isVolatile(),
19148 St->isNonTemporal(), Alignment);
19149 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
19150 St->getPointerInfo(), St->isVolatile(),
19151 St->isNonTemporal(),
19152 std::min(16U, Alignment));
19153 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
19156 // Optimize trunc store (of multiple scalars) to shuffle and store.
19157 // First, pack all of the elements in one place. Next, store to memory
19158 // in fewer chunks.
19159 if (St->isTruncatingStore() && VT.isVector()) {
19160 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19161 unsigned NumElems = VT.getVectorNumElements();
19162 assert(StVT != VT && "Cannot truncate to the same type");
19163 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
19164 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
19166 // From, To sizes and ElemCount must be pow of two
19167 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
19168 // We are going to use the original vector elt for storing.
19169 // Accumulated smaller vector elements must be a multiple of the store size.
19170 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
19172 unsigned SizeRatio = FromSz / ToSz;
19174 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
19176 // Create a type on which we perform the shuffle
19177 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
19178 StVT.getScalarType(), NumElems*SizeRatio);
19180 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
19182 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
19183 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19184 for (unsigned i = 0; i != NumElems; ++i)
19185 ShuffleVec[i] = i * SizeRatio;
19187 // Can't shuffle using an illegal type.
19188 if (!TLI.isTypeLegal(WideVecVT))
19191 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
19192 DAG.getUNDEF(WideVecVT),
19194 // At this point all of the data is stored at the bottom of the
19195 // register. We now need to save it to mem.
19197 // Find the largest store unit
19198 MVT StoreType = MVT::i8;
19199 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19200 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19201 MVT Tp = (MVT::SimpleValueType)tp;
19202 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
19206 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19207 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
19208 (64 <= NumElems * ToSz))
19209 StoreType = MVT::f64;
19211 // Bitcast the original vector into a vector of store-size units
19212 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
19213 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
19214 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
19215 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
19216 SmallVector<SDValue, 8> Chains;
19217 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
19218 TLI.getPointerTy());
19219 SDValue Ptr = St->getBasePtr();
19221 // Perform one or more big stores into memory.
19222 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
19223 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
19224 StoreType, ShuffWide,
19225 DAG.getIntPtrConstant(i));
19226 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
19227 St->getPointerInfo(), St->isVolatile(),
19228 St->isNonTemporal(), St->getAlignment());
19229 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19230 Chains.push_back(Ch);
19233 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
19237 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
19238 // the FP state in cases where an emms may be missing.
19239 // A preferable solution to the general problem is to figure out the right
19240 // places to insert EMMS. This qualifies as a quick hack.
19242 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
19243 if (VT.getSizeInBits() != 64)
19246 const Function *F = DAG.getMachineFunction().getFunction();
19247 bool NoImplicitFloatOps = F->getAttributes().
19248 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
19249 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
19250 && Subtarget->hasSSE2();
19251 if ((VT.isVector() ||
19252 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
19253 isa<LoadSDNode>(St->getValue()) &&
19254 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
19255 St->getChain().hasOneUse() && !St->isVolatile()) {
19256 SDNode* LdVal = St->getValue().getNode();
19257 LoadSDNode *Ld = nullptr;
19258 int TokenFactorIndex = -1;
19259 SmallVector<SDValue, 8> Ops;
19260 SDNode* ChainVal = St->getChain().getNode();
19261 // Must be a store of a load. We currently handle two cases: the load
19262 // is a direct child, and it's under an intervening TokenFactor. It is
19263 // possible to dig deeper under nested TokenFactors.
19264 if (ChainVal == LdVal)
19265 Ld = cast<LoadSDNode>(St->getChain());
19266 else if (St->getValue().hasOneUse() &&
19267 ChainVal->getOpcode() == ISD::TokenFactor) {
19268 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
19269 if (ChainVal->getOperand(i).getNode() == LdVal) {
19270 TokenFactorIndex = i;
19271 Ld = cast<LoadSDNode>(St->getValue());
19273 Ops.push_back(ChainVal->getOperand(i));
19277 if (!Ld || !ISD::isNormalLoad(Ld))
19280 // If this is not the MMX case, i.e. we are just turning i64 load/store
19281 // into f64 load/store, avoid the transformation if there are multiple
19282 // uses of the loaded value.
19283 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
19288 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
19289 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
19291 if (Subtarget->is64Bit() || F64IsLegal) {
19292 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
19293 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
19294 Ld->getPointerInfo(), Ld->isVolatile(),
19295 Ld->isNonTemporal(), Ld->isInvariant(),
19296 Ld->getAlignment());
19297 SDValue NewChain = NewLd.getValue(1);
19298 if (TokenFactorIndex != -1) {
19299 Ops.push_back(NewChain);
19300 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
19303 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
19304 St->getPointerInfo(),
19305 St->isVolatile(), St->isNonTemporal(),
19306 St->getAlignment());
19309 // Otherwise, lower to two pairs of 32-bit loads / stores.
19310 SDValue LoAddr = Ld->getBasePtr();
19311 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
19312 DAG.getConstant(4, MVT::i32));
19314 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
19315 Ld->getPointerInfo(),
19316 Ld->isVolatile(), Ld->isNonTemporal(),
19317 Ld->isInvariant(), Ld->getAlignment());
19318 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
19319 Ld->getPointerInfo().getWithOffset(4),
19320 Ld->isVolatile(), Ld->isNonTemporal(),
19322 MinAlign(Ld->getAlignment(), 4));
19324 SDValue NewChain = LoLd.getValue(1);
19325 if (TokenFactorIndex != -1) {
19326 Ops.push_back(LoLd);
19327 Ops.push_back(HiLd);
19328 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
19332 LoAddr = St->getBasePtr();
19333 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
19334 DAG.getConstant(4, MVT::i32));
19336 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
19337 St->getPointerInfo(),
19338 St->isVolatile(), St->isNonTemporal(),
19339 St->getAlignment());
19340 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
19341 St->getPointerInfo().getWithOffset(4),
19343 St->isNonTemporal(),
19344 MinAlign(St->getAlignment(), 4));
19345 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
19350 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
19351 /// and return the operands for the horizontal operation in LHS and RHS. A
19352 /// horizontal operation performs the binary operation on successive elements
19353 /// of its first operand, then on successive elements of its second operand,
19354 /// returning the resulting values in a vector. For example, if
19355 /// A = < float a0, float a1, float a2, float a3 >
19357 /// B = < float b0, float b1, float b2, float b3 >
19358 /// then the result of doing a horizontal operation on A and B is
19359 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
19360 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
19361 /// A horizontal-op B, for some already available A and B, and if so then LHS is
19362 /// set to A, RHS to B, and the routine returns 'true'.
19363 /// Note that the binary operation should have the property that if one of the
19364 /// operands is UNDEF then the result is UNDEF.
19365 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
19366 // Look for the following pattern: if
19367 // A = < float a0, float a1, float a2, float a3 >
19368 // B = < float b0, float b1, float b2, float b3 >
19370 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
19371 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
19372 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
19373 // which is A horizontal-op B.
19375 // At least one of the operands should be a vector shuffle.
19376 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
19377 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
19380 MVT VT = LHS.getSimpleValueType();
19382 assert((VT.is128BitVector() || VT.is256BitVector()) &&
19383 "Unsupported vector type for horizontal add/sub");
19385 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
19386 // operate independently on 128-bit lanes.
19387 unsigned NumElts = VT.getVectorNumElements();
19388 unsigned NumLanes = VT.getSizeInBits()/128;
19389 unsigned NumLaneElts = NumElts / NumLanes;
19390 assert((NumLaneElts % 2 == 0) &&
19391 "Vector type should have an even number of elements in each lane");
19392 unsigned HalfLaneElts = NumLaneElts/2;
19394 // View LHS in the form
19395 // LHS = VECTOR_SHUFFLE A, B, LMask
19396 // If LHS is not a shuffle then pretend it is the shuffle
19397 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
19398 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
19401 SmallVector<int, 16> LMask(NumElts);
19402 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19403 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
19404 A = LHS.getOperand(0);
19405 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
19406 B = LHS.getOperand(1);
19407 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
19408 std::copy(Mask.begin(), Mask.end(), LMask.begin());
19410 if (LHS.getOpcode() != ISD::UNDEF)
19412 for (unsigned i = 0; i != NumElts; ++i)
19416 // Likewise, view RHS in the form
19417 // RHS = VECTOR_SHUFFLE C, D, RMask
19419 SmallVector<int, 16> RMask(NumElts);
19420 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19421 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
19422 C = RHS.getOperand(0);
19423 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
19424 D = RHS.getOperand(1);
19425 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
19426 std::copy(Mask.begin(), Mask.end(), RMask.begin());
19428 if (RHS.getOpcode() != ISD::UNDEF)
19430 for (unsigned i = 0; i != NumElts; ++i)
19434 // Check that the shuffles are both shuffling the same vectors.
19435 if (!(A == C && B == D) && !(A == D && B == C))
19438 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
19439 if (!A.getNode() && !B.getNode())
19442 // If A and B occur in reverse order in RHS, then "swap" them (which means
19443 // rewriting the mask).
19445 CommuteVectorShuffleMask(RMask, NumElts);
19447 // At this point LHS and RHS are equivalent to
19448 // LHS = VECTOR_SHUFFLE A, B, LMask
19449 // RHS = VECTOR_SHUFFLE A, B, RMask
19450 // Check that the masks correspond to performing a horizontal operation.
19451 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
19452 for (unsigned i = 0; i != NumLaneElts; ++i) {
19453 int LIdx = LMask[i+l], RIdx = RMask[i+l];
19455 // Ignore any UNDEF components.
19456 if (LIdx < 0 || RIdx < 0 ||
19457 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
19458 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
19461 // Check that successive elements are being operated on. If not, this is
19462 // not a horizontal operation.
19463 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
19464 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
19465 if (!(LIdx == Index && RIdx == Index + 1) &&
19466 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
19471 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
19472 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
19476 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
19477 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
19478 const X86Subtarget *Subtarget) {
19479 EVT VT = N->getValueType(0);
19480 SDValue LHS = N->getOperand(0);
19481 SDValue RHS = N->getOperand(1);
19483 // Try to synthesize horizontal adds from adds of shuffles.
19484 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19485 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19486 isHorizontalBinOp(LHS, RHS, true))
19487 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
19491 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
19492 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
19493 const X86Subtarget *Subtarget) {
19494 EVT VT = N->getValueType(0);
19495 SDValue LHS = N->getOperand(0);
19496 SDValue RHS = N->getOperand(1);
19498 // Try to synthesize horizontal subs from subs of shuffles.
19499 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19500 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19501 isHorizontalBinOp(LHS, RHS, false))
19502 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
19506 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
19507 /// X86ISD::FXOR nodes.
19508 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
19509 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
19510 // F[X]OR(0.0, x) -> x
19511 // F[X]OR(x, 0.0) -> x
19512 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19513 if (C->getValueAPF().isPosZero())
19514 return N->getOperand(1);
19515 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19516 if (C->getValueAPF().isPosZero())
19517 return N->getOperand(0);
19521 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
19522 /// X86ISD::FMAX nodes.
19523 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
19524 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
19526 // Only perform optimizations if UnsafeMath is used.
19527 if (!DAG.getTarget().Options.UnsafeFPMath)
19530 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
19531 // into FMINC and FMAXC, which are Commutative operations.
19532 unsigned NewOp = 0;
19533 switch (N->getOpcode()) {
19534 default: llvm_unreachable("unknown opcode");
19535 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
19536 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
19539 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
19540 N->getOperand(0), N->getOperand(1));
19543 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
19544 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
19545 // FAND(0.0, x) -> 0.0
19546 // FAND(x, 0.0) -> 0.0
19547 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19548 if (C->getValueAPF().isPosZero())
19549 return N->getOperand(0);
19550 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19551 if (C->getValueAPF().isPosZero())
19552 return N->getOperand(1);
19556 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
19557 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
19558 // FANDN(x, 0.0) -> 0.0
19559 // FANDN(0.0, x) -> x
19560 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19561 if (C->getValueAPF().isPosZero())
19562 return N->getOperand(1);
19563 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19564 if (C->getValueAPF().isPosZero())
19565 return N->getOperand(1);
19569 static SDValue PerformBTCombine(SDNode *N,
19571 TargetLowering::DAGCombinerInfo &DCI) {
19572 // BT ignores high bits in the bit index operand.
19573 SDValue Op1 = N->getOperand(1);
19574 if (Op1.hasOneUse()) {
19575 unsigned BitWidth = Op1.getValueSizeInBits();
19576 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
19577 APInt KnownZero, KnownOne;
19578 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
19579 !DCI.isBeforeLegalizeOps());
19580 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19581 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
19582 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
19583 DCI.CommitTargetLoweringOpt(TLO);
19588 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
19589 SDValue Op = N->getOperand(0);
19590 if (Op.getOpcode() == ISD::BITCAST)
19591 Op = Op.getOperand(0);
19592 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
19593 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
19594 VT.getVectorElementType().getSizeInBits() ==
19595 OpVT.getVectorElementType().getSizeInBits()) {
19596 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
19601 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
19602 const X86Subtarget *Subtarget) {
19603 EVT VT = N->getValueType(0);
19604 if (!VT.isVector())
19607 SDValue N0 = N->getOperand(0);
19608 SDValue N1 = N->getOperand(1);
19609 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
19612 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
19613 // both SSE and AVX2 since there is no sign-extended shift right
19614 // operation on a vector with 64-bit elements.
19615 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
19616 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
19617 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
19618 N0.getOpcode() == ISD::SIGN_EXTEND)) {
19619 SDValue N00 = N0.getOperand(0);
19621 // EXTLOAD has a better solution on AVX2,
19622 // it may be replaced with X86ISD::VSEXT node.
19623 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
19624 if (!ISD::isNormalLoad(N00.getNode()))
19627 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
19628 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
19630 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
19636 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
19637 TargetLowering::DAGCombinerInfo &DCI,
19638 const X86Subtarget *Subtarget) {
19639 if (!DCI.isBeforeLegalizeOps())
19642 if (!Subtarget->hasFp256())
19645 EVT VT = N->getValueType(0);
19646 if (VT.isVector() && VT.getSizeInBits() == 256) {
19647 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19655 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
19656 const X86Subtarget* Subtarget) {
19658 EVT VT = N->getValueType(0);
19660 // Let legalize expand this if it isn't a legal type yet.
19661 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19664 EVT ScalarVT = VT.getScalarType();
19665 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
19666 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
19669 SDValue A = N->getOperand(0);
19670 SDValue B = N->getOperand(1);
19671 SDValue C = N->getOperand(2);
19673 bool NegA = (A.getOpcode() == ISD::FNEG);
19674 bool NegB = (B.getOpcode() == ISD::FNEG);
19675 bool NegC = (C.getOpcode() == ISD::FNEG);
19677 // Negative multiplication when NegA xor NegB
19678 bool NegMul = (NegA != NegB);
19680 A = A.getOperand(0);
19682 B = B.getOperand(0);
19684 C = C.getOperand(0);
19688 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
19690 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
19692 return DAG.getNode(Opcode, dl, VT, A, B, C);
19695 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
19696 TargetLowering::DAGCombinerInfo &DCI,
19697 const X86Subtarget *Subtarget) {
19698 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
19699 // (and (i32 x86isd::setcc_carry), 1)
19700 // This eliminates the zext. This transformation is necessary because
19701 // ISD::SETCC is always legalized to i8.
19703 SDValue N0 = N->getOperand(0);
19704 EVT VT = N->getValueType(0);
19706 if (N0.getOpcode() == ISD::AND &&
19708 N0.getOperand(0).hasOneUse()) {
19709 SDValue N00 = N0.getOperand(0);
19710 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19711 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19712 if (!C || C->getZExtValue() != 1)
19714 return DAG.getNode(ISD::AND, dl, VT,
19715 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19716 N00.getOperand(0), N00.getOperand(1)),
19717 DAG.getConstant(1, VT));
19721 if (N0.getOpcode() == ISD::TRUNCATE &&
19723 N0.getOperand(0).hasOneUse()) {
19724 SDValue N00 = N0.getOperand(0);
19725 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19726 return DAG.getNode(ISD::AND, dl, VT,
19727 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19728 N00.getOperand(0), N00.getOperand(1)),
19729 DAG.getConstant(1, VT));
19732 if (VT.is256BitVector()) {
19733 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19741 // Optimize x == -y --> x+y == 0
19742 // x != -y --> x+y != 0
19743 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
19744 const X86Subtarget* Subtarget) {
19745 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
19746 SDValue LHS = N->getOperand(0);
19747 SDValue RHS = N->getOperand(1);
19748 EVT VT = N->getValueType(0);
19751 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
19752 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
19753 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
19754 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19755 LHS.getValueType(), RHS, LHS.getOperand(1));
19756 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19757 addV, DAG.getConstant(0, addV.getValueType()), CC);
19759 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
19760 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
19761 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
19762 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19763 RHS.getValueType(), LHS, RHS.getOperand(1));
19764 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19765 addV, DAG.getConstant(0, addV.getValueType()), CC);
19768 if (VT.getScalarType() == MVT::i1) {
19769 bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
19770 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
19771 bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
19772 if (!IsSEXT0 && !IsVZero0)
19774 bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
19775 (RHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
19776 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
19778 if (!IsSEXT1 && !IsVZero1)
19781 if (IsSEXT0 && IsVZero1) {
19782 assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
19783 if (CC == ISD::SETEQ)
19784 return DAG.getNOT(DL, LHS.getOperand(0), VT);
19785 return LHS.getOperand(0);
19787 if (IsSEXT1 && IsVZero0) {
19788 assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
19789 if (CC == ISD::SETEQ)
19790 return DAG.getNOT(DL, RHS.getOperand(0), VT);
19791 return RHS.getOperand(0);
19798 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
19799 // as "sbb reg,reg", since it can be extended without zext and produces
19800 // an all-ones bit which is more useful than 0/1 in some cases.
19801 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
19804 return DAG.getNode(ISD::AND, DL, VT,
19805 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19806 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
19807 DAG.getConstant(1, VT));
19808 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
19809 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
19810 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19811 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
19814 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
19815 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
19816 TargetLowering::DAGCombinerInfo &DCI,
19817 const X86Subtarget *Subtarget) {
19819 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
19820 SDValue EFLAGS = N->getOperand(1);
19822 if (CC == X86::COND_A) {
19823 // Try to convert COND_A into COND_B in an attempt to facilitate
19824 // materializing "setb reg".
19826 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
19827 // cannot take an immediate as its first operand.
19829 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
19830 EFLAGS.getValueType().isInteger() &&
19831 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
19832 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
19833 EFLAGS.getNode()->getVTList(),
19834 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
19835 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
19836 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
19840 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
19841 // a zext and produces an all-ones bit which is more useful than 0/1 in some
19843 if (CC == X86::COND_B)
19844 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
19848 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19849 if (Flags.getNode()) {
19850 SDValue Cond = DAG.getConstant(CC, MVT::i8);
19851 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
19857 // Optimize branch condition evaluation.
19859 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
19860 TargetLowering::DAGCombinerInfo &DCI,
19861 const X86Subtarget *Subtarget) {
19863 SDValue Chain = N->getOperand(0);
19864 SDValue Dest = N->getOperand(1);
19865 SDValue EFLAGS = N->getOperand(3);
19866 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
19870 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19871 if (Flags.getNode()) {
19872 SDValue Cond = DAG.getConstant(CC, MVT::i8);
19873 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
19880 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
19881 const X86TargetLowering *XTLI) {
19882 SDValue Op0 = N->getOperand(0);
19883 EVT InVT = Op0->getValueType(0);
19885 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
19886 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
19888 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
19889 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
19890 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
19893 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
19894 // a 32-bit target where SSE doesn't support i64->FP operations.
19895 if (Op0.getOpcode() == ISD::LOAD) {
19896 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
19897 EVT VT = Ld->getValueType(0);
19898 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
19899 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
19900 !XTLI->getSubtarget()->is64Bit() &&
19902 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
19903 Ld->getChain(), Op0, DAG);
19904 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
19911 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
19912 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
19913 X86TargetLowering::DAGCombinerInfo &DCI) {
19914 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
19915 // the result is either zero or one (depending on the input carry bit).
19916 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
19917 if (X86::isZeroNode(N->getOperand(0)) &&
19918 X86::isZeroNode(N->getOperand(1)) &&
19919 // We don't have a good way to replace an EFLAGS use, so only do this when
19921 SDValue(N, 1).use_empty()) {
19923 EVT VT = N->getValueType(0);
19924 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
19925 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
19926 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
19927 DAG.getConstant(X86::COND_B,MVT::i8),
19929 DAG.getConstant(1, VT));
19930 return DCI.CombineTo(N, Res1, CarryOut);
19936 // fold (add Y, (sete X, 0)) -> adc 0, Y
19937 // (add Y, (setne X, 0)) -> sbb -1, Y
19938 // (sub (sete X, 0), Y) -> sbb 0, Y
19939 // (sub (setne X, 0), Y) -> adc -1, Y
19940 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
19943 // Look through ZExts.
19944 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
19945 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
19948 SDValue SetCC = Ext.getOperand(0);
19949 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
19952 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
19953 if (CC != X86::COND_E && CC != X86::COND_NE)
19956 SDValue Cmp = SetCC.getOperand(1);
19957 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
19958 !X86::isZeroNode(Cmp.getOperand(1)) ||
19959 !Cmp.getOperand(0).getValueType().isInteger())
19962 SDValue CmpOp0 = Cmp.getOperand(0);
19963 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
19964 DAG.getConstant(1, CmpOp0.getValueType()));
19966 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
19967 if (CC == X86::COND_NE)
19968 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
19969 DL, OtherVal.getValueType(), OtherVal,
19970 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
19971 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
19972 DL, OtherVal.getValueType(), OtherVal,
19973 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
19976 /// PerformADDCombine - Do target-specific dag combines on integer adds.
19977 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
19978 const X86Subtarget *Subtarget) {
19979 EVT VT = N->getValueType(0);
19980 SDValue Op0 = N->getOperand(0);
19981 SDValue Op1 = N->getOperand(1);
19983 // Try to synthesize horizontal adds from adds of shuffles.
19984 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19985 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19986 isHorizontalBinOp(Op0, Op1, true))
19987 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
19989 return OptimizeConditionalInDecrement(N, DAG);
19992 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
19993 const X86Subtarget *Subtarget) {
19994 SDValue Op0 = N->getOperand(0);
19995 SDValue Op1 = N->getOperand(1);
19997 // X86 can't encode an immediate LHS of a sub. See if we can push the
19998 // negation into a preceding instruction.
19999 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
20000 // If the RHS of the sub is a XOR with one use and a constant, invert the
20001 // immediate. Then add one to the LHS of the sub so we can turn
20002 // X-Y -> X+~Y+1, saving one register.
20003 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
20004 isa<ConstantSDNode>(Op1.getOperand(1))) {
20005 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
20006 EVT VT = Op0.getValueType();
20007 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
20009 DAG.getConstant(~XorC, VT));
20010 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
20011 DAG.getConstant(C->getAPIntValue()+1, VT));
20015 // Try to synthesize horizontal adds from adds of shuffles.
20016 EVT VT = N->getValueType(0);
20017 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20018 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20019 isHorizontalBinOp(Op0, Op1, true))
20020 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
20022 return OptimizeConditionalInDecrement(N, DAG);
20025 /// performVZEXTCombine - Performs build vector combines
20026 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
20027 TargetLowering::DAGCombinerInfo &DCI,
20028 const X86Subtarget *Subtarget) {
20029 // (vzext (bitcast (vzext (x)) -> (vzext x)
20030 SDValue In = N->getOperand(0);
20031 while (In.getOpcode() == ISD::BITCAST)
20032 In = In.getOperand(0);
20034 if (In.getOpcode() != X86ISD::VZEXT)
20037 return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
20041 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
20042 DAGCombinerInfo &DCI) const {
20043 SelectionDAG &DAG = DCI.DAG;
20044 switch (N->getOpcode()) {
20046 case ISD::EXTRACT_VECTOR_ELT:
20047 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
20049 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
20050 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
20051 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
20052 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
20053 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
20054 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
20057 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
20058 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
20059 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
20060 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
20061 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
20062 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
20063 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
20064 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
20065 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
20067 case X86ISD::FOR: return PerformFORCombine(N, DAG);
20069 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
20070 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
20071 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
20072 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
20073 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
20074 case ISD::ANY_EXTEND:
20075 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
20076 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
20077 case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
20078 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
20079 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
20080 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
20081 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
20082 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
20083 case X86ISD::SHUFP: // Handle all target specific shuffles
20084 case X86ISD::PALIGNR:
20085 case X86ISD::UNPCKH:
20086 case X86ISD::UNPCKL:
20087 case X86ISD::MOVHLPS:
20088 case X86ISD::MOVLHPS:
20089 case X86ISD::PSHUFD:
20090 case X86ISD::PSHUFHW:
20091 case X86ISD::PSHUFLW:
20092 case X86ISD::MOVSS:
20093 case X86ISD::MOVSD:
20094 case X86ISD::VPERMILP:
20095 case X86ISD::VPERM2X128:
20096 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
20097 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
20103 /// isTypeDesirableForOp - Return true if the target has native support for
20104 /// the specified value type and it is 'desirable' to use the type for the
20105 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
20106 /// instruction encodings are longer and some i16 instructions are slow.
20107 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
20108 if (!isTypeLegal(VT))
20110 if (VT != MVT::i16)
20117 case ISD::SIGN_EXTEND:
20118 case ISD::ZERO_EXTEND:
20119 case ISD::ANY_EXTEND:
20132 /// IsDesirableToPromoteOp - This method query the target whether it is
20133 /// beneficial for dag combiner to promote the specified node. If true, it
20134 /// should return the desired promotion type by reference.
20135 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
20136 EVT VT = Op.getValueType();
20137 if (VT != MVT::i16)
20140 bool Promote = false;
20141 bool Commute = false;
20142 switch (Op.getOpcode()) {
20145 LoadSDNode *LD = cast<LoadSDNode>(Op);
20146 // If the non-extending load has a single use and it's not live out, then it
20147 // might be folded.
20148 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
20149 Op.hasOneUse()*/) {
20150 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
20151 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
20152 // The only case where we'd want to promote LOAD (rather then it being
20153 // promoted as an operand is when it's only use is liveout.
20154 if (UI->getOpcode() != ISD::CopyToReg)
20161 case ISD::SIGN_EXTEND:
20162 case ISD::ZERO_EXTEND:
20163 case ISD::ANY_EXTEND:
20168 SDValue N0 = Op.getOperand(0);
20169 // Look out for (store (shl (load), x)).
20170 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
20183 SDValue N0 = Op.getOperand(0);
20184 SDValue N1 = Op.getOperand(1);
20185 if (!Commute && MayFoldLoad(N1))
20187 // Avoid disabling potential load folding opportunities.
20188 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
20190 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
20200 //===----------------------------------------------------------------------===//
20201 // X86 Inline Assembly Support
20202 //===----------------------------------------------------------------------===//
20205 // Helper to match a string separated by whitespace.
20206 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
20207 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
20209 for (unsigned i = 0, e = args.size(); i != e; ++i) {
20210 StringRef piece(*args[i]);
20211 if (!s.startswith(piece)) // Check if the piece matches.
20214 s = s.substr(piece.size());
20215 StringRef::size_type pos = s.find_first_not_of(" \t");
20216 if (pos == 0) // We matched a prefix.
20224 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
20227 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
20229 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
20230 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
20231 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
20232 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
20234 if (AsmPieces.size() == 3)
20236 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
20243 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
20244 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
20246 std::string AsmStr = IA->getAsmString();
20248 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
20249 if (!Ty || Ty->getBitWidth() % 16 != 0)
20252 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
20253 SmallVector<StringRef, 4> AsmPieces;
20254 SplitString(AsmStr, AsmPieces, ";\n");
20256 switch (AsmPieces.size()) {
20257 default: return false;
20259 // FIXME: this should verify that we are targeting a 486 or better. If not,
20260 // we will turn this bswap into something that will be lowered to logical
20261 // ops instead of emitting the bswap asm. For now, we don't support 486 or
20262 // lower so don't worry about this.
20264 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
20265 matchAsm(AsmPieces[0], "bswapl", "$0") ||
20266 matchAsm(AsmPieces[0], "bswapq", "$0") ||
20267 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
20268 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
20269 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
20270 // No need to check constraints, nothing other than the equivalent of
20271 // "=r,0" would be valid here.
20272 return IntrinsicLowering::LowerToByteSwap(CI);
20275 // rorw $$8, ${0:w} --> llvm.bswap.i16
20276 if (CI->getType()->isIntegerTy(16) &&
20277 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20278 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
20279 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
20281 const std::string &ConstraintsStr = IA->getConstraintString();
20282 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20283 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20284 if (clobbersFlagRegisters(AsmPieces))
20285 return IntrinsicLowering::LowerToByteSwap(CI);
20289 if (CI->getType()->isIntegerTy(32) &&
20290 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20291 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
20292 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
20293 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
20295 const std::string &ConstraintsStr = IA->getConstraintString();
20296 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20297 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20298 if (clobbersFlagRegisters(AsmPieces))
20299 return IntrinsicLowering::LowerToByteSwap(CI);
20302 if (CI->getType()->isIntegerTy(64)) {
20303 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
20304 if (Constraints.size() >= 2 &&
20305 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
20306 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
20307 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
20308 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
20309 matchAsm(AsmPieces[1], "bswap", "%edx") &&
20310 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
20311 return IntrinsicLowering::LowerToByteSwap(CI);
20319 /// getConstraintType - Given a constraint letter, return the type of
20320 /// constraint it is for this target.
20321 X86TargetLowering::ConstraintType
20322 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
20323 if (Constraint.size() == 1) {
20324 switch (Constraint[0]) {
20335 return C_RegisterClass;
20359 return TargetLowering::getConstraintType(Constraint);
20362 /// Examine constraint type and operand type and determine a weight value.
20363 /// This object must already have been set up with the operand type
20364 /// and the current alternative constraint selected.
20365 TargetLowering::ConstraintWeight
20366 X86TargetLowering::getSingleConstraintMatchWeight(
20367 AsmOperandInfo &info, const char *constraint) const {
20368 ConstraintWeight weight = CW_Invalid;
20369 Value *CallOperandVal = info.CallOperandVal;
20370 // If we don't have a value, we can't do a match,
20371 // but allow it at the lowest weight.
20372 if (!CallOperandVal)
20374 Type *type = CallOperandVal->getType();
20375 // Look at the constraint type.
20376 switch (*constraint) {
20378 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
20389 if (CallOperandVal->getType()->isIntegerTy())
20390 weight = CW_SpecificReg;
20395 if (type->isFloatingPointTy())
20396 weight = CW_SpecificReg;
20399 if (type->isX86_MMXTy() && Subtarget->hasMMX())
20400 weight = CW_SpecificReg;
20404 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
20405 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
20406 weight = CW_Register;
20409 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
20410 if (C->getZExtValue() <= 31)
20411 weight = CW_Constant;
20415 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20416 if (C->getZExtValue() <= 63)
20417 weight = CW_Constant;
20421 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20422 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
20423 weight = CW_Constant;
20427 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20428 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
20429 weight = CW_Constant;
20433 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20434 if (C->getZExtValue() <= 3)
20435 weight = CW_Constant;
20439 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20440 if (C->getZExtValue() <= 0xff)
20441 weight = CW_Constant;
20446 if (dyn_cast<ConstantFP>(CallOperandVal)) {
20447 weight = CW_Constant;
20451 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20452 if ((C->getSExtValue() >= -0x80000000LL) &&
20453 (C->getSExtValue() <= 0x7fffffffLL))
20454 weight = CW_Constant;
20458 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20459 if (C->getZExtValue() <= 0xffffffff)
20460 weight = CW_Constant;
20467 /// LowerXConstraint - try to replace an X constraint, which matches anything,
20468 /// with another that has more specific requirements based on the type of the
20469 /// corresponding operand.
20470 const char *X86TargetLowering::
20471 LowerXConstraint(EVT ConstraintVT) const {
20472 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
20473 // 'f' like normal targets.
20474 if (ConstraintVT.isFloatingPoint()) {
20475 if (Subtarget->hasSSE2())
20477 if (Subtarget->hasSSE1())
20481 return TargetLowering::LowerXConstraint(ConstraintVT);
20484 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
20485 /// vector. If it is invalid, don't add anything to Ops.
20486 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
20487 std::string &Constraint,
20488 std::vector<SDValue>&Ops,
20489 SelectionDAG &DAG) const {
20492 // Only support length 1 constraints for now.
20493 if (Constraint.length() > 1) return;
20495 char ConstraintLetter = Constraint[0];
20496 switch (ConstraintLetter) {
20499 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20500 if (C->getZExtValue() <= 31) {
20501 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20507 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20508 if (C->getZExtValue() <= 63) {
20509 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20515 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20516 if (isInt<8>(C->getSExtValue())) {
20517 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20523 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20524 if (C->getZExtValue() <= 255) {
20525 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20531 // 32-bit signed value
20532 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20533 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20534 C->getSExtValue())) {
20535 // Widen to 64 bits here to get it sign extended.
20536 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
20539 // FIXME gcc accepts some relocatable values here too, but only in certain
20540 // memory models; it's complicated.
20545 // 32-bit unsigned value
20546 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20547 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20548 C->getZExtValue())) {
20549 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20553 // FIXME gcc accepts some relocatable values here too, but only in certain
20554 // memory models; it's complicated.
20558 // Literal immediates are always ok.
20559 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
20560 // Widen to 64 bits here to get it sign extended.
20561 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
20565 // In any sort of PIC mode addresses need to be computed at runtime by
20566 // adding in a register or some sort of table lookup. These can't
20567 // be used as immediates.
20568 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
20571 // If we are in non-pic codegen mode, we allow the address of a global (with
20572 // an optional displacement) to be used with 'i'.
20573 GlobalAddressSDNode *GA = nullptr;
20574 int64_t Offset = 0;
20576 // Match either (GA), (GA+C), (GA+C1+C2), etc.
20578 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
20579 Offset += GA->getOffset();
20581 } else if (Op.getOpcode() == ISD::ADD) {
20582 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20583 Offset += C->getZExtValue();
20584 Op = Op.getOperand(0);
20587 } else if (Op.getOpcode() == ISD::SUB) {
20588 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20589 Offset += -C->getZExtValue();
20590 Op = Op.getOperand(0);
20595 // Otherwise, this isn't something we can handle, reject it.
20599 const GlobalValue *GV = GA->getGlobal();
20600 // If we require an extra load to get this address, as in PIC mode, we
20601 // can't accept it.
20602 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
20603 getTargetMachine())))
20606 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
20607 GA->getValueType(0), Offset);
20612 if (Result.getNode()) {
20613 Ops.push_back(Result);
20616 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
20619 std::pair<unsigned, const TargetRegisterClass*>
20620 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
20622 // First, see if this is a constraint that directly corresponds to an LLVM
20624 if (Constraint.size() == 1) {
20625 // GCC Constraint Letters
20626 switch (Constraint[0]) {
20628 // TODO: Slight differences here in allocation order and leaving
20629 // RIP in the class. Do they matter any more here than they do
20630 // in the normal allocation?
20631 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
20632 if (Subtarget->is64Bit()) {
20633 if (VT == MVT::i32 || VT == MVT::f32)
20634 return std::make_pair(0U, &X86::GR32RegClass);
20635 if (VT == MVT::i16)
20636 return std::make_pair(0U, &X86::GR16RegClass);
20637 if (VT == MVT::i8 || VT == MVT::i1)
20638 return std::make_pair(0U, &X86::GR8RegClass);
20639 if (VT == MVT::i64 || VT == MVT::f64)
20640 return std::make_pair(0U, &X86::GR64RegClass);
20643 // 32-bit fallthrough
20644 case 'Q': // Q_REGS
20645 if (VT == MVT::i32 || VT == MVT::f32)
20646 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
20647 if (VT == MVT::i16)
20648 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
20649 if (VT == MVT::i8 || VT == MVT::i1)
20650 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
20651 if (VT == MVT::i64)
20652 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
20654 case 'r': // GENERAL_REGS
20655 case 'l': // INDEX_REGS
20656 if (VT == MVT::i8 || VT == MVT::i1)
20657 return std::make_pair(0U, &X86::GR8RegClass);
20658 if (VT == MVT::i16)
20659 return std::make_pair(0U, &X86::GR16RegClass);
20660 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
20661 return std::make_pair(0U, &X86::GR32RegClass);
20662 return std::make_pair(0U, &X86::GR64RegClass);
20663 case 'R': // LEGACY_REGS
20664 if (VT == MVT::i8 || VT == MVT::i1)
20665 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
20666 if (VT == MVT::i16)
20667 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
20668 if (VT == MVT::i32 || !Subtarget->is64Bit())
20669 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
20670 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
20671 case 'f': // FP Stack registers.
20672 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
20673 // value to the correct fpstack register class.
20674 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
20675 return std::make_pair(0U, &X86::RFP32RegClass);
20676 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
20677 return std::make_pair(0U, &X86::RFP64RegClass);
20678 return std::make_pair(0U, &X86::RFP80RegClass);
20679 case 'y': // MMX_REGS if MMX allowed.
20680 if (!Subtarget->hasMMX()) break;
20681 return std::make_pair(0U, &X86::VR64RegClass);
20682 case 'Y': // SSE_REGS if SSE2 allowed
20683 if (!Subtarget->hasSSE2()) break;
20685 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
20686 if (!Subtarget->hasSSE1()) break;
20688 switch (VT.SimpleTy) {
20690 // Scalar SSE types.
20693 return std::make_pair(0U, &X86::FR32RegClass);
20696 return std::make_pair(0U, &X86::FR64RegClass);
20704 return std::make_pair(0U, &X86::VR128RegClass);
20712 return std::make_pair(0U, &X86::VR256RegClass);
20717 return std::make_pair(0U, &X86::VR512RegClass);
20723 // Use the default implementation in TargetLowering to convert the register
20724 // constraint into a member of a register class.
20725 std::pair<unsigned, const TargetRegisterClass*> Res;
20726 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
20728 // Not found as a standard register?
20730 // Map st(0) -> st(7) -> ST0
20731 if (Constraint.size() == 7 && Constraint[0] == '{' &&
20732 tolower(Constraint[1]) == 's' &&
20733 tolower(Constraint[2]) == 't' &&
20734 Constraint[3] == '(' &&
20735 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
20736 Constraint[5] == ')' &&
20737 Constraint[6] == '}') {
20739 Res.first = X86::ST0+Constraint[4]-'0';
20740 Res.second = &X86::RFP80RegClass;
20744 // GCC allows "st(0)" to be called just plain "st".
20745 if (StringRef("{st}").equals_lower(Constraint)) {
20746 Res.first = X86::ST0;
20747 Res.second = &X86::RFP80RegClass;
20752 if (StringRef("{flags}").equals_lower(Constraint)) {
20753 Res.first = X86::EFLAGS;
20754 Res.second = &X86::CCRRegClass;
20758 // 'A' means EAX + EDX.
20759 if (Constraint == "A") {
20760 Res.first = X86::EAX;
20761 Res.second = &X86::GR32_ADRegClass;
20767 // Otherwise, check to see if this is a register class of the wrong value
20768 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
20769 // turn into {ax},{dx}.
20770 if (Res.second->hasType(VT))
20771 return Res; // Correct type already, nothing to do.
20773 // All of the single-register GCC register classes map their values onto
20774 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
20775 // really want an 8-bit or 32-bit register, map to the appropriate register
20776 // class and return the appropriate register.
20777 if (Res.second == &X86::GR16RegClass) {
20778 if (VT == MVT::i8 || VT == MVT::i1) {
20779 unsigned DestReg = 0;
20780 switch (Res.first) {
20782 case X86::AX: DestReg = X86::AL; break;
20783 case X86::DX: DestReg = X86::DL; break;
20784 case X86::CX: DestReg = X86::CL; break;
20785 case X86::BX: DestReg = X86::BL; break;
20788 Res.first = DestReg;
20789 Res.second = &X86::GR8RegClass;
20791 } else if (VT == MVT::i32 || VT == MVT::f32) {
20792 unsigned DestReg = 0;
20793 switch (Res.first) {
20795 case X86::AX: DestReg = X86::EAX; break;
20796 case X86::DX: DestReg = X86::EDX; break;
20797 case X86::CX: DestReg = X86::ECX; break;
20798 case X86::BX: DestReg = X86::EBX; break;
20799 case X86::SI: DestReg = X86::ESI; break;
20800 case X86::DI: DestReg = X86::EDI; break;
20801 case X86::BP: DestReg = X86::EBP; break;
20802 case X86::SP: DestReg = X86::ESP; break;
20805 Res.first = DestReg;
20806 Res.second = &X86::GR32RegClass;
20808 } else if (VT == MVT::i64 || VT == MVT::f64) {
20809 unsigned DestReg = 0;
20810 switch (Res.first) {
20812 case X86::AX: DestReg = X86::RAX; break;
20813 case X86::DX: DestReg = X86::RDX; break;
20814 case X86::CX: DestReg = X86::RCX; break;
20815 case X86::BX: DestReg = X86::RBX; break;
20816 case X86::SI: DestReg = X86::RSI; break;
20817 case X86::DI: DestReg = X86::RDI; break;
20818 case X86::BP: DestReg = X86::RBP; break;
20819 case X86::SP: DestReg = X86::RSP; break;
20822 Res.first = DestReg;
20823 Res.second = &X86::GR64RegClass;
20826 } else if (Res.second == &X86::FR32RegClass ||
20827 Res.second == &X86::FR64RegClass ||
20828 Res.second == &X86::VR128RegClass ||
20829 Res.second == &X86::VR256RegClass ||
20830 Res.second == &X86::FR32XRegClass ||
20831 Res.second == &X86::FR64XRegClass ||
20832 Res.second == &X86::VR128XRegClass ||
20833 Res.second == &X86::VR256XRegClass ||
20834 Res.second == &X86::VR512RegClass) {
20835 // Handle references to XMM physical registers that got mapped into the
20836 // wrong class. This can happen with constraints like {xmm0} where the
20837 // target independent register mapper will just pick the first match it can
20838 // find, ignoring the required type.
20840 if (VT == MVT::f32 || VT == MVT::i32)
20841 Res.second = &X86::FR32RegClass;
20842 else if (VT == MVT::f64 || VT == MVT::i64)
20843 Res.second = &X86::FR64RegClass;
20844 else if (X86::VR128RegClass.hasType(VT))
20845 Res.second = &X86::VR128RegClass;
20846 else if (X86::VR256RegClass.hasType(VT))
20847 Res.second = &X86::VR256RegClass;
20848 else if (X86::VR512RegClass.hasType(VT))
20849 Res.second = &X86::VR512RegClass;
20855 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
20857 // Scaling factors are not free at all.
20858 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
20859 // will take 2 allocations instead of 1 for plain addressing mode,
20860 // i.e. inst (reg1).
20861 if (isLegalAddressingMode(AM, Ty))
20862 // Scale represents reg2 * scale, thus account for 1
20863 // as soon as we use a second register.
20864 return AM.Scale != 0;