1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86InstrBuilder.h"
19 #include "X86MachineFunctionInfo.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/VariadicFunction.h"
26 #include "llvm/CodeGen/IntrinsicLowering.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineJumpTableInfo.h"
31 #include "llvm/CodeGen/MachineModuleInfo.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/IR/CallSite.h"
34 #include "llvm/IR/CallingConv.h"
35 #include "llvm/IR/Constants.h"
36 #include "llvm/IR/DerivedTypes.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/IR/GlobalAlias.h"
39 #include "llvm/IR/GlobalVariable.h"
40 #include "llvm/IR/Instructions.h"
41 #include "llvm/IR/Intrinsics.h"
42 #include "llvm/MC/MCAsmInfo.h"
43 #include "llvm/MC/MCContext.h"
44 #include "llvm/MC/MCExpr.h"
45 #include "llvm/MC/MCSymbol.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/MathExtras.h"
49 #include "llvm/Target/TargetOptions.h"
54 #define DEBUG_TYPE "x86-isel"
56 STATISTIC(NumTailCalls, "Number of tail calls");
58 // Forward declarations.
59 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
62 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
63 SelectionDAG &DAG, SDLoc dl,
64 unsigned vectorWidth) {
65 assert((vectorWidth == 128 || vectorWidth == 256) &&
66 "Unsupported vector width");
67 EVT VT = Vec.getValueType();
68 EVT ElVT = VT.getVectorElementType();
69 unsigned Factor = VT.getSizeInBits()/vectorWidth;
70 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
71 VT.getVectorNumElements()/Factor);
73 // Extract from UNDEF is UNDEF.
74 if (Vec.getOpcode() == ISD::UNDEF)
75 return DAG.getUNDEF(ResultVT);
77 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
78 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
80 // This is the index of the first element of the vectorWidth-bit chunk
82 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
85 // If the input is a buildvector just emit a smaller one.
86 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
87 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
88 Vec->op_begin()+NormalizedIdxVal, ElemsPerChunk);
90 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
91 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
97 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
98 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
99 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
100 /// instructions or a simple subregister reference. Idx is an index in the
101 /// 128 bits we want. It need not be aligned to a 128-bit bounday. That makes
102 /// lowering EXTRACT_VECTOR_ELT operations easier.
103 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
104 SelectionDAG &DAG, SDLoc dl) {
105 assert((Vec.getValueType().is256BitVector() ||
106 Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
107 return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
110 /// Generate a DAG to grab 256-bits from a 512-bit vector.
111 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
112 SelectionDAG &DAG, SDLoc dl) {
113 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
114 return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
117 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
118 unsigned IdxVal, SelectionDAG &DAG,
119 SDLoc dl, unsigned vectorWidth) {
120 assert((vectorWidth == 128 || vectorWidth == 256) &&
121 "Unsupported vector width");
122 // Inserting UNDEF is Result
123 if (Vec.getOpcode() == ISD::UNDEF)
125 EVT VT = Vec.getValueType();
126 EVT ElVT = VT.getVectorElementType();
127 EVT ResultVT = Result.getValueType();
129 // Insert the relevant vectorWidth bits.
130 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
132 // This is the index of the first element of the vectorWidth-bit chunk
134 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
137 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
138 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
141 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
142 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
143 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
144 /// simple superregister reference. Idx is an index in the 128 bits
145 /// we want. It need not be aligned to a 128-bit bounday. That makes
146 /// lowering INSERT_VECTOR_ELT operations easier.
147 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
148 unsigned IdxVal, SelectionDAG &DAG,
150 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
151 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
154 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
155 unsigned IdxVal, SelectionDAG &DAG,
157 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
158 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
161 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
162 /// instructions. This is used because creating CONCAT_VECTOR nodes of
163 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
164 /// large BUILD_VECTORS.
165 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
166 unsigned NumElems, SelectionDAG &DAG,
168 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
169 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
172 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
173 unsigned NumElems, SelectionDAG &DAG,
175 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
176 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
179 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
180 const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
181 bool is64Bit = Subtarget->is64Bit();
183 if (Subtarget->isTargetMacho()) {
185 return new X86_64MachoTargetObjectFile();
186 return new TargetLoweringObjectFileMachO();
189 if (Subtarget->isTargetLinux())
190 return new X86LinuxTargetObjectFile();
191 if (Subtarget->isTargetELF())
192 return new TargetLoweringObjectFileELF();
193 if (Subtarget->isTargetKnownWindowsMSVC())
194 return new X86WindowsTargetObjectFile();
195 if (Subtarget->isTargetCOFF())
196 return new TargetLoweringObjectFileCOFF();
197 llvm_unreachable("unknown subtarget type");
200 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
201 : TargetLowering(TM, createTLOF(TM)) {
202 Subtarget = &TM.getSubtarget<X86Subtarget>();
203 X86ScalarSSEf64 = Subtarget->hasSSE2();
204 X86ScalarSSEf32 = Subtarget->hasSSE1();
205 TD = getDataLayout();
207 resetOperationActions();
210 void X86TargetLowering::resetOperationActions() {
211 const TargetMachine &TM = getTargetMachine();
212 static bool FirstTimeThrough = true;
214 // If none of the target options have changed, then we don't need to reset the
215 // operation actions.
216 if (!FirstTimeThrough && TO == TM.Options) return;
218 if (!FirstTimeThrough) {
219 // Reinitialize the actions.
221 FirstTimeThrough = false;
226 // Set up the TargetLowering object.
227 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
229 // X86 is weird, it always uses i8 for shift amounts and setcc results.
230 setBooleanContents(ZeroOrOneBooleanContent);
231 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
232 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
234 // For 64-bit since we have so many registers use the ILP scheduler, for
235 // 32-bit code use the register pressure specific scheduling.
236 // For Atom, always use ILP scheduling.
237 if (Subtarget->isAtom())
238 setSchedulingPreference(Sched::ILP);
239 else if (Subtarget->is64Bit())
240 setSchedulingPreference(Sched::ILP);
242 setSchedulingPreference(Sched::RegPressure);
243 const X86RegisterInfo *RegInfo =
244 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
245 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
247 // Bypass expensive divides on Atom when compiling with O2
248 if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
249 addBypassSlowDiv(32, 8);
250 if (Subtarget->is64Bit())
251 addBypassSlowDiv(64, 16);
254 if (Subtarget->isTargetKnownWindowsMSVC()) {
255 // Setup Windows compiler runtime calls.
256 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
257 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
258 setLibcallName(RTLIB::SREM_I64, "_allrem");
259 setLibcallName(RTLIB::UREM_I64, "_aullrem");
260 setLibcallName(RTLIB::MUL_I64, "_allmul");
261 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
262 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
263 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
264 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
265 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
267 // The _ftol2 runtime function has an unusual calling conv, which
268 // is modeled by a special pseudo-instruction.
269 setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
270 setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
271 setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
272 setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
275 if (Subtarget->isTargetDarwin()) {
276 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
277 setUseUnderscoreSetJmp(false);
278 setUseUnderscoreLongJmp(false);
279 } else if (Subtarget->isTargetWindowsGNU()) {
280 // MS runtime is weird: it exports _setjmp, but longjmp!
281 setUseUnderscoreSetJmp(true);
282 setUseUnderscoreLongJmp(false);
284 setUseUnderscoreSetJmp(true);
285 setUseUnderscoreLongJmp(true);
288 // Set up the register classes.
289 addRegisterClass(MVT::i8, &X86::GR8RegClass);
290 addRegisterClass(MVT::i16, &X86::GR16RegClass);
291 addRegisterClass(MVT::i32, &X86::GR32RegClass);
292 if (Subtarget->is64Bit())
293 addRegisterClass(MVT::i64, &X86::GR64RegClass);
295 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
297 // We don't accept any truncstore of integer registers.
298 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
299 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
300 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
301 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
302 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
303 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
305 // SETOEQ and SETUNE require checking two conditions.
306 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
307 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
308 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
309 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
310 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
311 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
313 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
315 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
316 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
317 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
319 if (Subtarget->is64Bit()) {
320 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
321 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
322 } else if (!TM.Options.UseSoftFloat) {
323 // We have an algorithm for SSE2->double, and we turn this into a
324 // 64-bit FILD followed by conditional FADD for other targets.
325 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
326 // We have an algorithm for SSE2, and we turn this into a 64-bit
327 // FILD for other targets.
328 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
331 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
333 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
334 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
336 if (!TM.Options.UseSoftFloat) {
337 // SSE has no i16 to fp conversion, only i32
338 if (X86ScalarSSEf32) {
339 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
340 // f32 and f64 cases are Legal, f80 case is not
341 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
343 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
344 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
347 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
348 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
351 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
352 // are Legal, f80 is custom lowered.
353 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
354 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
356 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
358 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
359 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
361 if (X86ScalarSSEf32) {
362 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
363 // f32 and f64 cases are Legal, f80 case is not
364 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
366 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
367 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
370 // Handle FP_TO_UINT by promoting the destination to a larger signed
372 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
373 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
374 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
376 if (Subtarget->is64Bit()) {
377 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
378 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
379 } else if (!TM.Options.UseSoftFloat) {
380 // Since AVX is a superset of SSE3, only check for SSE here.
381 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
382 // Expand FP_TO_UINT into a select.
383 // FIXME: We would like to use a Custom expander here eventually to do
384 // the optimal thing for SSE vs. the default expansion in the legalizer.
385 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
387 // With SSE3 we can use fisttpll to convert to a signed i64; without
388 // SSE, we're stuck with a fistpll.
389 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
392 if (isTargetFTOL()) {
393 // Use the _ftol2 runtime function, which has a pseudo-instruction
394 // to handle its weird calling convention.
395 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
398 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
399 if (!X86ScalarSSEf64) {
400 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
401 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
402 if (Subtarget->is64Bit()) {
403 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
404 // Without SSE, i64->f64 goes through memory.
405 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
409 // Scalar integer divide and remainder are lowered to use operations that
410 // produce two results, to match the available instructions. This exposes
411 // the two-result form to trivial CSE, which is able to combine x/y and x%y
412 // into a single instruction.
414 // Scalar integer multiply-high is also lowered to use two-result
415 // operations, to match the available instructions. However, plain multiply
416 // (low) operations are left as Legal, as there are single-result
417 // instructions for this in x86. Using the two-result multiply instructions
418 // when both high and low results are needed must be arranged by dagcombine.
419 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
421 setOperationAction(ISD::MULHS, VT, Expand);
422 setOperationAction(ISD::MULHU, VT, Expand);
423 setOperationAction(ISD::SDIV, VT, Expand);
424 setOperationAction(ISD::UDIV, VT, Expand);
425 setOperationAction(ISD::SREM, VT, Expand);
426 setOperationAction(ISD::UREM, VT, Expand);
428 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
429 setOperationAction(ISD::ADDC, VT, Custom);
430 setOperationAction(ISD::ADDE, VT, Custom);
431 setOperationAction(ISD::SUBC, VT, Custom);
432 setOperationAction(ISD::SUBE, VT, Custom);
435 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
436 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
437 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
438 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
439 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
440 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
441 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
442 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
443 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
444 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
445 if (Subtarget->is64Bit())
446 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
447 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
448 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
449 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
450 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
451 setOperationAction(ISD::FREM , MVT::f32 , Expand);
452 setOperationAction(ISD::FREM , MVT::f64 , Expand);
453 setOperationAction(ISD::FREM , MVT::f80 , Expand);
454 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
456 // Promote the i8 variants and force them on up to i32 which has a shorter
458 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
459 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
460 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
461 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
462 if (Subtarget->hasBMI()) {
463 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
464 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
465 if (Subtarget->is64Bit())
466 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
468 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
469 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
470 if (Subtarget->is64Bit())
471 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
474 if (Subtarget->hasLZCNT()) {
475 // When promoting the i8 variants, force them to i32 for a shorter
477 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
478 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
479 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
480 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
481 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
482 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
483 if (Subtarget->is64Bit())
484 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
486 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
487 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
488 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
489 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
490 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
491 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
492 if (Subtarget->is64Bit()) {
493 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
494 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
498 if (Subtarget->hasPOPCNT()) {
499 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
501 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
502 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
503 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
504 if (Subtarget->is64Bit())
505 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
508 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
510 if (!Subtarget->hasMOVBE())
511 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
513 // These should be promoted to a larger select which is supported.
514 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
515 // X86 wants to expand cmov itself.
516 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
517 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
518 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
519 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
520 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
521 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
522 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
523 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
524 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
525 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
526 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
527 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
528 if (Subtarget->is64Bit()) {
529 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
530 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
532 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
533 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
534 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
535 // support continuation, user-level threading, and etc.. As a result, no
536 // other SjLj exception interfaces are implemented and please don't build
537 // your own exception handling based on them.
538 // LLVM/Clang supports zero-cost DWARF exception handling.
539 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
540 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
543 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
544 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
545 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
546 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
547 if (Subtarget->is64Bit())
548 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
549 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
550 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
551 if (Subtarget->is64Bit()) {
552 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
553 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
554 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
555 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
556 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
558 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
559 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
560 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
561 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
562 if (Subtarget->is64Bit()) {
563 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
564 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
565 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
568 if (Subtarget->hasSSE1())
569 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
571 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
573 // Expand certain atomics
574 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
576 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
577 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
578 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
581 if (!Subtarget->is64Bit()) {
582 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
583 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
584 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
585 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
586 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
587 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
588 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
589 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
590 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
591 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
592 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
593 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
596 if (Subtarget->hasCmpxchg16b()) {
597 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
600 // FIXME - use subtarget debug flags
601 if (!Subtarget->isTargetDarwin() &&
602 !Subtarget->isTargetELF() &&
603 !Subtarget->isTargetCygMing()) {
604 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
607 if (Subtarget->is64Bit()) {
608 setExceptionPointerRegister(X86::RAX);
609 setExceptionSelectorRegister(X86::RDX);
611 setExceptionPointerRegister(X86::EAX);
612 setExceptionSelectorRegister(X86::EDX);
614 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
615 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
617 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
618 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
620 setOperationAction(ISD::TRAP, MVT::Other, Legal);
621 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
623 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
624 setOperationAction(ISD::VASTART , MVT::Other, Custom);
625 setOperationAction(ISD::VAEND , MVT::Other, Expand);
626 if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
627 // TargetInfo::X86_64ABIBuiltinVaList
628 setOperationAction(ISD::VAARG , MVT::Other, Custom);
629 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
631 // TargetInfo::CharPtrBuiltinVaList
632 setOperationAction(ISD::VAARG , MVT::Other, Expand);
633 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
636 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
637 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
639 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
640 MVT::i64 : MVT::i32, Custom);
642 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
643 // f32 and f64 use SSE.
644 // Set up the FP register classes.
645 addRegisterClass(MVT::f32, &X86::FR32RegClass);
646 addRegisterClass(MVT::f64, &X86::FR64RegClass);
648 // Use ANDPD to simulate FABS.
649 setOperationAction(ISD::FABS , MVT::f64, Custom);
650 setOperationAction(ISD::FABS , MVT::f32, Custom);
652 // Use XORP to simulate FNEG.
653 setOperationAction(ISD::FNEG , MVT::f64, Custom);
654 setOperationAction(ISD::FNEG , MVT::f32, Custom);
656 // Use ANDPD and ORPD to simulate FCOPYSIGN.
657 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
658 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
660 // Lower this to FGETSIGNx86 plus an AND.
661 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
662 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
664 // We don't support sin/cos/fmod
665 setOperationAction(ISD::FSIN , MVT::f64, Expand);
666 setOperationAction(ISD::FCOS , MVT::f64, Expand);
667 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
668 setOperationAction(ISD::FSIN , MVT::f32, Expand);
669 setOperationAction(ISD::FCOS , MVT::f32, Expand);
670 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
672 // Expand FP immediates into loads from the stack, except for the special
674 addLegalFPImmediate(APFloat(+0.0)); // xorpd
675 addLegalFPImmediate(APFloat(+0.0f)); // xorps
676 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
677 // Use SSE for f32, x87 for f64.
678 // Set up the FP register classes.
679 addRegisterClass(MVT::f32, &X86::FR32RegClass);
680 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
682 // Use ANDPS to simulate FABS.
683 setOperationAction(ISD::FABS , MVT::f32, Custom);
685 // Use XORP to simulate FNEG.
686 setOperationAction(ISD::FNEG , MVT::f32, Custom);
688 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
690 // Use ANDPS and ORPS to simulate FCOPYSIGN.
691 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
692 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
694 // We don't support sin/cos/fmod
695 setOperationAction(ISD::FSIN , MVT::f32, Expand);
696 setOperationAction(ISD::FCOS , MVT::f32, Expand);
697 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
699 // Special cases we handle for FP constants.
700 addLegalFPImmediate(APFloat(+0.0f)); // xorps
701 addLegalFPImmediate(APFloat(+0.0)); // FLD0
702 addLegalFPImmediate(APFloat(+1.0)); // FLD1
703 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
704 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
706 if (!TM.Options.UnsafeFPMath) {
707 setOperationAction(ISD::FSIN , MVT::f64, Expand);
708 setOperationAction(ISD::FCOS , MVT::f64, Expand);
709 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
711 } else if (!TM.Options.UseSoftFloat) {
712 // f32 and f64 in x87.
713 // Set up the FP register classes.
714 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
715 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
717 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
718 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
719 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
720 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
722 if (!TM.Options.UnsafeFPMath) {
723 setOperationAction(ISD::FSIN , MVT::f64, Expand);
724 setOperationAction(ISD::FSIN , MVT::f32, Expand);
725 setOperationAction(ISD::FCOS , MVT::f64, Expand);
726 setOperationAction(ISD::FCOS , MVT::f32, Expand);
727 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
728 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
730 addLegalFPImmediate(APFloat(+0.0)); // FLD0
731 addLegalFPImmediate(APFloat(+1.0)); // FLD1
732 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
733 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
734 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
735 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
736 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
737 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
740 // We don't support FMA.
741 setOperationAction(ISD::FMA, MVT::f64, Expand);
742 setOperationAction(ISD::FMA, MVT::f32, Expand);
744 // Long double always uses X87.
745 if (!TM.Options.UseSoftFloat) {
746 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
747 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
748 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
750 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
751 addLegalFPImmediate(TmpFlt); // FLD0
753 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
756 APFloat TmpFlt2(+1.0);
757 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
759 addLegalFPImmediate(TmpFlt2); // FLD1
760 TmpFlt2.changeSign();
761 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
764 if (!TM.Options.UnsafeFPMath) {
765 setOperationAction(ISD::FSIN , MVT::f80, Expand);
766 setOperationAction(ISD::FCOS , MVT::f80, Expand);
767 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
770 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
771 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
772 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
773 setOperationAction(ISD::FRINT, MVT::f80, Expand);
774 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
775 setOperationAction(ISD::FMA, MVT::f80, Expand);
778 // Always use a library call for pow.
779 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
780 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
781 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
783 setOperationAction(ISD::FLOG, MVT::f80, Expand);
784 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
785 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
786 setOperationAction(ISD::FEXP, MVT::f80, Expand);
787 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
789 // First set operation action for all vector types to either promote
790 // (for widening) or expand (for scalarization). Then we will selectively
791 // turn on ones that can be effectively codegen'd.
792 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
793 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
794 MVT VT = (MVT::SimpleValueType)i;
795 setOperationAction(ISD::ADD , VT, Expand);
796 setOperationAction(ISD::SUB , VT, Expand);
797 setOperationAction(ISD::FADD, VT, Expand);
798 setOperationAction(ISD::FNEG, VT, Expand);
799 setOperationAction(ISD::FSUB, VT, Expand);
800 setOperationAction(ISD::MUL , VT, Expand);
801 setOperationAction(ISD::FMUL, VT, Expand);
802 setOperationAction(ISD::SDIV, VT, Expand);
803 setOperationAction(ISD::UDIV, VT, Expand);
804 setOperationAction(ISD::FDIV, VT, Expand);
805 setOperationAction(ISD::SREM, VT, Expand);
806 setOperationAction(ISD::UREM, VT, Expand);
807 setOperationAction(ISD::LOAD, VT, Expand);
808 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
809 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
810 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
811 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
812 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
813 setOperationAction(ISD::FABS, VT, Expand);
814 setOperationAction(ISD::FSIN, VT, Expand);
815 setOperationAction(ISD::FSINCOS, VT, Expand);
816 setOperationAction(ISD::FCOS, VT, Expand);
817 setOperationAction(ISD::FSINCOS, VT, Expand);
818 setOperationAction(ISD::FREM, VT, Expand);
819 setOperationAction(ISD::FMA, VT, Expand);
820 setOperationAction(ISD::FPOWI, VT, Expand);
821 setOperationAction(ISD::FSQRT, VT, Expand);
822 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
823 setOperationAction(ISD::FFLOOR, VT, Expand);
824 setOperationAction(ISD::FCEIL, VT, Expand);
825 setOperationAction(ISD::FTRUNC, VT, Expand);
826 setOperationAction(ISD::FRINT, VT, Expand);
827 setOperationAction(ISD::FNEARBYINT, VT, Expand);
828 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
829 setOperationAction(ISD::MULHS, VT, Expand);
830 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
831 setOperationAction(ISD::MULHU, VT, Expand);
832 setOperationAction(ISD::SDIVREM, VT, Expand);
833 setOperationAction(ISD::UDIVREM, VT, Expand);
834 setOperationAction(ISD::FPOW, VT, Expand);
835 setOperationAction(ISD::CTPOP, VT, Expand);
836 setOperationAction(ISD::CTTZ, VT, Expand);
837 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
838 setOperationAction(ISD::CTLZ, VT, Expand);
839 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
840 setOperationAction(ISD::SHL, VT, Expand);
841 setOperationAction(ISD::SRA, VT, Expand);
842 setOperationAction(ISD::SRL, VT, Expand);
843 setOperationAction(ISD::ROTL, VT, Expand);
844 setOperationAction(ISD::ROTR, VT, Expand);
845 setOperationAction(ISD::BSWAP, VT, Expand);
846 setOperationAction(ISD::SETCC, VT, Expand);
847 setOperationAction(ISD::FLOG, VT, Expand);
848 setOperationAction(ISD::FLOG2, VT, Expand);
849 setOperationAction(ISD::FLOG10, VT, Expand);
850 setOperationAction(ISD::FEXP, VT, Expand);
851 setOperationAction(ISD::FEXP2, VT, Expand);
852 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
853 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
854 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
855 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
856 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
857 setOperationAction(ISD::TRUNCATE, VT, Expand);
858 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
859 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
860 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
861 setOperationAction(ISD::VSELECT, VT, Expand);
862 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
863 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
864 setTruncStoreAction(VT,
865 (MVT::SimpleValueType)InnerVT, Expand);
866 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
867 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
868 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
871 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
872 // with -msoft-float, disable use of MMX as well.
873 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
874 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
875 // No operations on x86mmx supported, everything uses intrinsics.
878 // MMX-sized vectors (other than x86mmx) are expected to be expanded
879 // into smaller operations.
880 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
881 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
882 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
883 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
884 setOperationAction(ISD::AND, MVT::v8i8, Expand);
885 setOperationAction(ISD::AND, MVT::v4i16, Expand);
886 setOperationAction(ISD::AND, MVT::v2i32, Expand);
887 setOperationAction(ISD::AND, MVT::v1i64, Expand);
888 setOperationAction(ISD::OR, MVT::v8i8, Expand);
889 setOperationAction(ISD::OR, MVT::v4i16, Expand);
890 setOperationAction(ISD::OR, MVT::v2i32, Expand);
891 setOperationAction(ISD::OR, MVT::v1i64, Expand);
892 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
893 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
894 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
895 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
896 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
897 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
898 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
899 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
900 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
901 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
902 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
903 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
904 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
905 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
906 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
907 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
908 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
910 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
911 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
913 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
914 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
915 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
916 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
917 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
918 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
919 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
920 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
921 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
922 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
923 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
924 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
927 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
928 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
930 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
931 // registers cannot be used even for integer operations.
932 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
933 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
934 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
935 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
937 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
938 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
939 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
940 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
941 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
942 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
943 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
944 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
945 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
946 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
947 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
948 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
949 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
950 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
951 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
952 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
953 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
954 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
955 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
957 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
958 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
959 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
960 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
962 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
963 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
964 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
965 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
966 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
968 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
969 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
970 MVT VT = (MVT::SimpleValueType)i;
971 // Do not attempt to custom lower non-power-of-2 vectors
972 if (!isPowerOf2_32(VT.getVectorNumElements()))
974 // Do not attempt to custom lower non-128-bit vectors
975 if (!VT.is128BitVector())
977 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
978 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
979 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
982 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
983 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
984 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
985 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
986 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
987 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
989 if (Subtarget->is64Bit()) {
990 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
991 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
994 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
995 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
996 MVT VT = (MVT::SimpleValueType)i;
998 // Do not attempt to promote non-128-bit vectors
999 if (!VT.is128BitVector())
1002 setOperationAction(ISD::AND, VT, Promote);
1003 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
1004 setOperationAction(ISD::OR, VT, Promote);
1005 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
1006 setOperationAction(ISD::XOR, VT, Promote);
1007 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
1008 setOperationAction(ISD::LOAD, VT, Promote);
1009 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
1010 setOperationAction(ISD::SELECT, VT, Promote);
1011 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1014 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1016 // Custom lower v2i64 and v2f64 selects.
1017 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
1018 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
1019 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
1020 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
1022 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1023 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1025 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1026 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1027 // As there is no 64-bit GPR available, we need build a special custom
1028 // sequence to convert from v2i32 to v2f32.
1029 if (!Subtarget->is64Bit())
1030 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
1032 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1033 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
1035 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
1038 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1039 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1040 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1041 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1042 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1043 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1044 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1045 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1046 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1047 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1048 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1050 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1051 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
1052 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1053 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
1054 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
1055 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
1056 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
1057 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
1058 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
1059 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
1061 // FIXME: Do we need to handle scalar-to-vector here?
1062 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1064 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
1065 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal);
1066 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
1067 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
1068 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
1070 // i8 and i16 vectors are custom , because the source register and source
1071 // source memory operand types are not the same width. f32 vectors are
1072 // custom since the immediate controlling the insert encodes additional
1074 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1075 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1076 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1077 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1079 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1080 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1081 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1082 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1084 // FIXME: these should be Legal but thats only for the case where
1085 // the index is constant. For now custom expand to deal with that.
1086 if (Subtarget->is64Bit()) {
1087 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1088 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1092 if (Subtarget->hasSSE2()) {
1093 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1094 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1096 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1097 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1099 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1100 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1102 // In the customized shift lowering, the legal cases in AVX2 will be
1104 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1105 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1107 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1108 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1110 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1112 setOperationAction(ISD::SDIV, MVT::v8i16, Custom);
1113 setOperationAction(ISD::SDIV, MVT::v4i32, Custom);
1116 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1117 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1118 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1119 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1120 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1121 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1122 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1124 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1125 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1126 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1128 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1129 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1130 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1131 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1132 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1133 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1134 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1135 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1136 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1137 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1138 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1139 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1141 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1142 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1143 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1144 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1145 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1146 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1147 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1148 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1149 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1150 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1151 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1152 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1154 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1155 // even though v8i16 is a legal type.
1156 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1157 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1158 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1160 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1161 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1162 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1164 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1165 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1167 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1169 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1170 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1172 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1173 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1175 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1176 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1178 setOperationAction(ISD::SDIV, MVT::v16i16, Custom);
1180 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1181 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1182 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1183 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1185 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1186 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1187 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1189 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1190 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal);
1191 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal);
1192 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal);
1194 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1195 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1196 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1197 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1198 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1199 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1200 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1201 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1202 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1203 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1204 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1205 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1207 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1208 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1209 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1210 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1211 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1212 setOperationAction(ISD::FMA, MVT::f32, Legal);
1213 setOperationAction(ISD::FMA, MVT::f64, Legal);
1216 if (Subtarget->hasInt256()) {
1217 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1218 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1219 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1220 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1222 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1223 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1224 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1225 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1227 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1228 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1229 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1230 // Don't lower v32i8 because there is no 128-bit byte mul
1232 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1234 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1236 setOperationAction(ISD::SDIV, MVT::v8i32, Custom);
1238 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1239 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1240 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1241 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1243 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1244 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1245 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1246 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1248 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1249 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1250 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1251 // Don't lower v32i8 because there is no 128-bit byte mul
1254 // In the customized shift lowering, the legal cases in AVX2 will be
1256 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1257 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1259 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1260 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1262 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1264 // Custom lower several nodes for 256-bit types.
1265 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1266 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1267 MVT VT = (MVT::SimpleValueType)i;
1269 // Extract subvector is special because the value type
1270 // (result) is 128-bit but the source is 256-bit wide.
1271 if (VT.is128BitVector())
1272 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1274 // Do not attempt to custom lower other non-256-bit vectors
1275 if (!VT.is256BitVector())
1278 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1279 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1280 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1281 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1282 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1283 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1284 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1287 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1288 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1289 MVT VT = (MVT::SimpleValueType)i;
1291 // Do not attempt to promote non-256-bit vectors
1292 if (!VT.is256BitVector())
1295 setOperationAction(ISD::AND, VT, Promote);
1296 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1297 setOperationAction(ISD::OR, VT, Promote);
1298 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1299 setOperationAction(ISD::XOR, VT, Promote);
1300 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1301 setOperationAction(ISD::LOAD, VT, Promote);
1302 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1303 setOperationAction(ISD::SELECT, VT, Promote);
1304 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1308 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1309 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1310 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1311 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1312 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1314 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1315 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1316 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1318 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1319 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1320 setOperationAction(ISD::XOR, MVT::i1, Legal);
1321 setOperationAction(ISD::OR, MVT::i1, Legal);
1322 setOperationAction(ISD::AND, MVT::i1, Legal);
1323 setLoadExtAction(ISD::EXTLOAD, MVT::v8f32, Legal);
1324 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1325 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1326 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1327 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1328 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1330 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1331 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1332 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1333 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1334 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1335 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1337 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1338 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1339 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1340 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1341 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1342 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1343 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1344 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1345 setOperationAction(ISD::SDIV, MVT::v16i32, Custom);
1347 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1348 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1349 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1350 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1351 if (Subtarget->is64Bit()) {
1352 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1353 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1354 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1355 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1357 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1358 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1359 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1360 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1361 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1362 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1363 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1364 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1365 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1366 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1368 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1369 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1370 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1371 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1372 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1373 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1374 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1375 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1376 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1377 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1378 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1379 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1380 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1382 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1383 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1384 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1385 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1386 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1387 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1389 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1390 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1392 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1394 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1395 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1396 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1397 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1398 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1399 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1400 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1401 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1402 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1404 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1405 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1407 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1408 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1410 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1412 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1413 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1415 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1416 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1418 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1419 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1421 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1422 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1423 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1424 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1425 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1426 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1428 // Custom lower several nodes.
1429 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1430 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1431 MVT VT = (MVT::SimpleValueType)i;
1433 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1434 // Extract subvector is special because the value type
1435 // (result) is 256/128-bit but the source is 512-bit wide.
1436 if (VT.is128BitVector() || VT.is256BitVector())
1437 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1439 if (VT.getVectorElementType() == MVT::i1)
1440 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1442 // Do not attempt to custom lower other non-512-bit vectors
1443 if (!VT.is512BitVector())
1446 if ( EltSize >= 32) {
1447 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1448 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1449 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1450 setOperationAction(ISD::VSELECT, VT, Legal);
1451 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1452 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1453 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1456 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1457 MVT VT = (MVT::SimpleValueType)i;
1459 // Do not attempt to promote non-256-bit vectors
1460 if (!VT.is512BitVector())
1463 setOperationAction(ISD::SELECT, VT, Promote);
1464 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1468 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1469 // of this type with custom code.
1470 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1471 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1472 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1476 // We want to custom lower some of our intrinsics.
1477 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1478 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1479 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1480 if (!Subtarget->is64Bit())
1481 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1483 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1484 // handle type legalization for these operations here.
1486 // FIXME: We really should do custom legalization for addition and
1487 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1488 // than generic legalization for 64-bit multiplication-with-overflow, though.
1489 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1490 // Add/Sub/Mul with overflow operations are custom lowered.
1492 setOperationAction(ISD::SADDO, VT, Custom);
1493 setOperationAction(ISD::UADDO, VT, Custom);
1494 setOperationAction(ISD::SSUBO, VT, Custom);
1495 setOperationAction(ISD::USUBO, VT, Custom);
1496 setOperationAction(ISD::SMULO, VT, Custom);
1497 setOperationAction(ISD::UMULO, VT, Custom);
1500 // There are no 8-bit 3-address imul/mul instructions
1501 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1502 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1504 if (!Subtarget->is64Bit()) {
1505 // These libcalls are not available in 32-bit.
1506 setLibcallName(RTLIB::SHL_I128, nullptr);
1507 setLibcallName(RTLIB::SRL_I128, nullptr);
1508 setLibcallName(RTLIB::SRA_I128, nullptr);
1511 // Combine sin / cos into one node or libcall if possible.
1512 if (Subtarget->hasSinCos()) {
1513 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1514 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1515 if (Subtarget->isTargetDarwin()) {
1516 // For MacOSX, we don't want to the normal expansion of a libcall to
1517 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1519 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1520 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1524 // We have target-specific dag combine patterns for the following nodes:
1525 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1526 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1527 setTargetDAGCombine(ISD::VSELECT);
1528 setTargetDAGCombine(ISD::SELECT);
1529 setTargetDAGCombine(ISD::SHL);
1530 setTargetDAGCombine(ISD::SRA);
1531 setTargetDAGCombine(ISD::SRL);
1532 setTargetDAGCombine(ISD::OR);
1533 setTargetDAGCombine(ISD::AND);
1534 setTargetDAGCombine(ISD::ADD);
1535 setTargetDAGCombine(ISD::FADD);
1536 setTargetDAGCombine(ISD::FSUB);
1537 setTargetDAGCombine(ISD::FMA);
1538 setTargetDAGCombine(ISD::SUB);
1539 setTargetDAGCombine(ISD::LOAD);
1540 setTargetDAGCombine(ISD::STORE);
1541 setTargetDAGCombine(ISD::ZERO_EXTEND);
1542 setTargetDAGCombine(ISD::ANY_EXTEND);
1543 setTargetDAGCombine(ISD::SIGN_EXTEND);
1544 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1545 setTargetDAGCombine(ISD::TRUNCATE);
1546 setTargetDAGCombine(ISD::SINT_TO_FP);
1547 setTargetDAGCombine(ISD::SETCC);
1548 if (Subtarget->is64Bit())
1549 setTargetDAGCombine(ISD::MUL);
1550 setTargetDAGCombine(ISD::XOR);
1552 computeRegisterProperties();
1554 // On Darwin, -Os means optimize for size without hurting performance,
1555 // do not reduce the limit.
1556 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1557 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1558 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1559 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1560 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1561 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1562 setPrefLoopAlignment(4); // 2^4 bytes.
1564 // Predictable cmov don't hurt on atom because it's in-order.
1565 PredictableSelectIsExpensive = !Subtarget->isAtom();
1567 setPrefFunctionAlignment(4); // 2^4 bytes.
1570 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1572 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1574 if (Subtarget->hasAVX512())
1575 switch(VT.getVectorNumElements()) {
1576 case 8: return MVT::v8i1;
1577 case 16: return MVT::v16i1;
1580 return VT.changeVectorElementTypeToInteger();
1583 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1584 /// the desired ByVal argument alignment.
1585 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1588 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1589 if (VTy->getBitWidth() == 128)
1591 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1592 unsigned EltAlign = 0;
1593 getMaxByValAlign(ATy->getElementType(), EltAlign);
1594 if (EltAlign > MaxAlign)
1595 MaxAlign = EltAlign;
1596 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1597 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1598 unsigned EltAlign = 0;
1599 getMaxByValAlign(STy->getElementType(i), EltAlign);
1600 if (EltAlign > MaxAlign)
1601 MaxAlign = EltAlign;
1608 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1609 /// function arguments in the caller parameter area. For X86, aggregates
1610 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1611 /// are at 4-byte boundaries.
1612 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1613 if (Subtarget->is64Bit()) {
1614 // Max of 8 and alignment of type.
1615 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1622 if (Subtarget->hasSSE1())
1623 getMaxByValAlign(Ty, Align);
1627 /// getOptimalMemOpType - Returns the target specific optimal type for load
1628 /// and store operations as a result of memset, memcpy, and memmove
1629 /// lowering. If DstAlign is zero that means it's safe to destination
1630 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1631 /// means there isn't a need to check it against alignment requirement,
1632 /// probably because the source does not need to be loaded. If 'IsMemset' is
1633 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1634 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1635 /// source is constant so it does not need to be loaded.
1636 /// It returns EVT::Other if the type should be determined using generic
1637 /// target-independent logic.
1639 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1640 unsigned DstAlign, unsigned SrcAlign,
1641 bool IsMemset, bool ZeroMemset,
1643 MachineFunction &MF) const {
1644 const Function *F = MF.getFunction();
1645 if ((!IsMemset || ZeroMemset) &&
1646 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1647 Attribute::NoImplicitFloat)) {
1649 (Subtarget->isUnalignedMemAccessFast() ||
1650 ((DstAlign == 0 || DstAlign >= 16) &&
1651 (SrcAlign == 0 || SrcAlign >= 16)))) {
1653 if (Subtarget->hasInt256())
1655 if (Subtarget->hasFp256())
1658 if (Subtarget->hasSSE2())
1660 if (Subtarget->hasSSE1())
1662 } else if (!MemcpyStrSrc && Size >= 8 &&
1663 !Subtarget->is64Bit() &&
1664 Subtarget->hasSSE2()) {
1665 // Do not use f64 to lower memcpy if source is string constant. It's
1666 // better to use i32 to avoid the loads.
1670 if (Subtarget->is64Bit() && Size >= 8)
1675 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1677 return X86ScalarSSEf32;
1678 else if (VT == MVT::f64)
1679 return X86ScalarSSEf64;
1684 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1688 *Fast = Subtarget->isUnalignedMemAccessFast();
1692 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1693 /// current function. The returned value is a member of the
1694 /// MachineJumpTableInfo::JTEntryKind enum.
1695 unsigned X86TargetLowering::getJumpTableEncoding() const {
1696 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1698 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1699 Subtarget->isPICStyleGOT())
1700 return MachineJumpTableInfo::EK_Custom32;
1702 // Otherwise, use the normal jump table encoding heuristics.
1703 return TargetLowering::getJumpTableEncoding();
1707 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1708 const MachineBasicBlock *MBB,
1709 unsigned uid,MCContext &Ctx) const{
1710 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1711 Subtarget->isPICStyleGOT());
1712 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1714 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1715 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1718 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1720 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1721 SelectionDAG &DAG) const {
1722 if (!Subtarget->is64Bit())
1723 // This doesn't have SDLoc associated with it, but is not really the
1724 // same as a Register.
1725 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1729 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1730 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1732 const MCExpr *X86TargetLowering::
1733 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1734 MCContext &Ctx) const {
1735 // X86-64 uses RIP relative addressing based on the jump table label.
1736 if (Subtarget->isPICStyleRIPRel())
1737 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1739 // Otherwise, the reference is relative to the PIC base.
1740 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1743 // FIXME: Why this routine is here? Move to RegInfo!
1744 std::pair<const TargetRegisterClass*, uint8_t>
1745 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1746 const TargetRegisterClass *RRC = nullptr;
1748 switch (VT.SimpleTy) {
1750 return TargetLowering::findRepresentativeClass(VT);
1751 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1752 RRC = Subtarget->is64Bit() ?
1753 (const TargetRegisterClass*)&X86::GR64RegClass :
1754 (const TargetRegisterClass*)&X86::GR32RegClass;
1757 RRC = &X86::VR64RegClass;
1759 case MVT::f32: case MVT::f64:
1760 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1761 case MVT::v4f32: case MVT::v2f64:
1762 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1764 RRC = &X86::VR128RegClass;
1767 return std::make_pair(RRC, Cost);
1770 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1771 unsigned &Offset) const {
1772 if (!Subtarget->isTargetLinux())
1775 if (Subtarget->is64Bit()) {
1776 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1778 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1790 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1791 unsigned DestAS) const {
1792 assert(SrcAS != DestAS && "Expected different address spaces!");
1794 return SrcAS < 256 && DestAS < 256;
1797 //===----------------------------------------------------------------------===//
1798 // Return Value Calling Convention Implementation
1799 //===----------------------------------------------------------------------===//
1801 #include "X86GenCallingConv.inc"
1804 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1805 MachineFunction &MF, bool isVarArg,
1806 const SmallVectorImpl<ISD::OutputArg> &Outs,
1807 LLVMContext &Context) const {
1808 SmallVector<CCValAssign, 16> RVLocs;
1809 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1811 return CCInfo.CheckReturn(Outs, RetCC_X86);
1814 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1815 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1820 X86TargetLowering::LowerReturn(SDValue Chain,
1821 CallingConv::ID CallConv, bool isVarArg,
1822 const SmallVectorImpl<ISD::OutputArg> &Outs,
1823 const SmallVectorImpl<SDValue> &OutVals,
1824 SDLoc dl, SelectionDAG &DAG) const {
1825 MachineFunction &MF = DAG.getMachineFunction();
1826 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1828 SmallVector<CCValAssign, 16> RVLocs;
1829 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1830 RVLocs, *DAG.getContext());
1831 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1834 SmallVector<SDValue, 6> RetOps;
1835 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1836 // Operand #1 = Bytes To Pop
1837 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1840 // Copy the result values into the output registers.
1841 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1842 CCValAssign &VA = RVLocs[i];
1843 assert(VA.isRegLoc() && "Can only return in registers!");
1844 SDValue ValToCopy = OutVals[i];
1845 EVT ValVT = ValToCopy.getValueType();
1847 // Promote values to the appropriate types
1848 if (VA.getLocInfo() == CCValAssign::SExt)
1849 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1850 else if (VA.getLocInfo() == CCValAssign::ZExt)
1851 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1852 else if (VA.getLocInfo() == CCValAssign::AExt)
1853 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1854 else if (VA.getLocInfo() == CCValAssign::BCvt)
1855 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1857 assert(VA.getLocInfo() != CCValAssign::FPExt &&
1858 "Unexpected FP-extend for return value.");
1860 // If this is x86-64, and we disabled SSE, we can't return FP values,
1861 // or SSE or MMX vectors.
1862 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1863 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1864 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1865 report_fatal_error("SSE register return with SSE disabled");
1867 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1868 // llvm-gcc has never done it right and no one has noticed, so this
1869 // should be OK for now.
1870 if (ValVT == MVT::f64 &&
1871 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1872 report_fatal_error("SSE2 register return with SSE2 disabled");
1874 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1875 // the RET instruction and handled by the FP Stackifier.
1876 if (VA.getLocReg() == X86::ST0 ||
1877 VA.getLocReg() == X86::ST1) {
1878 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1879 // change the value to the FP stack register class.
1880 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1881 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1882 RetOps.push_back(ValToCopy);
1883 // Don't emit a copytoreg.
1887 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1888 // which is returned in RAX / RDX.
1889 if (Subtarget->is64Bit()) {
1890 if (ValVT == MVT::x86mmx) {
1891 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1892 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1893 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1895 // If we don't have SSE2 available, convert to v4f32 so the generated
1896 // register is legal.
1897 if (!Subtarget->hasSSE2())
1898 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1903 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1904 Flag = Chain.getValue(1);
1905 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1908 // The x86-64 ABIs require that for returning structs by value we copy
1909 // the sret argument into %rax/%eax (depending on ABI) for the return.
1910 // Win32 requires us to put the sret argument to %eax as well.
1911 // We saved the argument into a virtual register in the entry block,
1912 // so now we copy the value out and into %rax/%eax.
1913 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1914 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1915 MachineFunction &MF = DAG.getMachineFunction();
1916 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1917 unsigned Reg = FuncInfo->getSRetReturnReg();
1919 "SRetReturnReg should have been set in LowerFormalArguments().");
1920 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1923 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1924 X86::RAX : X86::EAX;
1925 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1926 Flag = Chain.getValue(1);
1928 // RAX/EAX now acts like a return value.
1929 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1932 RetOps[0] = Chain; // Update chain.
1934 // Add the flag if we have it.
1936 RetOps.push_back(Flag);
1938 return DAG.getNode(X86ISD::RET_FLAG, dl,
1939 MVT::Other, &RetOps[0], RetOps.size());
1942 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1943 if (N->getNumValues() != 1)
1945 if (!N->hasNUsesOfValue(1, 0))
1948 SDValue TCChain = Chain;
1949 SDNode *Copy = *N->use_begin();
1950 if (Copy->getOpcode() == ISD::CopyToReg) {
1951 // If the copy has a glue operand, we conservatively assume it isn't safe to
1952 // perform a tail call.
1953 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1955 TCChain = Copy->getOperand(0);
1956 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1959 bool HasRet = false;
1960 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1962 if (UI->getOpcode() != X86ISD::RET_FLAG)
1975 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1976 ISD::NodeType ExtendKind) const {
1978 // TODO: Is this also valid on 32-bit?
1979 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1980 ReturnMVT = MVT::i8;
1982 ReturnMVT = MVT::i32;
1984 MVT MinVT = getRegisterType(ReturnMVT);
1985 return VT.bitsLT(MinVT) ? MinVT : VT;
1988 /// LowerCallResult - Lower the result values of a call into the
1989 /// appropriate copies out of appropriate physical registers.
1992 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1993 CallingConv::ID CallConv, bool isVarArg,
1994 const SmallVectorImpl<ISD::InputArg> &Ins,
1995 SDLoc dl, SelectionDAG &DAG,
1996 SmallVectorImpl<SDValue> &InVals) const {
1998 // Assign locations to each value returned by this call.
1999 SmallVector<CCValAssign, 16> RVLocs;
2000 bool Is64Bit = Subtarget->is64Bit();
2001 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2002 getTargetMachine(), RVLocs, *DAG.getContext());
2003 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2005 // Copy all of the result registers out of their specified physreg.
2006 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2007 CCValAssign &VA = RVLocs[i];
2008 EVT CopyVT = VA.getValVT();
2010 // If this is x86-64, and we disabled SSE, we can't return FP values
2011 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2012 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2013 report_fatal_error("SSE register return with SSE disabled");
2018 // If this is a call to a function that returns an fp value on the floating
2019 // point stack, we must guarantee the value is popped from the stack, so
2020 // a CopyFromReg is not good enough - the copy instruction may be eliminated
2021 // if the return value is not used. We use the FpPOP_RETVAL instruction
2023 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2024 // If we prefer to use the value in xmm registers, copy it out as f80 and
2025 // use a truncate to move it from fp stack reg to xmm reg.
2026 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2027 SDValue Ops[] = { Chain, InFlag };
2028 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2029 MVT::Other, MVT::Glue, Ops), 1);
2030 Val = Chain.getValue(0);
2032 // Round the f80 to the right size, which also moves it to the appropriate
2034 if (CopyVT != VA.getValVT())
2035 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2036 // This truncation won't change the value.
2037 DAG.getIntPtrConstant(1));
2039 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2040 CopyVT, InFlag).getValue(1);
2041 Val = Chain.getValue(0);
2043 InFlag = Chain.getValue(2);
2044 InVals.push_back(Val);
2050 //===----------------------------------------------------------------------===//
2051 // C & StdCall & Fast Calling Convention implementation
2052 //===----------------------------------------------------------------------===//
2053 // StdCall calling convention seems to be standard for many Windows' API
2054 // routines and around. It differs from C calling convention just a little:
2055 // callee should clean up the stack, not caller. Symbols should be also
2056 // decorated in some fancy way :) It doesn't support any vector arguments.
2057 // For info on fast calling convention see Fast Calling Convention (tail call)
2058 // implementation LowerX86_32FastCCCallTo.
2060 /// CallIsStructReturn - Determines whether a call uses struct return
2062 enum StructReturnType {
2067 static StructReturnType
2068 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2070 return NotStructReturn;
2072 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2073 if (!Flags.isSRet())
2074 return NotStructReturn;
2075 if (Flags.isInReg())
2076 return RegStructReturn;
2077 return StackStructReturn;
2080 /// ArgsAreStructReturn - Determines whether a function uses struct
2081 /// return semantics.
2082 static StructReturnType
2083 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2085 return NotStructReturn;
2087 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2088 if (!Flags.isSRet())
2089 return NotStructReturn;
2090 if (Flags.isInReg())
2091 return RegStructReturn;
2092 return StackStructReturn;
2095 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2096 /// by "Src" to address "Dst" with size and alignment information specified by
2097 /// the specific parameter attribute. The copy will be passed as a byval
2098 /// function parameter.
2100 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2101 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2103 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2105 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2106 /*isVolatile*/false, /*AlwaysInline=*/true,
2107 MachinePointerInfo(), MachinePointerInfo());
2110 /// IsTailCallConvention - Return true if the calling convention is one that
2111 /// supports tail call optimization.
2112 static bool IsTailCallConvention(CallingConv::ID CC) {
2113 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2114 CC == CallingConv::HiPE);
2117 /// \brief Return true if the calling convention is a C calling convention.
2118 static bool IsCCallConvention(CallingConv::ID CC) {
2119 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2120 CC == CallingConv::X86_64_SysV);
2123 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2124 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2128 CallingConv::ID CalleeCC = CS.getCallingConv();
2129 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2135 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2136 /// a tailcall target by changing its ABI.
2137 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2138 bool GuaranteedTailCallOpt) {
2139 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2143 X86TargetLowering::LowerMemArgument(SDValue Chain,
2144 CallingConv::ID CallConv,
2145 const SmallVectorImpl<ISD::InputArg> &Ins,
2146 SDLoc dl, SelectionDAG &DAG,
2147 const CCValAssign &VA,
2148 MachineFrameInfo *MFI,
2150 // Create the nodes corresponding to a load from this parameter slot.
2151 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2152 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2153 getTargetMachine().Options.GuaranteedTailCallOpt);
2154 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2157 // If value is passed by pointer we have address passed instead of the value
2159 if (VA.getLocInfo() == CCValAssign::Indirect)
2160 ValVT = VA.getLocVT();
2162 ValVT = VA.getValVT();
2164 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2165 // changed with more analysis.
2166 // In case of tail call optimization mark all arguments mutable. Since they
2167 // could be overwritten by lowering of arguments in case of a tail call.
2168 if (Flags.isByVal()) {
2169 unsigned Bytes = Flags.getByValSize();
2170 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2171 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2172 return DAG.getFrameIndex(FI, getPointerTy());
2174 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2175 VA.getLocMemOffset(), isImmutable);
2176 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2177 return DAG.getLoad(ValVT, dl, Chain, FIN,
2178 MachinePointerInfo::getFixedStack(FI),
2179 false, false, false, 0);
2184 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2185 CallingConv::ID CallConv,
2187 const SmallVectorImpl<ISD::InputArg> &Ins,
2190 SmallVectorImpl<SDValue> &InVals)
2192 MachineFunction &MF = DAG.getMachineFunction();
2193 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2195 const Function* Fn = MF.getFunction();
2196 if (Fn->hasExternalLinkage() &&
2197 Subtarget->isTargetCygMing() &&
2198 Fn->getName() == "main")
2199 FuncInfo->setForceFramePointer(true);
2201 MachineFrameInfo *MFI = MF.getFrameInfo();
2202 bool Is64Bit = Subtarget->is64Bit();
2203 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2205 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2206 "Var args not supported with calling convention fastcc, ghc or hipe");
2208 // Assign locations to all of the incoming arguments.
2209 SmallVector<CCValAssign, 16> ArgLocs;
2210 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2211 ArgLocs, *DAG.getContext());
2213 // Allocate shadow area for Win64
2215 CCInfo.AllocateStack(32, 8);
2217 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2219 unsigned LastVal = ~0U;
2221 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2222 CCValAssign &VA = ArgLocs[i];
2223 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2225 assert(VA.getValNo() != LastVal &&
2226 "Don't support value assigned to multiple locs yet");
2228 LastVal = VA.getValNo();
2230 if (VA.isRegLoc()) {
2231 EVT RegVT = VA.getLocVT();
2232 const TargetRegisterClass *RC;
2233 if (RegVT == MVT::i32)
2234 RC = &X86::GR32RegClass;
2235 else if (Is64Bit && RegVT == MVT::i64)
2236 RC = &X86::GR64RegClass;
2237 else if (RegVT == MVT::f32)
2238 RC = &X86::FR32RegClass;
2239 else if (RegVT == MVT::f64)
2240 RC = &X86::FR64RegClass;
2241 else if (RegVT.is512BitVector())
2242 RC = &X86::VR512RegClass;
2243 else if (RegVT.is256BitVector())
2244 RC = &X86::VR256RegClass;
2245 else if (RegVT.is128BitVector())
2246 RC = &X86::VR128RegClass;
2247 else if (RegVT == MVT::x86mmx)
2248 RC = &X86::VR64RegClass;
2249 else if (RegVT == MVT::i1)
2250 RC = &X86::VK1RegClass;
2251 else if (RegVT == MVT::v8i1)
2252 RC = &X86::VK8RegClass;
2253 else if (RegVT == MVT::v16i1)
2254 RC = &X86::VK16RegClass;
2256 llvm_unreachable("Unknown argument type!");
2258 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2259 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2261 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2262 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2264 if (VA.getLocInfo() == CCValAssign::SExt)
2265 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2266 DAG.getValueType(VA.getValVT()));
2267 else if (VA.getLocInfo() == CCValAssign::ZExt)
2268 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2269 DAG.getValueType(VA.getValVT()));
2270 else if (VA.getLocInfo() == CCValAssign::BCvt)
2271 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2273 if (VA.isExtInLoc()) {
2274 // Handle MMX values passed in XMM regs.
2275 if (RegVT.isVector())
2276 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2278 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2281 assert(VA.isMemLoc());
2282 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2285 // If value is passed via pointer - do a load.
2286 if (VA.getLocInfo() == CCValAssign::Indirect)
2287 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2288 MachinePointerInfo(), false, false, false, 0);
2290 InVals.push_back(ArgValue);
2293 // The x86-64 ABIs require that for returning structs by value we copy
2294 // the sret argument into %rax/%eax (depending on ABI) for the return.
2295 // Win32 requires us to put the sret argument to %eax as well.
2296 // Save the argument into a virtual register so that we can access it
2297 // from the return points.
2298 if (MF.getFunction()->hasStructRetAttr() &&
2299 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2300 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2301 unsigned Reg = FuncInfo->getSRetReturnReg();
2303 MVT PtrTy = getPointerTy();
2304 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2305 FuncInfo->setSRetReturnReg(Reg);
2307 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2308 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2311 unsigned StackSize = CCInfo.getNextStackOffset();
2312 // Align stack specially for tail calls.
2313 if (FuncIsMadeTailCallSafe(CallConv,
2314 MF.getTarget().Options.GuaranteedTailCallOpt))
2315 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2317 // If the function takes variable number of arguments, make a frame index for
2318 // the start of the first vararg value... for expansion of llvm.va_start.
2320 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2321 CallConv != CallingConv::X86_ThisCall)) {
2322 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2325 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2327 // FIXME: We should really autogenerate these arrays
2328 static const MCPhysReg GPR64ArgRegsWin64[] = {
2329 X86::RCX, X86::RDX, X86::R8, X86::R9
2331 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2332 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2334 static const MCPhysReg XMMArgRegs64Bit[] = {
2335 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2336 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2338 const MCPhysReg *GPR64ArgRegs;
2339 unsigned NumXMMRegs = 0;
2342 // The XMM registers which might contain var arg parameters are shadowed
2343 // in their paired GPR. So we only need to save the GPR to their home
2345 TotalNumIntRegs = 4;
2346 GPR64ArgRegs = GPR64ArgRegsWin64;
2348 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2349 GPR64ArgRegs = GPR64ArgRegs64Bit;
2351 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2354 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2357 bool NoImplicitFloatOps = Fn->getAttributes().
2358 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2359 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2360 "SSE register cannot be used when SSE is disabled!");
2361 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2362 NoImplicitFloatOps) &&
2363 "SSE register cannot be used when SSE is disabled!");
2364 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2365 !Subtarget->hasSSE1())
2366 // Kernel mode asks for SSE to be disabled, so don't push them
2368 TotalNumXMMRegs = 0;
2371 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2372 // Get to the caller-allocated home save location. Add 8 to account
2373 // for the return address.
2374 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2375 FuncInfo->setRegSaveFrameIndex(
2376 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2377 // Fixup to set vararg frame on shadow area (4 x i64).
2379 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2381 // For X86-64, if there are vararg parameters that are passed via
2382 // registers, then we must store them to their spots on the stack so
2383 // they may be loaded by deferencing the result of va_next.
2384 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2385 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2386 FuncInfo->setRegSaveFrameIndex(
2387 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2391 // Store the integer parameter registers.
2392 SmallVector<SDValue, 8> MemOps;
2393 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2395 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2396 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2397 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2398 DAG.getIntPtrConstant(Offset));
2399 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2400 &X86::GR64RegClass);
2401 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2403 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2404 MachinePointerInfo::getFixedStack(
2405 FuncInfo->getRegSaveFrameIndex(), Offset),
2407 MemOps.push_back(Store);
2411 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2412 // Now store the XMM (fp + vector) parameter registers.
2413 SmallVector<SDValue, 11> SaveXMMOps;
2414 SaveXMMOps.push_back(Chain);
2416 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2417 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2418 SaveXMMOps.push_back(ALVal);
2420 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2421 FuncInfo->getRegSaveFrameIndex()));
2422 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2423 FuncInfo->getVarArgsFPOffset()));
2425 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2426 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2427 &X86::VR128RegClass);
2428 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2429 SaveXMMOps.push_back(Val);
2431 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2433 &SaveXMMOps[0], SaveXMMOps.size()));
2436 if (!MemOps.empty())
2437 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2438 &MemOps[0], MemOps.size());
2442 // Some CCs need callee pop.
2443 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2444 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2445 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2447 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2448 // If this is an sret function, the return should pop the hidden pointer.
2449 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2450 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2451 argsAreStructReturn(Ins) == StackStructReturn)
2452 FuncInfo->setBytesToPopOnReturn(4);
2456 // RegSaveFrameIndex is X86-64 only.
2457 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2458 if (CallConv == CallingConv::X86_FastCall ||
2459 CallConv == CallingConv::X86_ThisCall)
2460 // fastcc functions can't have varargs.
2461 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2464 FuncInfo->setArgumentStackSize(StackSize);
2470 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2471 SDValue StackPtr, SDValue Arg,
2472 SDLoc dl, SelectionDAG &DAG,
2473 const CCValAssign &VA,
2474 ISD::ArgFlagsTy Flags) const {
2475 unsigned LocMemOffset = VA.getLocMemOffset();
2476 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2477 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2478 if (Flags.isByVal())
2479 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2481 return DAG.getStore(Chain, dl, Arg, PtrOff,
2482 MachinePointerInfo::getStack(LocMemOffset),
2486 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2487 /// optimization is performed and it is required.
2489 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2490 SDValue &OutRetAddr, SDValue Chain,
2491 bool IsTailCall, bool Is64Bit,
2492 int FPDiff, SDLoc dl) const {
2493 // Adjust the Return address stack slot.
2494 EVT VT = getPointerTy();
2495 OutRetAddr = getReturnAddressFrameIndex(DAG);
2497 // Load the "old" Return address.
2498 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2499 false, false, false, 0);
2500 return SDValue(OutRetAddr.getNode(), 1);
2503 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2504 /// optimization is performed and it is required (FPDiff!=0).
2506 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2507 SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2508 unsigned SlotSize, int FPDiff, SDLoc dl) {
2509 // Store the return address to the appropriate stack slot.
2510 if (!FPDiff) return Chain;
2511 // Calculate the new stack slot for the return address.
2512 int NewReturnAddrFI =
2513 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2515 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2516 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2517 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2523 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2524 SmallVectorImpl<SDValue> &InVals) const {
2525 SelectionDAG &DAG = CLI.DAG;
2527 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2528 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2529 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2530 SDValue Chain = CLI.Chain;
2531 SDValue Callee = CLI.Callee;
2532 CallingConv::ID CallConv = CLI.CallConv;
2533 bool &isTailCall = CLI.IsTailCall;
2534 bool isVarArg = CLI.IsVarArg;
2536 MachineFunction &MF = DAG.getMachineFunction();
2537 bool Is64Bit = Subtarget->is64Bit();
2538 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2539 StructReturnType SR = callIsStructReturn(Outs);
2540 bool IsSibcall = false;
2542 if (MF.getTarget().Options.DisableTailCalls)
2546 // Check if it's really possible to do a tail call.
2547 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2548 isVarArg, SR != NotStructReturn,
2549 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2550 Outs, OutVals, Ins, DAG);
2552 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
2553 report_fatal_error("failed to perform tail call elimination on a call "
2554 "site marked musttail");
2556 // Sibcalls are automatically detected tailcalls which do not require
2558 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2565 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2566 "Var args not supported with calling convention fastcc, ghc or hipe");
2568 // Analyze operands of the call, assigning locations to each operand.
2569 SmallVector<CCValAssign, 16> ArgLocs;
2570 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2571 ArgLocs, *DAG.getContext());
2573 // Allocate shadow area for Win64
2575 CCInfo.AllocateStack(32, 8);
2577 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2579 // Get a count of how many bytes are to be pushed on the stack.
2580 unsigned NumBytes = CCInfo.getNextStackOffset();
2582 // This is a sibcall. The memory operands are available in caller's
2583 // own caller's stack.
2585 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2586 IsTailCallConvention(CallConv))
2587 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2590 if (isTailCall && !IsSibcall) {
2591 // Lower arguments at fp - stackoffset + fpdiff.
2592 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2593 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2595 FPDiff = NumBytesCallerPushed - NumBytes;
2597 // Set the delta of movement of the returnaddr stackslot.
2598 // But only set if delta is greater than previous delta.
2599 if (FPDiff < X86Info->getTCReturnAddrDelta())
2600 X86Info->setTCReturnAddrDelta(FPDiff);
2603 unsigned NumBytesToPush = NumBytes;
2604 unsigned NumBytesToPop = NumBytes;
2606 // If we have an inalloca argument, all stack space has already been allocated
2607 // for us and be right at the top of the stack. We don't support multiple
2608 // arguments passed in memory when using inalloca.
2609 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2611 assert(ArgLocs.back().getLocMemOffset() == 0 &&
2612 "an inalloca argument must be the only memory argument");
2616 Chain = DAG.getCALLSEQ_START(
2617 Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2619 SDValue RetAddrFrIdx;
2620 // Load return address for tail calls.
2621 if (isTailCall && FPDiff)
2622 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2623 Is64Bit, FPDiff, dl);
2625 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2626 SmallVector<SDValue, 8> MemOpChains;
2629 // Walk the register/memloc assignments, inserting copies/loads. In the case
2630 // of tail call optimization arguments are handle later.
2631 const X86RegisterInfo *RegInfo =
2632 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2633 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2634 // Skip inalloca arguments, they have already been written.
2635 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2636 if (Flags.isInAlloca())
2639 CCValAssign &VA = ArgLocs[i];
2640 EVT RegVT = VA.getLocVT();
2641 SDValue Arg = OutVals[i];
2642 bool isByVal = Flags.isByVal();
2644 // Promote the value if needed.
2645 switch (VA.getLocInfo()) {
2646 default: llvm_unreachable("Unknown loc info!");
2647 case CCValAssign::Full: break;
2648 case CCValAssign::SExt:
2649 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2651 case CCValAssign::ZExt:
2652 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2654 case CCValAssign::AExt:
2655 if (RegVT.is128BitVector()) {
2656 // Special case: passing MMX values in XMM registers.
2657 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2658 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2659 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2661 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2663 case CCValAssign::BCvt:
2664 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2666 case CCValAssign::Indirect: {
2667 // Store the argument.
2668 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2669 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2670 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2671 MachinePointerInfo::getFixedStack(FI),
2678 if (VA.isRegLoc()) {
2679 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2680 if (isVarArg && IsWin64) {
2681 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2682 // shadow reg if callee is a varargs function.
2683 unsigned ShadowReg = 0;
2684 switch (VA.getLocReg()) {
2685 case X86::XMM0: ShadowReg = X86::RCX; break;
2686 case X86::XMM1: ShadowReg = X86::RDX; break;
2687 case X86::XMM2: ShadowReg = X86::R8; break;
2688 case X86::XMM3: ShadowReg = X86::R9; break;
2691 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2693 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2694 assert(VA.isMemLoc());
2695 if (!StackPtr.getNode())
2696 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2698 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2699 dl, DAG, VA, Flags));
2703 if (!MemOpChains.empty())
2704 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2705 &MemOpChains[0], MemOpChains.size());
2707 if (Subtarget->isPICStyleGOT()) {
2708 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2711 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2712 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2714 // If we are tail calling and generating PIC/GOT style code load the
2715 // address of the callee into ECX. The value in ecx is used as target of
2716 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2717 // for tail calls on PIC/GOT architectures. Normally we would just put the
2718 // address of GOT into ebx and then call target@PLT. But for tail calls
2719 // ebx would be restored (since ebx is callee saved) before jumping to the
2722 // Note: The actual moving to ECX is done further down.
2723 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2724 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2725 !G->getGlobal()->hasProtectedVisibility())
2726 Callee = LowerGlobalAddress(Callee, DAG);
2727 else if (isa<ExternalSymbolSDNode>(Callee))
2728 Callee = LowerExternalSymbol(Callee, DAG);
2732 if (Is64Bit && isVarArg && !IsWin64) {
2733 // From AMD64 ABI document:
2734 // For calls that may call functions that use varargs or stdargs
2735 // (prototype-less calls or calls to functions containing ellipsis (...) in
2736 // the declaration) %al is used as hidden argument to specify the number
2737 // of SSE registers used. The contents of %al do not need to match exactly
2738 // the number of registers, but must be an ubound on the number of SSE
2739 // registers used and is in the range 0 - 8 inclusive.
2741 // Count the number of XMM registers allocated.
2742 static const MCPhysReg XMMArgRegs[] = {
2743 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2744 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2746 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2747 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2748 && "SSE registers cannot be used when SSE is disabled");
2750 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2751 DAG.getConstant(NumXMMRegs, MVT::i8)));
2754 // For tail calls lower the arguments to the 'real' stack slot.
2756 // Force all the incoming stack arguments to be loaded from the stack
2757 // before any new outgoing arguments are stored to the stack, because the
2758 // outgoing stack slots may alias the incoming argument stack slots, and
2759 // the alias isn't otherwise explicit. This is slightly more conservative
2760 // than necessary, because it means that each store effectively depends
2761 // on every argument instead of just those arguments it would clobber.
2762 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2764 SmallVector<SDValue, 8> MemOpChains2;
2767 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2768 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2769 CCValAssign &VA = ArgLocs[i];
2772 assert(VA.isMemLoc());
2773 SDValue Arg = OutVals[i];
2774 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2775 // Create frame index.
2776 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2777 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2778 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2779 FIN = DAG.getFrameIndex(FI, getPointerTy());
2781 if (Flags.isByVal()) {
2782 // Copy relative to framepointer.
2783 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2784 if (!StackPtr.getNode())
2785 StackPtr = DAG.getCopyFromReg(Chain, dl,
2786 RegInfo->getStackRegister(),
2788 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2790 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2794 // Store relative to framepointer.
2795 MemOpChains2.push_back(
2796 DAG.getStore(ArgChain, dl, Arg, FIN,
2797 MachinePointerInfo::getFixedStack(FI),
2803 if (!MemOpChains2.empty())
2804 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2805 &MemOpChains2[0], MemOpChains2.size());
2807 // Store the return address to the appropriate stack slot.
2808 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2809 getPointerTy(), RegInfo->getSlotSize(),
2813 // Build a sequence of copy-to-reg nodes chained together with token chain
2814 // and flag operands which copy the outgoing args into registers.
2816 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2817 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2818 RegsToPass[i].second, InFlag);
2819 InFlag = Chain.getValue(1);
2822 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2823 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2824 // In the 64-bit large code model, we have to make all calls
2825 // through a register, since the call instruction's 32-bit
2826 // pc-relative offset may not be large enough to hold the whole
2828 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2829 // If the callee is a GlobalAddress node (quite common, every direct call
2830 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2833 // We should use extra load for direct calls to dllimported functions in
2835 const GlobalValue *GV = G->getGlobal();
2836 if (!GV->hasDLLImportStorageClass()) {
2837 unsigned char OpFlags = 0;
2838 bool ExtraLoad = false;
2839 unsigned WrapperKind = ISD::DELETED_NODE;
2841 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2842 // external symbols most go through the PLT in PIC mode. If the symbol
2843 // has hidden or protected visibility, or if it is static or local, then
2844 // we don't need to use the PLT - we can directly call it.
2845 if (Subtarget->isTargetELF() &&
2846 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2847 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2848 OpFlags = X86II::MO_PLT;
2849 } else if (Subtarget->isPICStyleStubAny() &&
2850 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2851 (!Subtarget->getTargetTriple().isMacOSX() ||
2852 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2853 // PC-relative references to external symbols should go through $stub,
2854 // unless we're building with the leopard linker or later, which
2855 // automatically synthesizes these stubs.
2856 OpFlags = X86II::MO_DARWIN_STUB;
2857 } else if (Subtarget->isPICStyleRIPRel() &&
2858 isa<Function>(GV) &&
2859 cast<Function>(GV)->getAttributes().
2860 hasAttribute(AttributeSet::FunctionIndex,
2861 Attribute::NonLazyBind)) {
2862 // If the function is marked as non-lazy, generate an indirect call
2863 // which loads from the GOT directly. This avoids runtime overhead
2864 // at the cost of eager binding (and one extra byte of encoding).
2865 OpFlags = X86II::MO_GOTPCREL;
2866 WrapperKind = X86ISD::WrapperRIP;
2870 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2871 G->getOffset(), OpFlags);
2873 // Add a wrapper if needed.
2874 if (WrapperKind != ISD::DELETED_NODE)
2875 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2876 // Add extra indirection if needed.
2878 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2879 MachinePointerInfo::getGOT(),
2880 false, false, false, 0);
2882 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2883 unsigned char OpFlags = 0;
2885 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2886 // external symbols should go through the PLT.
2887 if (Subtarget->isTargetELF() &&
2888 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2889 OpFlags = X86II::MO_PLT;
2890 } else if (Subtarget->isPICStyleStubAny() &&
2891 (!Subtarget->getTargetTriple().isMacOSX() ||
2892 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2893 // PC-relative references to external symbols should go through $stub,
2894 // unless we're building with the leopard linker or later, which
2895 // automatically synthesizes these stubs.
2896 OpFlags = X86II::MO_DARWIN_STUB;
2899 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2903 // Returns a chain & a flag for retval copy to use.
2904 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2905 SmallVector<SDValue, 8> Ops;
2907 if (!IsSibcall && isTailCall) {
2908 Chain = DAG.getCALLSEQ_END(Chain,
2909 DAG.getIntPtrConstant(NumBytesToPop, true),
2910 DAG.getIntPtrConstant(0, true), InFlag, dl);
2911 InFlag = Chain.getValue(1);
2914 Ops.push_back(Chain);
2915 Ops.push_back(Callee);
2918 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2920 // Add argument registers to the end of the list so that they are known live
2922 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2923 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2924 RegsToPass[i].second.getValueType()));
2926 // Add a register mask operand representing the call-preserved registers.
2927 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2928 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2929 assert(Mask && "Missing call preserved mask for calling convention");
2930 Ops.push_back(DAG.getRegisterMask(Mask));
2932 if (InFlag.getNode())
2933 Ops.push_back(InFlag);
2937 //// If this is the first return lowered for this function, add the regs
2938 //// to the liveout set for the function.
2939 // This isn't right, although it's probably harmless on x86; liveouts
2940 // should be computed from returns not tail calls. Consider a void
2941 // function making a tail call to a function returning int.
2942 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
2945 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2946 InFlag = Chain.getValue(1);
2948 // Create the CALLSEQ_END node.
2949 unsigned NumBytesForCalleeToPop;
2950 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2951 getTargetMachine().Options.GuaranteedTailCallOpt))
2952 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
2953 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2954 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2955 SR == StackStructReturn)
2956 // If this is a call to a struct-return function, the callee
2957 // pops the hidden struct pointer, so we have to push it back.
2958 // This is common for Darwin/X86, Linux & Mingw32 targets.
2959 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2960 NumBytesForCalleeToPop = 4;
2962 NumBytesForCalleeToPop = 0; // Callee pops nothing.
2964 // Returns a flag for retval copy to use.
2966 Chain = DAG.getCALLSEQ_END(Chain,
2967 DAG.getIntPtrConstant(NumBytesToPop, true),
2968 DAG.getIntPtrConstant(NumBytesForCalleeToPop,
2971 InFlag = Chain.getValue(1);
2974 // Handle result values, copying them out of physregs into vregs that we
2976 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2977 Ins, dl, DAG, InVals);
2980 //===----------------------------------------------------------------------===//
2981 // Fast Calling Convention (tail call) implementation
2982 //===----------------------------------------------------------------------===//
2984 // Like std call, callee cleans arguments, convention except that ECX is
2985 // reserved for storing the tail called function address. Only 2 registers are
2986 // free for argument passing (inreg). Tail call optimization is performed
2988 // * tailcallopt is enabled
2989 // * caller/callee are fastcc
2990 // On X86_64 architecture with GOT-style position independent code only local
2991 // (within module) calls are supported at the moment.
2992 // To keep the stack aligned according to platform abi the function
2993 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2994 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2995 // If a tail called function callee has more arguments than the caller the
2996 // caller needs to make sure that there is room to move the RETADDR to. This is
2997 // achieved by reserving an area the size of the argument delta right after the
2998 // original REtADDR, but before the saved framepointer or the spilled registers
2999 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3011 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3012 /// for a 16 byte align requirement.
3014 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3015 SelectionDAG& DAG) const {
3016 MachineFunction &MF = DAG.getMachineFunction();
3017 const TargetMachine &TM = MF.getTarget();
3018 const X86RegisterInfo *RegInfo =
3019 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3020 const TargetFrameLowering &TFI = *TM.getFrameLowering();
3021 unsigned StackAlignment = TFI.getStackAlignment();
3022 uint64_t AlignMask = StackAlignment - 1;
3023 int64_t Offset = StackSize;
3024 unsigned SlotSize = RegInfo->getSlotSize();
3025 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3026 // Number smaller than 12 so just add the difference.
3027 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3029 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3030 Offset = ((~AlignMask) & Offset) + StackAlignment +
3031 (StackAlignment-SlotSize);
3036 /// MatchingStackOffset - Return true if the given stack call argument is
3037 /// already available in the same position (relatively) of the caller's
3038 /// incoming argument stack.
3040 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3041 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3042 const X86InstrInfo *TII) {
3043 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3045 if (Arg.getOpcode() == ISD::CopyFromReg) {
3046 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3047 if (!TargetRegisterInfo::isVirtualRegister(VR))
3049 MachineInstr *Def = MRI->getVRegDef(VR);
3052 if (!Flags.isByVal()) {
3053 if (!TII->isLoadFromStackSlot(Def, FI))
3056 unsigned Opcode = Def->getOpcode();
3057 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3058 Def->getOperand(1).isFI()) {
3059 FI = Def->getOperand(1).getIndex();
3060 Bytes = Flags.getByValSize();
3064 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3065 if (Flags.isByVal())
3066 // ByVal argument is passed in as a pointer but it's now being
3067 // dereferenced. e.g.
3068 // define @foo(%struct.X* %A) {
3069 // tail call @bar(%struct.X* byval %A)
3072 SDValue Ptr = Ld->getBasePtr();
3073 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3076 FI = FINode->getIndex();
3077 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3078 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3079 FI = FINode->getIndex();
3080 Bytes = Flags.getByValSize();
3084 assert(FI != INT_MAX);
3085 if (!MFI->isFixedObjectIndex(FI))
3087 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3090 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3091 /// for tail call optimization. Targets which want to do tail call
3092 /// optimization should implement this function.
3094 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3095 CallingConv::ID CalleeCC,
3097 bool isCalleeStructRet,
3098 bool isCallerStructRet,
3100 const SmallVectorImpl<ISD::OutputArg> &Outs,
3101 const SmallVectorImpl<SDValue> &OutVals,
3102 const SmallVectorImpl<ISD::InputArg> &Ins,
3103 SelectionDAG &DAG) const {
3104 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3107 // If -tailcallopt is specified, make fastcc functions tail-callable.
3108 const MachineFunction &MF = DAG.getMachineFunction();
3109 const Function *CallerF = MF.getFunction();
3111 // If the function return type is x86_fp80 and the callee return type is not,
3112 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3113 // perform a tailcall optimization here.
3114 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3117 CallingConv::ID CallerCC = CallerF->getCallingConv();
3118 bool CCMatch = CallerCC == CalleeCC;
3119 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3120 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3122 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3123 if (IsTailCallConvention(CalleeCC) && CCMatch)
3128 // Look for obvious safe cases to perform tail call optimization that do not
3129 // require ABI changes. This is what gcc calls sibcall.
3131 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3132 // emit a special epilogue.
3133 const X86RegisterInfo *RegInfo =
3134 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3135 if (RegInfo->needsStackRealignment(MF))
3138 // Also avoid sibcall optimization if either caller or callee uses struct
3139 // return semantics.
3140 if (isCalleeStructRet || isCallerStructRet)
3143 // An stdcall/thiscall caller is expected to clean up its arguments; the
3144 // callee isn't going to do that.
3145 // FIXME: this is more restrictive than needed. We could produce a tailcall
3146 // when the stack adjustment matches. For example, with a thiscall that takes
3147 // only one argument.
3148 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3149 CallerCC == CallingConv::X86_ThisCall))
3152 // Do not sibcall optimize vararg calls unless all arguments are passed via
3154 if (isVarArg && !Outs.empty()) {
3156 // Optimizing for varargs on Win64 is unlikely to be safe without
3157 // additional testing.
3158 if (IsCalleeWin64 || IsCallerWin64)
3161 SmallVector<CCValAssign, 16> ArgLocs;
3162 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3163 getTargetMachine(), ArgLocs, *DAG.getContext());
3165 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3166 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3167 if (!ArgLocs[i].isRegLoc())
3171 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3172 // stack. Therefore, if it's not used by the call it is not safe to optimize
3173 // this into a sibcall.
3174 bool Unused = false;
3175 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3182 SmallVector<CCValAssign, 16> RVLocs;
3183 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3184 getTargetMachine(), RVLocs, *DAG.getContext());
3185 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3186 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3187 CCValAssign &VA = RVLocs[i];
3188 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3193 // If the calling conventions do not match, then we'd better make sure the
3194 // results are returned in the same way as what the caller expects.
3196 SmallVector<CCValAssign, 16> RVLocs1;
3197 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3198 getTargetMachine(), RVLocs1, *DAG.getContext());
3199 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3201 SmallVector<CCValAssign, 16> RVLocs2;
3202 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3203 getTargetMachine(), RVLocs2, *DAG.getContext());
3204 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3206 if (RVLocs1.size() != RVLocs2.size())
3208 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3209 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3211 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3213 if (RVLocs1[i].isRegLoc()) {
3214 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3217 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3223 // If the callee takes no arguments then go on to check the results of the
3225 if (!Outs.empty()) {
3226 // Check if stack adjustment is needed. For now, do not do this if any
3227 // argument is passed on the stack.
3228 SmallVector<CCValAssign, 16> ArgLocs;
3229 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3230 getTargetMachine(), ArgLocs, *DAG.getContext());
3232 // Allocate shadow area for Win64
3234 CCInfo.AllocateStack(32, 8);
3236 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3237 if (CCInfo.getNextStackOffset()) {
3238 MachineFunction &MF = DAG.getMachineFunction();
3239 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3242 // Check if the arguments are already laid out in the right way as
3243 // the caller's fixed stack objects.
3244 MachineFrameInfo *MFI = MF.getFrameInfo();
3245 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3246 const X86InstrInfo *TII =
3247 ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3248 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3249 CCValAssign &VA = ArgLocs[i];
3250 SDValue Arg = OutVals[i];
3251 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3252 if (VA.getLocInfo() == CCValAssign::Indirect)
3254 if (!VA.isRegLoc()) {
3255 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3262 // If the tailcall address may be in a register, then make sure it's
3263 // possible to register allocate for it. In 32-bit, the call address can
3264 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3265 // callee-saved registers are restored. These happen to be the same
3266 // registers used to pass 'inreg' arguments so watch out for those.
3267 if (!Subtarget->is64Bit() &&
3268 ((!isa<GlobalAddressSDNode>(Callee) &&
3269 !isa<ExternalSymbolSDNode>(Callee)) ||
3270 getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3271 unsigned NumInRegs = 0;
3272 // In PIC we need an extra register to formulate the address computation
3274 unsigned MaxInRegs =
3275 (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3277 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3278 CCValAssign &VA = ArgLocs[i];
3281 unsigned Reg = VA.getLocReg();
3284 case X86::EAX: case X86::EDX: case X86::ECX:
3285 if (++NumInRegs == MaxInRegs)
3297 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3298 const TargetLibraryInfo *libInfo) const {
3299 return X86::createFastISel(funcInfo, libInfo);
3302 //===----------------------------------------------------------------------===//
3303 // Other Lowering Hooks
3304 //===----------------------------------------------------------------------===//
3306 static bool MayFoldLoad(SDValue Op) {
3307 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3310 static bool MayFoldIntoStore(SDValue Op) {
3311 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3314 static bool isTargetShuffle(unsigned Opcode) {
3316 default: return false;
3317 case X86ISD::PSHUFD:
3318 case X86ISD::PSHUFHW:
3319 case X86ISD::PSHUFLW:
3321 case X86ISD::PALIGNR:
3322 case X86ISD::MOVLHPS:
3323 case X86ISD::MOVLHPD:
3324 case X86ISD::MOVHLPS:
3325 case X86ISD::MOVLPS:
3326 case X86ISD::MOVLPD:
3327 case X86ISD::MOVSHDUP:
3328 case X86ISD::MOVSLDUP:
3329 case X86ISD::MOVDDUP:
3332 case X86ISD::UNPCKL:
3333 case X86ISD::UNPCKH:
3334 case X86ISD::VPERMILP:
3335 case X86ISD::VPERM2X128:
3336 case X86ISD::VPERMI:
3341 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3342 SDValue V1, SelectionDAG &DAG) {
3344 default: llvm_unreachable("Unknown x86 shuffle node");
3345 case X86ISD::MOVSHDUP:
3346 case X86ISD::MOVSLDUP:
3347 case X86ISD::MOVDDUP:
3348 return DAG.getNode(Opc, dl, VT, V1);
3352 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3353 SDValue V1, unsigned TargetMask,
3354 SelectionDAG &DAG) {
3356 default: llvm_unreachable("Unknown x86 shuffle node");
3357 case X86ISD::PSHUFD:
3358 case X86ISD::PSHUFHW:
3359 case X86ISD::PSHUFLW:
3360 case X86ISD::VPERMILP:
3361 case X86ISD::VPERMI:
3362 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3366 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3367 SDValue V1, SDValue V2, unsigned TargetMask,
3368 SelectionDAG &DAG) {
3370 default: llvm_unreachable("Unknown x86 shuffle node");
3371 case X86ISD::PALIGNR:
3373 case X86ISD::VPERM2X128:
3374 return DAG.getNode(Opc, dl, VT, V1, V2,
3375 DAG.getConstant(TargetMask, MVT::i8));
3379 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3380 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3382 default: llvm_unreachable("Unknown x86 shuffle node");
3383 case X86ISD::MOVLHPS:
3384 case X86ISD::MOVLHPD:
3385 case X86ISD::MOVHLPS:
3386 case X86ISD::MOVLPS:
3387 case X86ISD::MOVLPD:
3390 case X86ISD::UNPCKL:
3391 case X86ISD::UNPCKH:
3392 return DAG.getNode(Opc, dl, VT, V1, V2);
3396 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3397 MachineFunction &MF = DAG.getMachineFunction();
3398 const X86RegisterInfo *RegInfo =
3399 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3400 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3401 int ReturnAddrIndex = FuncInfo->getRAIndex();
3403 if (ReturnAddrIndex == 0) {
3404 // Set up a frame object for the return address.
3405 unsigned SlotSize = RegInfo->getSlotSize();
3406 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3409 FuncInfo->setRAIndex(ReturnAddrIndex);
3412 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3415 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3416 bool hasSymbolicDisplacement) {
3417 // Offset should fit into 32 bit immediate field.
3418 if (!isInt<32>(Offset))
3421 // If we don't have a symbolic displacement - we don't have any extra
3423 if (!hasSymbolicDisplacement)
3426 // FIXME: Some tweaks might be needed for medium code model.
3427 if (M != CodeModel::Small && M != CodeModel::Kernel)
3430 // For small code model we assume that latest object is 16MB before end of 31
3431 // bits boundary. We may also accept pretty large negative constants knowing
3432 // that all objects are in the positive half of address space.
3433 if (M == CodeModel::Small && Offset < 16*1024*1024)
3436 // For kernel code model we know that all object resist in the negative half
3437 // of 32bits address space. We may not accept negative offsets, since they may
3438 // be just off and we may accept pretty large positive ones.
3439 if (M == CodeModel::Kernel && Offset > 0)
3445 /// isCalleePop - Determines whether the callee is required to pop its
3446 /// own arguments. Callee pop is necessary to support tail calls.
3447 bool X86::isCalleePop(CallingConv::ID CallingConv,
3448 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3452 switch (CallingConv) {
3455 case CallingConv::X86_StdCall:
3457 case CallingConv::X86_FastCall:
3459 case CallingConv::X86_ThisCall:
3461 case CallingConv::Fast:
3463 case CallingConv::GHC:
3465 case CallingConv::HiPE:
3470 /// \brief Return true if the condition is an unsigned comparison operation.
3471 static bool isX86CCUnsigned(unsigned X86CC) {
3473 default: llvm_unreachable("Invalid integer condition!");
3474 case X86::COND_E: return true;
3475 case X86::COND_G: return false;
3476 case X86::COND_GE: return false;
3477 case X86::COND_L: return false;
3478 case X86::COND_LE: return false;
3479 case X86::COND_NE: return true;
3480 case X86::COND_B: return true;
3481 case X86::COND_A: return true;
3482 case X86::COND_BE: return true;
3483 case X86::COND_AE: return true;
3485 llvm_unreachable("covered switch fell through?!");
3488 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3489 /// specific condition code, returning the condition code and the LHS/RHS of the
3490 /// comparison to make.
3491 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3492 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3494 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3495 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3496 // X > -1 -> X == 0, jump !sign.
3497 RHS = DAG.getConstant(0, RHS.getValueType());
3498 return X86::COND_NS;
3500 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3501 // X < 0 -> X == 0, jump on sign.
3504 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3506 RHS = DAG.getConstant(0, RHS.getValueType());
3507 return X86::COND_LE;
3511 switch (SetCCOpcode) {
3512 default: llvm_unreachable("Invalid integer condition!");
3513 case ISD::SETEQ: return X86::COND_E;
3514 case ISD::SETGT: return X86::COND_G;
3515 case ISD::SETGE: return X86::COND_GE;
3516 case ISD::SETLT: return X86::COND_L;
3517 case ISD::SETLE: return X86::COND_LE;
3518 case ISD::SETNE: return X86::COND_NE;
3519 case ISD::SETULT: return X86::COND_B;
3520 case ISD::SETUGT: return X86::COND_A;
3521 case ISD::SETULE: return X86::COND_BE;
3522 case ISD::SETUGE: return X86::COND_AE;
3526 // First determine if it is required or is profitable to flip the operands.
3528 // If LHS is a foldable load, but RHS is not, flip the condition.
3529 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3530 !ISD::isNON_EXTLoad(RHS.getNode())) {
3531 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3532 std::swap(LHS, RHS);
3535 switch (SetCCOpcode) {
3541 std::swap(LHS, RHS);
3545 // On a floating point condition, the flags are set as follows:
3547 // 0 | 0 | 0 | X > Y
3548 // 0 | 0 | 1 | X < Y
3549 // 1 | 0 | 0 | X == Y
3550 // 1 | 1 | 1 | unordered
3551 switch (SetCCOpcode) {
3552 default: llvm_unreachable("Condcode should be pre-legalized away");
3554 case ISD::SETEQ: return X86::COND_E;
3555 case ISD::SETOLT: // flipped
3557 case ISD::SETGT: return X86::COND_A;
3558 case ISD::SETOLE: // flipped
3560 case ISD::SETGE: return X86::COND_AE;
3561 case ISD::SETUGT: // flipped
3563 case ISD::SETLT: return X86::COND_B;
3564 case ISD::SETUGE: // flipped
3566 case ISD::SETLE: return X86::COND_BE;
3568 case ISD::SETNE: return X86::COND_NE;
3569 case ISD::SETUO: return X86::COND_P;
3570 case ISD::SETO: return X86::COND_NP;
3572 case ISD::SETUNE: return X86::COND_INVALID;
3576 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3577 /// code. Current x86 isa includes the following FP cmov instructions:
3578 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3579 static bool hasFPCMov(unsigned X86CC) {
3595 /// isFPImmLegal - Returns true if the target can instruction select the
3596 /// specified FP immediate natively. If false, the legalizer will
3597 /// materialize the FP immediate as a load from a constant pool.
3598 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3599 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3600 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3606 /// \brief Returns true if it is beneficial to convert a load of a constant
3607 /// to just the constant itself.
3608 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3610 assert(Ty->isIntegerTy());
3612 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3613 if (BitSize == 0 || BitSize > 64)
3618 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3619 /// the specified range (L, H].
3620 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3621 return (Val < 0) || (Val >= Low && Val < Hi);
3624 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3625 /// specified value.
3626 static bool isUndefOrEqual(int Val, int CmpVal) {
3627 return (Val < 0 || Val == CmpVal);
3630 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3631 /// from position Pos and ending in Pos+Size, falls within the specified
3632 /// sequential range (L, L+Pos]. or is undef.
3633 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3634 unsigned Pos, unsigned Size, int Low) {
3635 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3636 if (!isUndefOrEqual(Mask[i], Low))
3641 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3642 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3643 /// the second operand.
3644 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3645 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3646 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3647 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3648 return (Mask[0] < 2 && Mask[1] < 2);
3652 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3653 /// is suitable for input to PSHUFHW.
3654 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3655 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3658 // Lower quadword copied in order or undef.
3659 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3662 // Upper quadword shuffled.
3663 for (unsigned i = 4; i != 8; ++i)
3664 if (!isUndefOrInRange(Mask[i], 4, 8))
3667 if (VT == MVT::v16i16) {
3668 // Lower quadword copied in order or undef.
3669 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3672 // Upper quadword shuffled.
3673 for (unsigned i = 12; i != 16; ++i)
3674 if (!isUndefOrInRange(Mask[i], 12, 16))
3681 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3682 /// is suitable for input to PSHUFLW.
3683 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3684 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3687 // Upper quadword copied in order.
3688 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3691 // Lower quadword shuffled.
3692 for (unsigned i = 0; i != 4; ++i)
3693 if (!isUndefOrInRange(Mask[i], 0, 4))
3696 if (VT == MVT::v16i16) {
3697 // Upper quadword copied in order.
3698 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3701 // Lower quadword shuffled.
3702 for (unsigned i = 8; i != 12; ++i)
3703 if (!isUndefOrInRange(Mask[i], 8, 12))
3710 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3711 /// is suitable for input to PALIGNR.
3712 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3713 const X86Subtarget *Subtarget) {
3714 if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3715 (VT.is256BitVector() && !Subtarget->hasInt256()))
3718 unsigned NumElts = VT.getVectorNumElements();
3719 unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3720 unsigned NumLaneElts = NumElts/NumLanes;
3722 // Do not handle 64-bit element shuffles with palignr.
3723 if (NumLaneElts == 2)
3726 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3728 for (i = 0; i != NumLaneElts; ++i) {
3733 // Lane is all undef, go to next lane
3734 if (i == NumLaneElts)
3737 int Start = Mask[i+l];
3739 // Make sure its in this lane in one of the sources
3740 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3741 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3744 // If not lane 0, then we must match lane 0
3745 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3748 // Correct second source to be contiguous with first source
3749 if (Start >= (int)NumElts)
3750 Start -= NumElts - NumLaneElts;
3752 // Make sure we're shifting in the right direction.
3753 if (Start <= (int)(i+l))
3758 // Check the rest of the elements to see if they are consecutive.
3759 for (++i; i != NumLaneElts; ++i) {
3760 int Idx = Mask[i+l];
3762 // Make sure its in this lane
3763 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3764 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3767 // If not lane 0, then we must match lane 0
3768 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3771 if (Idx >= (int)NumElts)
3772 Idx -= NumElts - NumLaneElts;
3774 if (!isUndefOrEqual(Idx, Start+i))
3783 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3784 /// the two vector operands have swapped position.
3785 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3786 unsigned NumElems) {
3787 for (unsigned i = 0; i != NumElems; ++i) {
3791 else if (idx < (int)NumElems)
3792 Mask[i] = idx + NumElems;
3794 Mask[i] = idx - NumElems;
3798 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3799 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3800 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3801 /// reverse of what x86 shuffles want.
3802 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3804 unsigned NumElems = VT.getVectorNumElements();
3805 unsigned NumLanes = VT.getSizeInBits()/128;
3806 unsigned NumLaneElems = NumElems/NumLanes;
3808 if (NumLaneElems != 2 && NumLaneElems != 4)
3811 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3812 bool symetricMaskRequired =
3813 (VT.getSizeInBits() >= 256) && (EltSize == 32);
3815 // VSHUFPSY divides the resulting vector into 4 chunks.
3816 // The sources are also splitted into 4 chunks, and each destination
3817 // chunk must come from a different source chunk.
3819 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3820 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3822 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3823 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3825 // VSHUFPDY divides the resulting vector into 4 chunks.
3826 // The sources are also splitted into 4 chunks, and each destination
3827 // chunk must come from a different source chunk.
3829 // SRC1 => X3 X2 X1 X0
3830 // SRC2 => Y3 Y2 Y1 Y0
3832 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3834 SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3835 unsigned HalfLaneElems = NumLaneElems/2;
3836 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3837 for (unsigned i = 0; i != NumLaneElems; ++i) {
3838 int Idx = Mask[i+l];
3839 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3840 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3842 // For VSHUFPSY, the mask of the second half must be the same as the
3843 // first but with the appropriate offsets. This works in the same way as
3844 // VPERMILPS works with masks.
3845 if (!symetricMaskRequired || Idx < 0)
3847 if (MaskVal[i] < 0) {
3848 MaskVal[i] = Idx - l;
3851 if ((signed)(Idx - l) != MaskVal[i])
3859 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3860 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3861 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3862 if (!VT.is128BitVector())
3865 unsigned NumElems = VT.getVectorNumElements();
3870 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3871 return isUndefOrEqual(Mask[0], 6) &&
3872 isUndefOrEqual(Mask[1], 7) &&
3873 isUndefOrEqual(Mask[2], 2) &&
3874 isUndefOrEqual(Mask[3], 3);
3877 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3878 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3880 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3881 if (!VT.is128BitVector())
3884 unsigned NumElems = VT.getVectorNumElements();
3889 return isUndefOrEqual(Mask[0], 2) &&
3890 isUndefOrEqual(Mask[1], 3) &&
3891 isUndefOrEqual(Mask[2], 2) &&
3892 isUndefOrEqual(Mask[3], 3);
3895 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3896 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3897 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3898 if (!VT.is128BitVector())
3901 unsigned NumElems = VT.getVectorNumElements();
3903 if (NumElems != 2 && NumElems != 4)
3906 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3907 if (!isUndefOrEqual(Mask[i], i + NumElems))
3910 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3911 if (!isUndefOrEqual(Mask[i], i))
3917 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3918 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3919 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3920 if (!VT.is128BitVector())
3923 unsigned NumElems = VT.getVectorNumElements();
3925 if (NumElems != 2 && NumElems != 4)
3928 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3929 if (!isUndefOrEqual(Mask[i], i))
3932 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3933 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3939 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
3940 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
3941 /// i. e: If all but one element come from the same vector.
3942 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
3943 // TODO: Deal with AVX's VINSERTPS
3944 if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
3947 unsigned CorrectPosV1 = 0;
3948 unsigned CorrectPosV2 = 0;
3949 for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i)
3952 else if (Mask[i] == i + 4)
3955 if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
3956 // We have 3 elements from one vector, and one from another.
3963 // Some special combinations that can be optimized.
3966 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3967 SelectionDAG &DAG) {
3968 MVT VT = SVOp->getSimpleValueType(0);
3971 if (VT != MVT::v8i32 && VT != MVT::v8f32)
3974 ArrayRef<int> Mask = SVOp->getMask();
3976 // These are the special masks that may be optimized.
3977 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3978 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
3979 bool MatchEvenMask = true;
3980 bool MatchOddMask = true;
3981 for (int i=0; i<8; ++i) {
3982 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3983 MatchEvenMask = false;
3984 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3985 MatchOddMask = false;
3988 if (!MatchEvenMask && !MatchOddMask)
3991 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3993 SDValue Op0 = SVOp->getOperand(0);
3994 SDValue Op1 = SVOp->getOperand(1);
3996 if (MatchEvenMask) {
3997 // Shift the second operand right to 32 bits.
3998 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3999 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4001 // Shift the first operand left to 32 bits.
4002 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4003 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4005 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4006 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4009 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4010 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4011 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4012 bool HasInt256, bool V2IsSplat = false) {
4014 assert(VT.getSizeInBits() >= 128 &&
4015 "Unsupported vector type for unpckl");
4017 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4019 unsigned NumOf256BitLanes;
4020 unsigned NumElts = VT.getVectorNumElements();
4021 if (VT.is256BitVector()) {
4022 if (NumElts != 4 && NumElts != 8 &&
4023 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4026 NumOf256BitLanes = 1;
4027 } else if (VT.is512BitVector()) {
4028 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4029 "Unsupported vector type for unpckh");
4031 NumOf256BitLanes = 2;
4034 NumOf256BitLanes = 1;
4037 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4038 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4040 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4041 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4042 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4043 int BitI = Mask[l256*NumEltsInStride+l+i];
4044 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4045 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4047 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4049 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4057 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4058 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4059 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4060 bool HasInt256, bool V2IsSplat = false) {
4061 assert(VT.getSizeInBits() >= 128 &&
4062 "Unsupported vector type for unpckh");
4064 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4066 unsigned NumOf256BitLanes;
4067 unsigned NumElts = VT.getVectorNumElements();
4068 if (VT.is256BitVector()) {
4069 if (NumElts != 4 && NumElts != 8 &&
4070 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4073 NumOf256BitLanes = 1;
4074 } else if (VT.is512BitVector()) {
4075 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4076 "Unsupported vector type for unpckh");
4078 NumOf256BitLanes = 2;
4081 NumOf256BitLanes = 1;
4084 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4085 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4087 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4088 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4089 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4090 int BitI = Mask[l256*NumEltsInStride+l+i];
4091 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4092 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4094 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4096 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4104 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4105 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4107 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4108 unsigned NumElts = VT.getVectorNumElements();
4109 bool Is256BitVec = VT.is256BitVector();
4111 if (VT.is512BitVector())
4113 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4114 "Unsupported vector type for unpckh");
4116 if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4117 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4120 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4121 // FIXME: Need a better way to get rid of this, there's no latency difference
4122 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4123 // the former later. We should also remove the "_undef" special mask.
4124 if (NumElts == 4 && Is256BitVec)
4127 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4128 // independently on 128-bit lanes.
4129 unsigned NumLanes = VT.getSizeInBits()/128;
4130 unsigned NumLaneElts = NumElts/NumLanes;
4132 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4133 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4134 int BitI = Mask[l+i];
4135 int BitI1 = Mask[l+i+1];
4137 if (!isUndefOrEqual(BitI, j))
4139 if (!isUndefOrEqual(BitI1, j))
4147 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4148 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4150 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4151 unsigned NumElts = VT.getVectorNumElements();
4153 if (VT.is512BitVector())
4156 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4157 "Unsupported vector type for unpckh");
4159 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4160 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4163 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4164 // independently on 128-bit lanes.
4165 unsigned NumLanes = VT.getSizeInBits()/128;
4166 unsigned NumLaneElts = NumElts/NumLanes;
4168 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4169 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4170 int BitI = Mask[l+i];
4171 int BitI1 = Mask[l+i+1];
4172 if (!isUndefOrEqual(BitI, j))
4174 if (!isUndefOrEqual(BitI1, j))
4181 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4182 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4183 /// MOVSD, and MOVD, i.e. setting the lowest element.
4184 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4185 if (VT.getVectorElementType().getSizeInBits() < 32)
4187 if (!VT.is128BitVector())
4190 unsigned NumElts = VT.getVectorNumElements();
4192 if (!isUndefOrEqual(Mask[0], NumElts))
4195 for (unsigned i = 1; i != NumElts; ++i)
4196 if (!isUndefOrEqual(Mask[i], i))
4202 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4203 /// as permutations between 128-bit chunks or halves. As an example: this
4205 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4206 /// The first half comes from the second half of V1 and the second half from the
4207 /// the second half of V2.
4208 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4209 if (!HasFp256 || !VT.is256BitVector())
4212 // The shuffle result is divided into half A and half B. In total the two
4213 // sources have 4 halves, namely: C, D, E, F. The final values of A and
4214 // B must come from C, D, E or F.
4215 unsigned HalfSize = VT.getVectorNumElements()/2;
4216 bool MatchA = false, MatchB = false;
4218 // Check if A comes from one of C, D, E, F.
4219 for (unsigned Half = 0; Half != 4; ++Half) {
4220 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4226 // Check if B comes from one of C, D, E, F.
4227 for (unsigned Half = 0; Half != 4; ++Half) {
4228 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4234 return MatchA && MatchB;
4237 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4238 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4239 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4240 MVT VT = SVOp->getSimpleValueType(0);
4242 unsigned HalfSize = VT.getVectorNumElements()/2;
4244 unsigned FstHalf = 0, SndHalf = 0;
4245 for (unsigned i = 0; i < HalfSize; ++i) {
4246 if (SVOp->getMaskElt(i) > 0) {
4247 FstHalf = SVOp->getMaskElt(i)/HalfSize;
4251 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4252 if (SVOp->getMaskElt(i) > 0) {
4253 SndHalf = SVOp->getMaskElt(i)/HalfSize;
4258 return (FstHalf | (SndHalf << 4));
4261 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4262 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4263 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4267 unsigned NumElts = VT.getVectorNumElements();
4269 if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4270 for (unsigned i = 0; i != NumElts; ++i) {
4273 Imm8 |= Mask[i] << (i*2);
4278 unsigned LaneSize = 4;
4279 SmallVector<int, 4> MaskVal(LaneSize, -1);
4281 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4282 for (unsigned i = 0; i != LaneSize; ++i) {
4283 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4287 if (MaskVal[i] < 0) {
4288 MaskVal[i] = Mask[i+l] - l;
4289 Imm8 |= MaskVal[i] << (i*2);
4292 if (Mask[i+l] != (signed)(MaskVal[i]+l))
4299 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4300 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4301 /// Note that VPERMIL mask matching is different depending whether theunderlying
4302 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4303 /// to the same elements of the low, but to the higher half of the source.
4304 /// In VPERMILPD the two lanes could be shuffled independently of each other
4305 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4306 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4307 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4308 if (VT.getSizeInBits() < 256 || EltSize < 32)
4310 bool symetricMaskRequired = (EltSize == 32);
4311 unsigned NumElts = VT.getVectorNumElements();
4313 unsigned NumLanes = VT.getSizeInBits()/128;
4314 unsigned LaneSize = NumElts/NumLanes;
4315 // 2 or 4 elements in one lane
4317 SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4318 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4319 for (unsigned i = 0; i != LaneSize; ++i) {
4320 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4322 if (symetricMaskRequired) {
4323 if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4324 ExpectedMaskVal[i] = Mask[i+l] - l;
4327 if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4335 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4336 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
4337 /// element of vector 2 and the other elements to come from vector 1 in order.
4338 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4339 bool V2IsSplat = false, bool V2IsUndef = false) {
4340 if (!VT.is128BitVector())
4343 unsigned NumOps = VT.getVectorNumElements();
4344 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4347 if (!isUndefOrEqual(Mask[0], 0))
4350 for (unsigned i = 1; i != NumOps; ++i)
4351 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4352 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4353 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4359 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4360 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4361 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4362 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4363 const X86Subtarget *Subtarget) {
4364 if (!Subtarget->hasSSE3())
4367 unsigned NumElems = VT.getVectorNumElements();
4369 if ((VT.is128BitVector() && NumElems != 4) ||
4370 (VT.is256BitVector() && NumElems != 8) ||
4371 (VT.is512BitVector() && NumElems != 16))
4374 // "i+1" is the value the indexed mask element must have
4375 for (unsigned i = 0; i != NumElems; i += 2)
4376 if (!isUndefOrEqual(Mask[i], i+1) ||
4377 !isUndefOrEqual(Mask[i+1], i+1))
4383 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4384 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4385 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4386 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4387 const X86Subtarget *Subtarget) {
4388 if (!Subtarget->hasSSE3())
4391 unsigned NumElems = VT.getVectorNumElements();
4393 if ((VT.is128BitVector() && NumElems != 4) ||
4394 (VT.is256BitVector() && NumElems != 8) ||
4395 (VT.is512BitVector() && NumElems != 16))
4398 // "i" is the value the indexed mask element must have
4399 for (unsigned i = 0; i != NumElems; i += 2)
4400 if (!isUndefOrEqual(Mask[i], i) ||
4401 !isUndefOrEqual(Mask[i+1], i))
4407 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4408 /// specifies a shuffle of elements that is suitable for input to 256-bit
4409 /// version of MOVDDUP.
4410 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4411 if (!HasFp256 || !VT.is256BitVector())
4414 unsigned NumElts = VT.getVectorNumElements();
4418 for (unsigned i = 0; i != NumElts/2; ++i)
4419 if (!isUndefOrEqual(Mask[i], 0))
4421 for (unsigned i = NumElts/2; i != NumElts; ++i)
4422 if (!isUndefOrEqual(Mask[i], NumElts/2))
4427 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4428 /// specifies a shuffle of elements that is suitable for input to 128-bit
4429 /// version of MOVDDUP.
4430 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4431 if (!VT.is128BitVector())
4434 unsigned e = VT.getVectorNumElements() / 2;
4435 for (unsigned i = 0; i != e; ++i)
4436 if (!isUndefOrEqual(Mask[i], i))
4438 for (unsigned i = 0; i != e; ++i)
4439 if (!isUndefOrEqual(Mask[e+i], i))
4444 /// isVEXTRACTIndex - Return true if the specified
4445 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4446 /// suitable for instruction that extract 128 or 256 bit vectors
4447 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4448 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4449 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4452 // The index should be aligned on a vecWidth-bit boundary.
4454 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4456 MVT VT = N->getSimpleValueType(0);
4457 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4458 bool Result = (Index * ElSize) % vecWidth == 0;
4463 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4464 /// operand specifies a subvector insert that is suitable for input to
4465 /// insertion of 128 or 256-bit subvectors
4466 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4467 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4468 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4470 // The index should be aligned on a vecWidth-bit boundary.
4472 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4474 MVT VT = N->getSimpleValueType(0);
4475 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4476 bool Result = (Index * ElSize) % vecWidth == 0;
4481 bool X86::isVINSERT128Index(SDNode *N) {
4482 return isVINSERTIndex(N, 128);
4485 bool X86::isVINSERT256Index(SDNode *N) {
4486 return isVINSERTIndex(N, 256);
4489 bool X86::isVEXTRACT128Index(SDNode *N) {
4490 return isVEXTRACTIndex(N, 128);
4493 bool X86::isVEXTRACT256Index(SDNode *N) {
4494 return isVEXTRACTIndex(N, 256);
4497 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4498 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4499 /// Handles 128-bit and 256-bit.
4500 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4501 MVT VT = N->getSimpleValueType(0);
4503 assert((VT.getSizeInBits() >= 128) &&
4504 "Unsupported vector type for PSHUF/SHUFP");
4506 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4507 // independently on 128-bit lanes.
4508 unsigned NumElts = VT.getVectorNumElements();
4509 unsigned NumLanes = VT.getSizeInBits()/128;
4510 unsigned NumLaneElts = NumElts/NumLanes;
4512 assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4513 "Only supports 2, 4 or 8 elements per lane");
4515 unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4517 for (unsigned i = 0; i != NumElts; ++i) {
4518 int Elt = N->getMaskElt(i);
4519 if (Elt < 0) continue;
4520 Elt &= NumLaneElts - 1;
4521 unsigned ShAmt = (i << Shift) % 8;
4522 Mask |= Elt << ShAmt;
4528 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4529 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4530 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4531 MVT VT = N->getSimpleValueType(0);
4533 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4534 "Unsupported vector type for PSHUFHW");
4536 unsigned NumElts = VT.getVectorNumElements();
4539 for (unsigned l = 0; l != NumElts; l += 8) {
4540 // 8 nodes per lane, but we only care about the last 4.
4541 for (unsigned i = 0; i < 4; ++i) {
4542 int Elt = N->getMaskElt(l+i+4);
4543 if (Elt < 0) continue;
4544 Elt &= 0x3; // only 2-bits.
4545 Mask |= Elt << (i * 2);
4552 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4553 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4554 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4555 MVT VT = N->getSimpleValueType(0);
4557 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4558 "Unsupported vector type for PSHUFHW");
4560 unsigned NumElts = VT.getVectorNumElements();
4563 for (unsigned l = 0; l != NumElts; l += 8) {
4564 // 8 nodes per lane, but we only care about the first 4.
4565 for (unsigned i = 0; i < 4; ++i) {
4566 int Elt = N->getMaskElt(l+i);
4567 if (Elt < 0) continue;
4568 Elt &= 0x3; // only 2-bits
4569 Mask |= Elt << (i * 2);
4576 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4577 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4578 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4579 MVT VT = SVOp->getSimpleValueType(0);
4580 unsigned EltSize = VT.is512BitVector() ? 1 :
4581 VT.getVectorElementType().getSizeInBits() >> 3;
4583 unsigned NumElts = VT.getVectorNumElements();
4584 unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4585 unsigned NumLaneElts = NumElts/NumLanes;
4589 for (i = 0; i != NumElts; ++i) {
4590 Val = SVOp->getMaskElt(i);
4594 if (Val >= (int)NumElts)
4595 Val -= NumElts - NumLaneElts;
4597 assert(Val - i > 0 && "PALIGNR imm should be positive");
4598 return (Val - i) * EltSize;
4601 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4602 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4603 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4604 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4607 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4609 MVT VecVT = N->getOperand(0).getSimpleValueType();
4610 MVT ElVT = VecVT.getVectorElementType();
4612 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4613 return Index / NumElemsPerChunk;
4616 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4617 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4618 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4619 llvm_unreachable("Illegal insert subvector for VINSERT");
4622 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4624 MVT VecVT = N->getSimpleValueType(0);
4625 MVT ElVT = VecVT.getVectorElementType();
4627 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4628 return Index / NumElemsPerChunk;
4631 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4632 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4633 /// and VINSERTI128 instructions.
4634 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4635 return getExtractVEXTRACTImmediate(N, 128);
4638 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4639 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4640 /// and VINSERTI64x4 instructions.
4641 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4642 return getExtractVEXTRACTImmediate(N, 256);
4645 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4646 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4647 /// and VINSERTI128 instructions.
4648 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4649 return getInsertVINSERTImmediate(N, 128);
4652 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4653 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4654 /// and VINSERTI64x4 instructions.
4655 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4656 return getInsertVINSERTImmediate(N, 256);
4659 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4661 bool X86::isZeroNode(SDValue Elt) {
4662 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4663 return CN->isNullValue();
4664 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4665 return CFP->getValueAPF().isPosZero();
4669 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4670 /// their permute mask.
4671 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4672 SelectionDAG &DAG) {
4673 MVT VT = SVOp->getSimpleValueType(0);
4674 unsigned NumElems = VT.getVectorNumElements();
4675 SmallVector<int, 8> MaskVec;
4677 for (unsigned i = 0; i != NumElems; ++i) {
4678 int Idx = SVOp->getMaskElt(i);
4680 if (Idx < (int)NumElems)
4685 MaskVec.push_back(Idx);
4687 return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4688 SVOp->getOperand(0), &MaskVec[0]);
4691 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4692 /// match movhlps. The lower half elements should come from upper half of
4693 /// V1 (and in order), and the upper half elements should come from the upper
4694 /// half of V2 (and in order).
4695 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4696 if (!VT.is128BitVector())
4698 if (VT.getVectorNumElements() != 4)
4700 for (unsigned i = 0, e = 2; i != e; ++i)
4701 if (!isUndefOrEqual(Mask[i], i+2))
4703 for (unsigned i = 2; i != 4; ++i)
4704 if (!isUndefOrEqual(Mask[i], i+4))
4709 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4710 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4712 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4713 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4715 N = N->getOperand(0).getNode();
4716 if (!ISD::isNON_EXTLoad(N))
4719 *LD = cast<LoadSDNode>(N);
4723 // Test whether the given value is a vector value which will be legalized
4725 static bool WillBeConstantPoolLoad(SDNode *N) {
4726 if (N->getOpcode() != ISD::BUILD_VECTOR)
4729 // Check for any non-constant elements.
4730 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4731 switch (N->getOperand(i).getNode()->getOpcode()) {
4733 case ISD::ConstantFP:
4740 // Vectors of all-zeros and all-ones are materialized with special
4741 // instructions rather than being loaded.
4742 return !ISD::isBuildVectorAllZeros(N) &&
4743 !ISD::isBuildVectorAllOnes(N);
4746 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4747 /// match movlp{s|d}. The lower half elements should come from lower half of
4748 /// V1 (and in order), and the upper half elements should come from the upper
4749 /// half of V2 (and in order). And since V1 will become the source of the
4750 /// MOVLP, it must be either a vector load or a scalar load to vector.
4751 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4752 ArrayRef<int> Mask, MVT VT) {
4753 if (!VT.is128BitVector())
4756 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4758 // Is V2 is a vector load, don't do this transformation. We will try to use
4759 // load folding shufps op.
4760 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4763 unsigned NumElems = VT.getVectorNumElements();
4765 if (NumElems != 2 && NumElems != 4)
4767 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4768 if (!isUndefOrEqual(Mask[i], i))
4770 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4771 if (!isUndefOrEqual(Mask[i], i+NumElems))
4776 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4778 static bool isSplatVector(SDNode *N) {
4779 if (N->getOpcode() != ISD::BUILD_VECTOR)
4782 SDValue SplatValue = N->getOperand(0);
4783 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4784 if (N->getOperand(i) != SplatValue)
4789 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4790 /// to an zero vector.
4791 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4792 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4793 SDValue V1 = N->getOperand(0);
4794 SDValue V2 = N->getOperand(1);
4795 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4796 for (unsigned i = 0; i != NumElems; ++i) {
4797 int Idx = N->getMaskElt(i);
4798 if (Idx >= (int)NumElems) {
4799 unsigned Opc = V2.getOpcode();
4800 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4802 if (Opc != ISD::BUILD_VECTOR ||
4803 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4805 } else if (Idx >= 0) {
4806 unsigned Opc = V1.getOpcode();
4807 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4809 if (Opc != ISD::BUILD_VECTOR ||
4810 !X86::isZeroNode(V1.getOperand(Idx)))
4817 /// getZeroVector - Returns a vector of specified type with all zero elements.
4819 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4820 SelectionDAG &DAG, SDLoc dl) {
4821 assert(VT.isVector() && "Expected a vector type");
4823 // Always build SSE zero vectors as <4 x i32> bitcasted
4824 // to their dest type. This ensures they get CSE'd.
4826 if (VT.is128BitVector()) { // SSE
4827 if (Subtarget->hasSSE2()) { // SSE2
4828 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4829 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4831 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4832 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4834 } else if (VT.is256BitVector()) { // AVX
4835 if (Subtarget->hasInt256()) { // AVX2
4836 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4837 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4838 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4839 array_lengthof(Ops));
4841 // 256-bit logic and arithmetic instructions in AVX are all
4842 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4843 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4844 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4845 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops,
4846 array_lengthof(Ops));
4848 } else if (VT.is512BitVector()) { // AVX-512
4849 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4850 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4851 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4852 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops, 16);
4853 } else if (VT.getScalarType() == MVT::i1) {
4854 assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4855 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4856 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4857 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4858 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
4859 Ops, VT.getVectorNumElements());
4861 llvm_unreachable("Unexpected vector type");
4863 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4866 /// getOnesVector - Returns a vector of specified type with all bits set.
4867 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4868 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4869 /// Then bitcast to their original type, ensuring they get CSE'd.
4870 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4872 assert(VT.isVector() && "Expected a vector type");
4874 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4876 if (VT.is256BitVector()) {
4877 if (HasInt256) { // AVX2
4878 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4879 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4880 array_lengthof(Ops));
4882 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4883 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4885 } else if (VT.is128BitVector()) {
4886 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4888 llvm_unreachable("Unexpected vector type");
4890 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4893 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4894 /// that point to V2 points to its first element.
4895 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4896 for (unsigned i = 0; i != NumElems; ++i) {
4897 if (Mask[i] > (int)NumElems) {
4903 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4904 /// operation of specified width.
4905 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4907 unsigned NumElems = VT.getVectorNumElements();
4908 SmallVector<int, 8> Mask;
4909 Mask.push_back(NumElems);
4910 for (unsigned i = 1; i != NumElems; ++i)
4912 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4915 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4916 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4918 unsigned NumElems = VT.getVectorNumElements();
4919 SmallVector<int, 8> Mask;
4920 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4922 Mask.push_back(i + NumElems);
4924 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4927 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4928 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4930 unsigned NumElems = VT.getVectorNumElements();
4931 SmallVector<int, 8> Mask;
4932 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4933 Mask.push_back(i + Half);
4934 Mask.push_back(i + NumElems + Half);
4936 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4939 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4940 // a generic shuffle instruction because the target has no such instructions.
4941 // Generate shuffles which repeat i16 and i8 several times until they can be
4942 // represented by v4f32 and then be manipulated by target suported shuffles.
4943 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4944 MVT VT = V.getSimpleValueType();
4945 int NumElems = VT.getVectorNumElements();
4948 while (NumElems > 4) {
4949 if (EltNo < NumElems/2) {
4950 V = getUnpackl(DAG, dl, VT, V, V);
4952 V = getUnpackh(DAG, dl, VT, V, V);
4953 EltNo -= NumElems/2;
4960 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4961 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4962 MVT VT = V.getSimpleValueType();
4965 if (VT.is128BitVector()) {
4966 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4967 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4968 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4970 } else if (VT.is256BitVector()) {
4971 // To use VPERMILPS to splat scalars, the second half of indicies must
4972 // refer to the higher part, which is a duplication of the lower one,
4973 // because VPERMILPS can only handle in-lane permutations.
4974 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4975 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4977 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4978 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4981 llvm_unreachable("Vector size not supported");
4983 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4986 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4987 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4988 MVT SrcVT = SV->getSimpleValueType(0);
4989 SDValue V1 = SV->getOperand(0);
4992 int EltNo = SV->getSplatIndex();
4993 int NumElems = SrcVT.getVectorNumElements();
4994 bool Is256BitVec = SrcVT.is256BitVector();
4996 assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4997 "Unknown how to promote splat for type");
4999 // Extract the 128-bit part containing the splat element and update
5000 // the splat element index when it refers to the higher register.
5002 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5003 if (EltNo >= NumElems/2)
5004 EltNo -= NumElems/2;
5007 // All i16 and i8 vector types can't be used directly by a generic shuffle
5008 // instruction because the target has no such instruction. Generate shuffles
5009 // which repeat i16 and i8 several times until they fit in i32, and then can
5010 // be manipulated by target suported shuffles.
5011 MVT EltVT = SrcVT.getVectorElementType();
5012 if (EltVT == MVT::i8 || EltVT == MVT::i16)
5013 V1 = PromoteSplati8i16(V1, DAG, EltNo);
5015 // Recreate the 256-bit vector and place the same 128-bit vector
5016 // into the low and high part. This is necessary because we want
5017 // to use VPERM* to shuffle the vectors
5019 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5022 return getLegalSplat(DAG, V1, EltNo);
5025 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5026 /// vector of zero or undef vector. This produces a shuffle where the low
5027 /// element of V2 is swizzled into the zero/undef vector, landing at element
5028 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
5029 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5031 const X86Subtarget *Subtarget,
5032 SelectionDAG &DAG) {
5033 MVT VT = V2.getSimpleValueType();
5035 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5036 unsigned NumElems = VT.getVectorNumElements();
5037 SmallVector<int, 16> MaskVec;
5038 for (unsigned i = 0; i != NumElems; ++i)
5039 // If this is the insertion idx, put the low elt of V2 here.
5040 MaskVec.push_back(i == Idx ? NumElems : i);
5041 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5044 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5045 /// target specific opcode. Returns true if the Mask could be calculated.
5046 /// Sets IsUnary to true if only uses one source.
5047 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5048 SmallVectorImpl<int> &Mask, bool &IsUnary) {
5049 unsigned NumElems = VT.getVectorNumElements();
5053 switch(N->getOpcode()) {
5055 ImmN = N->getOperand(N->getNumOperands()-1);
5056 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5058 case X86ISD::UNPCKH:
5059 DecodeUNPCKHMask(VT, Mask);
5061 case X86ISD::UNPCKL:
5062 DecodeUNPCKLMask(VT, Mask);
5064 case X86ISD::MOVHLPS:
5065 DecodeMOVHLPSMask(NumElems, Mask);
5067 case X86ISD::MOVLHPS:
5068 DecodeMOVLHPSMask(NumElems, Mask);
5070 case X86ISD::PALIGNR:
5071 ImmN = N->getOperand(N->getNumOperands()-1);
5072 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5074 case X86ISD::PSHUFD:
5075 case X86ISD::VPERMILP:
5076 ImmN = N->getOperand(N->getNumOperands()-1);
5077 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5080 case X86ISD::PSHUFHW:
5081 ImmN = N->getOperand(N->getNumOperands()-1);
5082 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5085 case X86ISD::PSHUFLW:
5086 ImmN = N->getOperand(N->getNumOperands()-1);
5087 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5090 case X86ISD::VPERMI:
5091 ImmN = N->getOperand(N->getNumOperands()-1);
5092 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5096 case X86ISD::MOVSD: {
5097 // The index 0 always comes from the first element of the second source,
5098 // this is why MOVSS and MOVSD are used in the first place. The other
5099 // elements come from the other positions of the first source vector
5100 Mask.push_back(NumElems);
5101 for (unsigned i = 1; i != NumElems; ++i) {
5106 case X86ISD::VPERM2X128:
5107 ImmN = N->getOperand(N->getNumOperands()-1);
5108 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5109 if (Mask.empty()) return false;
5111 case X86ISD::MOVDDUP:
5112 case X86ISD::MOVLHPD:
5113 case X86ISD::MOVLPD:
5114 case X86ISD::MOVLPS:
5115 case X86ISD::MOVSHDUP:
5116 case X86ISD::MOVSLDUP:
5117 // Not yet implemented
5119 default: llvm_unreachable("unknown target shuffle node");
5125 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5126 /// element of the result of the vector shuffle.
5127 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5130 return SDValue(); // Limit search depth.
5132 SDValue V = SDValue(N, 0);
5133 EVT VT = V.getValueType();
5134 unsigned Opcode = V.getOpcode();
5136 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5137 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5138 int Elt = SV->getMaskElt(Index);
5141 return DAG.getUNDEF(VT.getVectorElementType());
5143 unsigned NumElems = VT.getVectorNumElements();
5144 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5145 : SV->getOperand(1);
5146 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5149 // Recurse into target specific vector shuffles to find scalars.
5150 if (isTargetShuffle(Opcode)) {
5151 MVT ShufVT = V.getSimpleValueType();
5152 unsigned NumElems = ShufVT.getVectorNumElements();
5153 SmallVector<int, 16> ShuffleMask;
5156 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5159 int Elt = ShuffleMask[Index];
5161 return DAG.getUNDEF(ShufVT.getVectorElementType());
5163 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5165 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5169 // Actual nodes that may contain scalar elements
5170 if (Opcode == ISD::BITCAST) {
5171 V = V.getOperand(0);
5172 EVT SrcVT = V.getValueType();
5173 unsigned NumElems = VT.getVectorNumElements();
5175 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5179 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5180 return (Index == 0) ? V.getOperand(0)
5181 : DAG.getUNDEF(VT.getVectorElementType());
5183 if (V.getOpcode() == ISD::BUILD_VECTOR)
5184 return V.getOperand(Index);
5189 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5190 /// shuffle operation which come from a consecutively from a zero. The
5191 /// search can start in two different directions, from left or right.
5192 /// We count undefs as zeros until PreferredNum is reached.
5193 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5194 unsigned NumElems, bool ZerosFromLeft,
5196 unsigned PreferredNum = -1U) {
5197 unsigned NumZeros = 0;
5198 for (unsigned i = 0; i != NumElems; ++i) {
5199 unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5200 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5204 if (X86::isZeroNode(Elt))
5206 else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5207 NumZeros = std::min(NumZeros + 1, PreferredNum);
5215 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5216 /// correspond consecutively to elements from one of the vector operands,
5217 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5219 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5220 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5221 unsigned NumElems, unsigned &OpNum) {
5222 bool SeenV1 = false;
5223 bool SeenV2 = false;
5225 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5226 int Idx = SVOp->getMaskElt(i);
5227 // Ignore undef indicies
5231 if (Idx < (int)NumElems)
5236 // Only accept consecutive elements from the same vector
5237 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5241 OpNum = SeenV1 ? 0 : 1;
5245 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5246 /// logical left shift of a vector.
5247 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5248 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5250 SVOp->getSimpleValueType(0).getVectorNumElements();
5251 unsigned NumZeros = getNumOfConsecutiveZeros(
5252 SVOp, NumElems, false /* check zeros from right */, DAG,
5253 SVOp->getMaskElt(0));
5259 // Considering the elements in the mask that are not consecutive zeros,
5260 // check if they consecutively come from only one of the source vectors.
5262 // V1 = {X, A, B, C} 0
5264 // vector_shuffle V1, V2 <1, 2, 3, X>
5266 if (!isShuffleMaskConsecutive(SVOp,
5267 0, // Mask Start Index
5268 NumElems-NumZeros, // Mask End Index(exclusive)
5269 NumZeros, // Where to start looking in the src vector
5270 NumElems, // Number of elements in vector
5271 OpSrc)) // Which source operand ?
5276 ShVal = SVOp->getOperand(OpSrc);
5280 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5281 /// logical left shift of a vector.
5282 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5283 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5285 SVOp->getSimpleValueType(0).getVectorNumElements();
5286 unsigned NumZeros = getNumOfConsecutiveZeros(
5287 SVOp, NumElems, true /* check zeros from left */, DAG,
5288 NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5294 // Considering the elements in the mask that are not consecutive zeros,
5295 // check if they consecutively come from only one of the source vectors.
5297 // 0 { A, B, X, X } = V2
5299 // vector_shuffle V1, V2 <X, X, 4, 5>
5301 if (!isShuffleMaskConsecutive(SVOp,
5302 NumZeros, // Mask Start Index
5303 NumElems, // Mask End Index(exclusive)
5304 0, // Where to start looking in the src vector
5305 NumElems, // Number of elements in vector
5306 OpSrc)) // Which source operand ?
5311 ShVal = SVOp->getOperand(OpSrc);
5315 /// isVectorShift - Returns true if the shuffle can be implemented as a
5316 /// logical left or right shift of a vector.
5317 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5318 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5319 // Although the logic below support any bitwidth size, there are no
5320 // shift instructions which handle more than 128-bit vectors.
5321 if (!SVOp->getSimpleValueType(0).is128BitVector())
5324 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5325 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5331 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5333 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5334 unsigned NumNonZero, unsigned NumZero,
5336 const X86Subtarget* Subtarget,
5337 const TargetLowering &TLI) {
5344 for (unsigned i = 0; i < 16; ++i) {
5345 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5346 if (ThisIsNonZero && First) {
5348 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5350 V = DAG.getUNDEF(MVT::v8i16);
5355 SDValue ThisElt, LastElt;
5356 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5357 if (LastIsNonZero) {
5358 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5359 MVT::i16, Op.getOperand(i-1));
5361 if (ThisIsNonZero) {
5362 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5363 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5364 ThisElt, DAG.getConstant(8, MVT::i8));
5366 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5370 if (ThisElt.getNode())
5371 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5372 DAG.getIntPtrConstant(i/2));
5376 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5379 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5381 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5382 unsigned NumNonZero, unsigned NumZero,
5384 const X86Subtarget* Subtarget,
5385 const TargetLowering &TLI) {
5392 for (unsigned i = 0; i < 8; ++i) {
5393 bool isNonZero = (NonZeros & (1 << i)) != 0;
5397 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5399 V = DAG.getUNDEF(MVT::v8i16);
5402 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5403 MVT::v8i16, V, Op.getOperand(i),
5404 DAG.getIntPtrConstant(i));
5411 /// getVShift - Return a vector logical shift node.
5413 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5414 unsigned NumBits, SelectionDAG &DAG,
5415 const TargetLowering &TLI, SDLoc dl) {
5416 assert(VT.is128BitVector() && "Unknown type for VShift");
5417 EVT ShVT = MVT::v2i64;
5418 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5419 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5420 return DAG.getNode(ISD::BITCAST, dl, VT,
5421 DAG.getNode(Opc, dl, ShVT, SrcOp,
5422 DAG.getConstant(NumBits,
5423 TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5427 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5429 // Check if the scalar load can be widened into a vector load. And if
5430 // the address is "base + cst" see if the cst can be "absorbed" into
5431 // the shuffle mask.
5432 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5433 SDValue Ptr = LD->getBasePtr();
5434 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5436 EVT PVT = LD->getValueType(0);
5437 if (PVT != MVT::i32 && PVT != MVT::f32)
5442 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5443 FI = FINode->getIndex();
5445 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5446 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5447 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5448 Offset = Ptr.getConstantOperandVal(1);
5449 Ptr = Ptr.getOperand(0);
5454 // FIXME: 256-bit vector instructions don't require a strict alignment,
5455 // improve this code to support it better.
5456 unsigned RequiredAlign = VT.getSizeInBits()/8;
5457 SDValue Chain = LD->getChain();
5458 // Make sure the stack object alignment is at least 16 or 32.
5459 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5460 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5461 if (MFI->isFixedObjectIndex(FI)) {
5462 // Can't change the alignment. FIXME: It's possible to compute
5463 // the exact stack offset and reference FI + adjust offset instead.
5464 // If someone *really* cares about this. That's the way to implement it.
5467 MFI->setObjectAlignment(FI, RequiredAlign);
5471 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5472 // Ptr + (Offset & ~15).
5475 if ((Offset % RequiredAlign) & 3)
5477 int64_t StartOffset = Offset & ~(RequiredAlign-1);
5479 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5480 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5482 int EltNo = (Offset - StartOffset) >> 2;
5483 unsigned NumElems = VT.getVectorNumElements();
5485 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5486 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5487 LD->getPointerInfo().getWithOffset(StartOffset),
5488 false, false, false, 0);
5490 SmallVector<int, 8> Mask;
5491 for (unsigned i = 0; i != NumElems; ++i)
5492 Mask.push_back(EltNo);
5494 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5500 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5501 /// vector of type 'VT', see if the elements can be replaced by a single large
5502 /// load which has the same value as a build_vector whose operands are 'elts'.
5504 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5506 /// FIXME: we'd also like to handle the case where the last elements are zero
5507 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5508 /// There's even a handy isZeroNode for that purpose.
5509 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5510 SDLoc &DL, SelectionDAG &DAG,
5511 bool isAfterLegalize) {
5512 EVT EltVT = VT.getVectorElementType();
5513 unsigned NumElems = Elts.size();
5515 LoadSDNode *LDBase = nullptr;
5516 unsigned LastLoadedElt = -1U;
5518 // For each element in the initializer, see if we've found a load or an undef.
5519 // If we don't find an initial load element, or later load elements are
5520 // non-consecutive, bail out.
5521 for (unsigned i = 0; i < NumElems; ++i) {
5522 SDValue Elt = Elts[i];
5524 if (!Elt.getNode() ||
5525 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5528 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5530 LDBase = cast<LoadSDNode>(Elt.getNode());
5534 if (Elt.getOpcode() == ISD::UNDEF)
5537 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5538 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5543 // If we have found an entire vector of loads and undefs, then return a large
5544 // load of the entire vector width starting at the base pointer. If we found
5545 // consecutive loads for the low half, generate a vzext_load node.
5546 if (LastLoadedElt == NumElems - 1) {
5548 if (isAfterLegalize &&
5549 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5552 SDValue NewLd = SDValue();
5554 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5555 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5556 LDBase->getPointerInfo(),
5557 LDBase->isVolatile(), LDBase->isNonTemporal(),
5558 LDBase->isInvariant(), 0);
5559 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5560 LDBase->getPointerInfo(),
5561 LDBase->isVolatile(), LDBase->isNonTemporal(),
5562 LDBase->isInvariant(), LDBase->getAlignment());
5564 if (LDBase->hasAnyUseOfValue(1)) {
5565 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5567 SDValue(NewLd.getNode(), 1));
5568 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5569 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5570 SDValue(NewLd.getNode(), 1));
5575 if (NumElems == 4 && LastLoadedElt == 1 &&
5576 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5577 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5578 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5580 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops,
5581 array_lengthof(Ops), MVT::i64,
5582 LDBase->getPointerInfo(),
5583 LDBase->getAlignment(),
5584 false/*isVolatile*/, true/*ReadMem*/,
5587 // Make sure the newly-created LOAD is in the same position as LDBase in
5588 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5589 // update uses of LDBase's output chain to use the TokenFactor.
5590 if (LDBase->hasAnyUseOfValue(1)) {
5591 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5592 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5593 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5594 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5595 SDValue(ResNode.getNode(), 1));
5598 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5603 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5604 /// to generate a splat value for the following cases:
5605 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5606 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5607 /// a scalar load, or a constant.
5608 /// The VBROADCAST node is returned when a pattern is found,
5609 /// or SDValue() otherwise.
5610 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5611 SelectionDAG &DAG) {
5612 if (!Subtarget->hasFp256())
5615 MVT VT = Op.getSimpleValueType();
5618 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5619 "Unsupported vector type for broadcast.");
5624 switch (Op.getOpcode()) {
5626 // Unknown pattern found.
5629 case ISD::BUILD_VECTOR: {
5630 // The BUILD_VECTOR node must be a splat.
5631 if (!isSplatVector(Op.getNode()))
5634 Ld = Op.getOperand(0);
5635 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5636 Ld.getOpcode() == ISD::ConstantFP);
5638 // The suspected load node has several users. Make sure that all
5639 // of its users are from the BUILD_VECTOR node.
5640 // Constants may have multiple users.
5641 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5646 case ISD::VECTOR_SHUFFLE: {
5647 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5649 // Shuffles must have a splat mask where the first element is
5651 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5654 SDValue Sc = Op.getOperand(0);
5655 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5656 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5658 if (!Subtarget->hasInt256())
5661 // Use the register form of the broadcast instruction available on AVX2.
5662 if (VT.getSizeInBits() >= 256)
5663 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5664 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5667 Ld = Sc.getOperand(0);
5668 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5669 Ld.getOpcode() == ISD::ConstantFP);
5671 // The scalar_to_vector node and the suspected
5672 // load node must have exactly one user.
5673 // Constants may have multiple users.
5675 // AVX-512 has register version of the broadcast
5676 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5677 Ld.getValueType().getSizeInBits() >= 32;
5678 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5685 bool IsGE256 = (VT.getSizeInBits() >= 256);
5687 // Handle the broadcasting a single constant scalar from the constant pool
5688 // into a vector. On Sandybridge it is still better to load a constant vector
5689 // from the constant pool and not to broadcast it from a scalar.
5690 if (ConstSplatVal && Subtarget->hasInt256()) {
5691 EVT CVT = Ld.getValueType();
5692 assert(!CVT.isVector() && "Must not broadcast a vector type");
5693 unsigned ScalarSize = CVT.getSizeInBits();
5695 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5696 const Constant *C = nullptr;
5697 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5698 C = CI->getConstantIntValue();
5699 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5700 C = CF->getConstantFPValue();
5702 assert(C && "Invalid constant type");
5704 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5705 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5706 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5707 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5708 MachinePointerInfo::getConstantPool(),
5709 false, false, false, Alignment);
5711 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5715 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5716 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5718 // Handle AVX2 in-register broadcasts.
5719 if (!IsLoad && Subtarget->hasInt256() &&
5720 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5721 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5723 // The scalar source must be a normal load.
5727 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5728 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5730 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5731 // double since there is no vbroadcastsd xmm
5732 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5733 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5734 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5737 // Unsupported broadcast.
5741 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5742 /// underlying vector and index.
5744 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5746 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5748 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5749 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5752 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5754 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5756 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5757 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5760 // In this case the vector is the extract_subvector expression and the index
5761 // is 2, as specified by the shuffle.
5762 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5763 SDValue ShuffleVec = SVOp->getOperand(0);
5764 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5765 assert(ShuffleVecVT.getVectorElementType() ==
5766 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5768 int ShuffleIdx = SVOp->getMaskElt(Idx);
5769 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5770 ExtractedFromVec = ShuffleVec;
5776 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5777 MVT VT = Op.getSimpleValueType();
5779 // Skip if insert_vec_elt is not supported.
5780 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5781 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5785 unsigned NumElems = Op.getNumOperands();
5789 SmallVector<unsigned, 4> InsertIndices;
5790 SmallVector<int, 8> Mask(NumElems, -1);
5792 for (unsigned i = 0; i != NumElems; ++i) {
5793 unsigned Opc = Op.getOperand(i).getOpcode();
5795 if (Opc == ISD::UNDEF)
5798 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5799 // Quit if more than 1 elements need inserting.
5800 if (InsertIndices.size() > 1)
5803 InsertIndices.push_back(i);
5807 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5808 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5809 // Quit if non-constant index.
5810 if (!isa<ConstantSDNode>(ExtIdx))
5812 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5814 // Quit if extracted from vector of different type.
5815 if (ExtractedFromVec.getValueType() != VT)
5818 if (!VecIn1.getNode())
5819 VecIn1 = ExtractedFromVec;
5820 else if (VecIn1 != ExtractedFromVec) {
5821 if (!VecIn2.getNode())
5822 VecIn2 = ExtractedFromVec;
5823 else if (VecIn2 != ExtractedFromVec)
5824 // Quit if more than 2 vectors to shuffle
5828 if (ExtractedFromVec == VecIn1)
5830 else if (ExtractedFromVec == VecIn2)
5831 Mask[i] = Idx + NumElems;
5834 if (!VecIn1.getNode())
5837 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5838 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5839 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5840 unsigned Idx = InsertIndices[i];
5841 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5842 DAG.getIntPtrConstant(Idx));
5848 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5850 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5852 MVT VT = Op.getSimpleValueType();
5853 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5854 "Unexpected type in LowerBUILD_VECTORvXi1!");
5857 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5858 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5859 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5860 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5861 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5862 Ops, VT.getVectorNumElements());
5865 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5866 SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5867 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5868 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5869 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5870 Ops, VT.getVectorNumElements());
5873 bool AllContants = true;
5874 uint64_t Immediate = 0;
5875 int NonConstIdx = -1;
5876 bool IsSplat = true;
5877 unsigned NumNonConsts = 0;
5878 unsigned NumConsts = 0;
5879 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5880 SDValue In = Op.getOperand(idx);
5881 if (In.getOpcode() == ISD::UNDEF)
5883 if (!isa<ConstantSDNode>(In)) {
5884 AllContants = false;
5890 if (cast<ConstantSDNode>(In)->getZExtValue())
5891 Immediate |= (1ULL << idx);
5893 if (In != Op.getOperand(0))
5898 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5899 DAG.getConstant(Immediate, MVT::i16));
5900 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5901 DAG.getIntPtrConstant(0));
5904 if (NumNonConsts == 1 && NonConstIdx != 0) {
5907 SDValue VecAsImm = DAG.getConstant(Immediate,
5908 MVT::getIntegerVT(VT.getSizeInBits()));
5909 DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
5912 DstVec = DAG.getUNDEF(VT);
5913 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5914 Op.getOperand(NonConstIdx),
5915 DAG.getIntPtrConstant(NonConstIdx));
5917 if (!IsSplat && (NonConstIdx != 0))
5918 llvm_unreachable("Unsupported BUILD_VECTOR operation");
5919 MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
5922 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5923 DAG.getConstant(-1, SelectVT),
5924 DAG.getConstant(0, SelectVT));
5926 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5927 DAG.getConstant((Immediate | 1), SelectVT),
5928 DAG.getConstant(Immediate, SelectVT));
5929 return DAG.getNode(ISD::BITCAST, dl, VT, Select);
5933 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5936 MVT VT = Op.getSimpleValueType();
5937 MVT ExtVT = VT.getVectorElementType();
5938 unsigned NumElems = Op.getNumOperands();
5940 // Generate vectors for predicate vectors.
5941 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5942 return LowerBUILD_VECTORvXi1(Op, DAG);
5944 // Vectors containing all zeros can be matched by pxor and xorps later
5945 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5946 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5947 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5948 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5951 return getZeroVector(VT, Subtarget, DAG, dl);
5954 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5955 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5956 // vpcmpeqd on 256-bit vectors.
5957 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5958 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5961 if (!VT.is512BitVector())
5962 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5965 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
5966 if (Broadcast.getNode())
5969 unsigned EVTBits = ExtVT.getSizeInBits();
5971 unsigned NumZero = 0;
5972 unsigned NumNonZero = 0;
5973 unsigned NonZeros = 0;
5974 bool IsAllConstants = true;
5975 SmallSet<SDValue, 8> Values;
5976 for (unsigned i = 0; i < NumElems; ++i) {
5977 SDValue Elt = Op.getOperand(i);
5978 if (Elt.getOpcode() == ISD::UNDEF)
5981 if (Elt.getOpcode() != ISD::Constant &&
5982 Elt.getOpcode() != ISD::ConstantFP)
5983 IsAllConstants = false;
5984 if (X86::isZeroNode(Elt))
5987 NonZeros |= (1 << i);
5992 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5993 if (NumNonZero == 0)
5994 return DAG.getUNDEF(VT);
5996 // Special case for single non-zero, non-undef, element.
5997 if (NumNonZero == 1) {
5998 unsigned Idx = countTrailingZeros(NonZeros);
5999 SDValue Item = Op.getOperand(Idx);
6001 // If this is an insertion of an i64 value on x86-32, and if the top bits of
6002 // the value are obviously zero, truncate the value to i32 and do the
6003 // insertion that way. Only do this if the value is non-constant or if the
6004 // value is a constant being inserted into element 0. It is cheaper to do
6005 // a constant pool load than it is to do a movd + shuffle.
6006 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6007 (!IsAllConstants || Idx == 0)) {
6008 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6010 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6011 EVT VecVT = MVT::v4i32;
6012 unsigned VecElts = 4;
6014 // Truncate the value (which may itself be a constant) to i32, and
6015 // convert it to a vector with movd (S2V+shuffle to zero extend).
6016 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6017 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6018 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6020 // Now we have our 32-bit value zero extended in the low element of
6021 // a vector. If Idx != 0, swizzle it into place.
6023 SmallVector<int, 4> Mask;
6024 Mask.push_back(Idx);
6025 for (unsigned i = 1; i != VecElts; ++i)
6027 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6030 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6034 // If we have a constant or non-constant insertion into the low element of
6035 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6036 // the rest of the elements. This will be matched as movd/movq/movss/movsd
6037 // depending on what the source datatype is.
6040 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6042 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6043 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6044 if (VT.is256BitVector() || VT.is512BitVector()) {
6045 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6046 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6047 Item, DAG.getIntPtrConstant(0));
6049 assert(VT.is128BitVector() && "Expected an SSE value type!");
6050 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6051 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6052 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6055 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6056 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6057 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6058 if (VT.is256BitVector()) {
6059 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6060 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6062 assert(VT.is128BitVector() && "Expected an SSE value type!");
6063 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6065 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6069 // Is it a vector logical left shift?
6070 if (NumElems == 2 && Idx == 1 &&
6071 X86::isZeroNode(Op.getOperand(0)) &&
6072 !X86::isZeroNode(Op.getOperand(1))) {
6073 unsigned NumBits = VT.getSizeInBits();
6074 return getVShift(true, VT,
6075 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6076 VT, Op.getOperand(1)),
6077 NumBits/2, DAG, *this, dl);
6080 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6083 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6084 // is a non-constant being inserted into an element other than the low one,
6085 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6086 // movd/movss) to move this into the low element, then shuffle it into
6088 if (EVTBits == 32) {
6089 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6091 // Turn it into a shuffle of zero and zero-extended scalar to vector.
6092 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6093 SmallVector<int, 8> MaskVec;
6094 for (unsigned i = 0; i != NumElems; ++i)
6095 MaskVec.push_back(i == Idx ? 0 : 1);
6096 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6100 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6101 if (Values.size() == 1) {
6102 if (EVTBits == 32) {
6103 // Instead of a shuffle like this:
6104 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6105 // Check if it's possible to issue this instead.
6106 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6107 unsigned Idx = countTrailingZeros(NonZeros);
6108 SDValue Item = Op.getOperand(Idx);
6109 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6110 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6115 // A vector full of immediates; various special cases are already
6116 // handled, so this is best done with a single constant-pool load.
6120 // For AVX-length vectors, build the individual 128-bit pieces and use
6121 // shuffles to put them in place.
6122 if (VT.is256BitVector() || VT.is512BitVector()) {
6123 SmallVector<SDValue, 64> V;
6124 for (unsigned i = 0; i != NumElems; ++i)
6125 V.push_back(Op.getOperand(i));
6127 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6129 // Build both the lower and upper subvector.
6130 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
6131 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
6134 // Recreate the wider vector with the lower and upper part.
6135 if (VT.is256BitVector())
6136 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6137 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6140 // Let legalizer expand 2-wide build_vectors.
6141 if (EVTBits == 64) {
6142 if (NumNonZero == 1) {
6143 // One half is zero or undef.
6144 unsigned Idx = countTrailingZeros(NonZeros);
6145 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6146 Op.getOperand(Idx));
6147 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6152 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6153 if (EVTBits == 8 && NumElems == 16) {
6154 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6156 if (V.getNode()) return V;
6159 if (EVTBits == 16 && NumElems == 8) {
6160 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6162 if (V.getNode()) return V;
6165 // If element VT is == 32 bits, turn it into a number of shuffles.
6166 SmallVector<SDValue, 8> V(NumElems);
6167 if (NumElems == 4 && NumZero > 0) {
6168 for (unsigned i = 0; i < 4; ++i) {
6169 bool isZero = !(NonZeros & (1 << i));
6171 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6173 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6176 for (unsigned i = 0; i < 2; ++i) {
6177 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6180 V[i] = V[i*2]; // Must be a zero vector.
6183 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6186 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6189 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6194 bool Reverse1 = (NonZeros & 0x3) == 2;
6195 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6199 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6200 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6202 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6205 if (Values.size() > 1 && VT.is128BitVector()) {
6206 // Check for a build vector of consecutive loads.
6207 for (unsigned i = 0; i < NumElems; ++i)
6208 V[i] = Op.getOperand(i);
6210 // Check for elements which are consecutive loads.
6211 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6215 // Check for a build vector from mostly shuffle plus few inserting.
6216 SDValue Sh = buildFromShuffleMostly(Op, DAG);
6220 // For SSE 4.1, use insertps to put the high elements into the low element.
6221 if (getSubtarget()->hasSSE41()) {
6223 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6224 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6226 Result = DAG.getUNDEF(VT);
6228 for (unsigned i = 1; i < NumElems; ++i) {
6229 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6230 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6231 Op.getOperand(i), DAG.getIntPtrConstant(i));
6236 // Otherwise, expand into a number of unpckl*, start by extending each of
6237 // our (non-undef) elements to the full vector width with the element in the
6238 // bottom slot of the vector (which generates no code for SSE).
6239 for (unsigned i = 0; i < NumElems; ++i) {
6240 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6241 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6243 V[i] = DAG.getUNDEF(VT);
6246 // Next, we iteratively mix elements, e.g. for v4f32:
6247 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6248 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6249 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6250 unsigned EltStride = NumElems >> 1;
6251 while (EltStride != 0) {
6252 for (unsigned i = 0; i < EltStride; ++i) {
6253 // If V[i+EltStride] is undef and this is the first round of mixing,
6254 // then it is safe to just drop this shuffle: V[i] is already in the
6255 // right place, the one element (since it's the first round) being
6256 // inserted as undef can be dropped. This isn't safe for successive
6257 // rounds because they will permute elements within both vectors.
6258 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6259 EltStride == NumElems/2)
6262 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6271 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6272 // to create 256-bit vectors from two other 128-bit ones.
6273 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6275 MVT ResVT = Op.getSimpleValueType();
6277 assert((ResVT.is256BitVector() ||
6278 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6280 SDValue V1 = Op.getOperand(0);
6281 SDValue V2 = Op.getOperand(1);
6282 unsigned NumElems = ResVT.getVectorNumElements();
6283 if(ResVT.is256BitVector())
6284 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6286 if (Op.getNumOperands() == 4) {
6287 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6288 ResVT.getVectorNumElements()/2);
6289 SDValue V3 = Op.getOperand(2);
6290 SDValue V4 = Op.getOperand(3);
6291 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6292 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6294 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6297 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6298 MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6299 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6300 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6301 Op.getNumOperands() == 4)));
6303 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6304 // from two other 128-bit ones.
6306 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6307 return LowerAVXCONCAT_VECTORS(Op, DAG);
6310 // Try to lower a shuffle node into a simple blend instruction.
6312 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6313 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6314 SDValue V1 = SVOp->getOperand(0);
6315 SDValue V2 = SVOp->getOperand(1);
6317 MVT VT = SVOp->getSimpleValueType(0);
6318 MVT EltVT = VT.getVectorElementType();
6319 unsigned NumElems = VT.getVectorNumElements();
6321 // There is no blend with immediate in AVX-512.
6322 if (VT.is512BitVector())
6325 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
6327 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
6330 // Check the mask for BLEND and build the value.
6331 unsigned MaskValue = 0;
6332 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6333 unsigned NumLanes = (NumElems-1)/8 + 1;
6334 unsigned NumElemsInLane = NumElems / NumLanes;
6336 // Blend for v16i16 should be symetric for the both lanes.
6337 for (unsigned i = 0; i < NumElemsInLane; ++i) {
6339 int SndLaneEltIdx = (NumLanes == 2) ?
6340 SVOp->getMaskElt(i + NumElemsInLane) : -1;
6341 int EltIdx = SVOp->getMaskElt(i);
6343 if ((EltIdx < 0 || EltIdx == (int)i) &&
6344 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6347 if (((unsigned)EltIdx == (i + NumElems)) &&
6348 (SndLaneEltIdx < 0 ||
6349 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6350 MaskValue |= (1<<i);
6355 // Convert i32 vectors to floating point if it is not AVX2.
6356 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6358 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6359 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6361 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6362 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6365 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6366 DAG.getConstant(MaskValue, MVT::i32));
6367 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6370 /// In vector type \p VT, return true if the element at index \p InputIdx
6371 /// falls on a different 128-bit lane than \p OutputIdx.
6372 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
6373 unsigned OutputIdx) {
6374 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6375 return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
6378 /// Generate a PSHUFB if possible. Selects elements from \p V1 according to
6379 /// \p MaskVals. MaskVals[OutputIdx] = InputIdx specifies that we want to
6380 /// shuffle the element at InputIdx in V1 to OutputIdx in the result. If \p
6381 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
6383 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
6384 SelectionDAG &DAG) {
6385 MVT VT = V1.getSimpleValueType();
6386 assert(VT.is128BitVector() || VT.is256BitVector());
6388 MVT EltVT = VT.getVectorElementType();
6389 unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
6390 unsigned NumElts = VT.getVectorNumElements();
6392 SmallVector<SDValue, 32> PshufbMask;
6393 for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
6394 int InputIdx = MaskVals[OutputIdx];
6395 unsigned InputByteIdx;
6397 if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
6398 InputByteIdx = 0x80;
6400 // Cross lane is not allowed.
6401 if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
6403 InputByteIdx = InputIdx * EltSizeInBytes;
6404 // Index is an byte offset within the 128-bit lane.
6405 InputByteIdx &= 0xf;
6408 for (unsigned j = 0; j < EltSizeInBytes; ++j) {
6409 PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
6410 if (InputByteIdx != 0x80)
6415 MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
6417 V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
6418 return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
6419 DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT,
6420 PshufbMask.data(), PshufbMask.size()));
6423 // v8i16 shuffles - Prefer shuffles in the following order:
6424 // 1. [all] pshuflw, pshufhw, optional move
6425 // 2. [ssse3] 1 x pshufb
6426 // 3. [ssse3] 2 x pshufb + 1 x por
6427 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6429 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6430 SelectionDAG &DAG) {
6431 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6432 SDValue V1 = SVOp->getOperand(0);
6433 SDValue V2 = SVOp->getOperand(1);
6435 SmallVector<int, 8> MaskVals;
6437 // Determine if more than 1 of the words in each of the low and high quadwords
6438 // of the result come from the same quadword of one of the two inputs. Undef
6439 // mask values count as coming from any quadword, for better codegen.
6441 // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
6442 // feeds this quad. For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
6443 unsigned LoQuad[] = { 0, 0, 0, 0 };
6444 unsigned HiQuad[] = { 0, 0, 0, 0 };
6445 // Indices of quads used.
6446 std::bitset<4> InputQuads;
6447 for (unsigned i = 0; i < 8; ++i) {
6448 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6449 int EltIdx = SVOp->getMaskElt(i);
6450 MaskVals.push_back(EltIdx);
6459 InputQuads.set(EltIdx / 4);
6462 int BestLoQuad = -1;
6463 unsigned MaxQuad = 1;
6464 for (unsigned i = 0; i < 4; ++i) {
6465 if (LoQuad[i] > MaxQuad) {
6467 MaxQuad = LoQuad[i];
6471 int BestHiQuad = -1;
6473 for (unsigned i = 0; i < 4; ++i) {
6474 if (HiQuad[i] > MaxQuad) {
6476 MaxQuad = HiQuad[i];
6480 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6481 // of the two input vectors, shuffle them into one input vector so only a
6482 // single pshufb instruction is necessary. If there are more than 2 input
6483 // quads, disable the next transformation since it does not help SSSE3.
6484 bool V1Used = InputQuads[0] || InputQuads[1];
6485 bool V2Used = InputQuads[2] || InputQuads[3];
6486 if (Subtarget->hasSSSE3()) {
6487 if (InputQuads.count() == 2 && V1Used && V2Used) {
6488 BestLoQuad = InputQuads[0] ? 0 : 1;
6489 BestHiQuad = InputQuads[2] ? 2 : 3;
6491 if (InputQuads.count() > 2) {
6497 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6498 // the shuffle mask. If a quad is scored as -1, that means that it contains
6499 // words from all 4 input quadwords.
6501 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6503 BestLoQuad < 0 ? 0 : BestLoQuad,
6504 BestHiQuad < 0 ? 1 : BestHiQuad
6506 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6507 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6508 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6509 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6511 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6512 // source words for the shuffle, to aid later transformations.
6513 bool AllWordsInNewV = true;
6514 bool InOrder[2] = { true, true };
6515 for (unsigned i = 0; i != 8; ++i) {
6516 int idx = MaskVals[i];
6518 InOrder[i/4] = false;
6519 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6521 AllWordsInNewV = false;
6525 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6526 if (AllWordsInNewV) {
6527 for (int i = 0; i != 8; ++i) {
6528 int idx = MaskVals[i];
6531 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6532 if ((idx != i) && idx < 4)
6534 if ((idx != i) && idx > 3)
6543 // If we've eliminated the use of V2, and the new mask is a pshuflw or
6544 // pshufhw, that's as cheap as it gets. Return the new shuffle.
6545 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6546 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6547 unsigned TargetMask = 0;
6548 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6549 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6550 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6551 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6552 getShufflePSHUFLWImmediate(SVOp);
6553 V1 = NewV.getOperand(0);
6554 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6558 // Promote splats to a larger type which usually leads to more efficient code.
6559 // FIXME: Is this true if pshufb is available?
6560 if (SVOp->isSplat())
6561 return PromoteSplat(SVOp, DAG);
6563 // If we have SSSE3, and all words of the result are from 1 input vector,
6564 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
6565 // is present, fall back to case 4.
6566 if (Subtarget->hasSSSE3()) {
6567 SmallVector<SDValue,16> pshufbMask;
6569 // If we have elements from both input vectors, set the high bit of the
6570 // shuffle mask element to zero out elements that come from V2 in the V1
6571 // mask, and elements that come from V1 in the V2 mask, so that the two
6572 // results can be OR'd together.
6573 bool TwoInputs = V1Used && V2Used;
6574 V1 = getPSHUFB(MaskVals, V1, dl, DAG);
6576 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6578 // Calculate the shuffle mask for the second input, shuffle it, and
6579 // OR it with the first shuffled input.
6580 CommuteVectorShuffleMask(MaskVals, 8);
6581 V2 = getPSHUFB(MaskVals, V2, dl, DAG);
6582 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6583 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6586 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6587 // and update MaskVals with new element order.
6588 std::bitset<8> InOrder;
6589 if (BestLoQuad >= 0) {
6590 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6591 for (int i = 0; i != 4; ++i) {
6592 int idx = MaskVals[i];
6595 } else if ((idx / 4) == BestLoQuad) {
6600 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6603 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6604 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6605 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6607 getShufflePSHUFLWImmediate(SVOp), DAG);
6611 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6612 // and update MaskVals with the new element order.
6613 if (BestHiQuad >= 0) {
6614 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6615 for (unsigned i = 4; i != 8; ++i) {
6616 int idx = MaskVals[i];
6619 } else if ((idx / 4) == BestHiQuad) {
6620 MaskV[i] = (idx & 3) + 4;
6624 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6627 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6628 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6629 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6631 getShufflePSHUFHWImmediate(SVOp), DAG);
6635 // In case BestHi & BestLo were both -1, which means each quadword has a word
6636 // from each of the four input quadwords, calculate the InOrder bitvector now
6637 // before falling through to the insert/extract cleanup.
6638 if (BestLoQuad == -1 && BestHiQuad == -1) {
6640 for (int i = 0; i != 8; ++i)
6641 if (MaskVals[i] < 0 || MaskVals[i] == i)
6645 // The other elements are put in the right place using pextrw and pinsrw.
6646 for (unsigned i = 0; i != 8; ++i) {
6649 int EltIdx = MaskVals[i];
6652 SDValue ExtOp = (EltIdx < 8) ?
6653 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6654 DAG.getIntPtrConstant(EltIdx)) :
6655 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6656 DAG.getIntPtrConstant(EltIdx - 8));
6657 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6658 DAG.getIntPtrConstant(i));
6663 /// \brief v16i16 shuffles
6665 /// FIXME: We only support generation of a single pshufb currently. We can
6666 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
6667 /// well (e.g 2 x pshufb + 1 x por).
6669 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
6670 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6671 SDValue V1 = SVOp->getOperand(0);
6672 SDValue V2 = SVOp->getOperand(1);
6675 if (V2.getOpcode() != ISD::UNDEF)
6678 SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6679 return getPSHUFB(MaskVals, V1, dl, DAG);
6682 // v16i8 shuffles - Prefer shuffles in the following order:
6683 // 1. [ssse3] 1 x pshufb
6684 // 2. [ssse3] 2 x pshufb + 1 x por
6685 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
6686 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6687 const X86Subtarget* Subtarget,
6688 SelectionDAG &DAG) {
6689 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6690 SDValue V1 = SVOp->getOperand(0);
6691 SDValue V2 = SVOp->getOperand(1);
6693 ArrayRef<int> MaskVals = SVOp->getMask();
6695 // Promote splats to a larger type which usually leads to more efficient code.
6696 // FIXME: Is this true if pshufb is available?
6697 if (SVOp->isSplat())
6698 return PromoteSplat(SVOp, DAG);
6700 // If we have SSSE3, case 1 is generated when all result bytes come from
6701 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
6702 // present, fall back to case 3.
6704 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6705 if (Subtarget->hasSSSE3()) {
6706 SmallVector<SDValue,16> pshufbMask;
6708 // If all result elements are from one input vector, then only translate
6709 // undef mask values to 0x80 (zero out result) in the pshufb mask.
6711 // Otherwise, we have elements from both input vectors, and must zero out
6712 // elements that come from V2 in the first mask, and V1 in the second mask
6713 // so that we can OR them together.
6714 for (unsigned i = 0; i != 16; ++i) {
6715 int EltIdx = MaskVals[i];
6716 if (EltIdx < 0 || EltIdx >= 16)
6718 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6720 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6721 DAG.getNode(ISD::BUILD_VECTOR, dl,
6722 MVT::v16i8, &pshufbMask[0], 16));
6724 // As PSHUFB will zero elements with negative indices, it's safe to ignore
6725 // the 2nd operand if it's undefined or zero.
6726 if (V2.getOpcode() == ISD::UNDEF ||
6727 ISD::isBuildVectorAllZeros(V2.getNode()))
6730 // Calculate the shuffle mask for the second input, shuffle it, and
6731 // OR it with the first shuffled input.
6733 for (unsigned i = 0; i != 16; ++i) {
6734 int EltIdx = MaskVals[i];
6735 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6736 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6738 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6739 DAG.getNode(ISD::BUILD_VECTOR, dl,
6740 MVT::v16i8, &pshufbMask[0], 16));
6741 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6744 // No SSSE3 - Calculate in place words and then fix all out of place words
6745 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
6746 // the 16 different words that comprise the two doublequadword input vectors.
6747 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6748 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6750 for (int i = 0; i != 8; ++i) {
6751 int Elt0 = MaskVals[i*2];
6752 int Elt1 = MaskVals[i*2+1];
6754 // This word of the result is all undef, skip it.
6755 if (Elt0 < 0 && Elt1 < 0)
6758 // This word of the result is already in the correct place, skip it.
6759 if ((Elt0 == i*2) && (Elt1 == i*2+1))
6762 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6763 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6766 // If Elt0 and Elt1 are defined, are consecutive, and can be load
6767 // using a single extract together, load it and store it.
6768 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6769 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6770 DAG.getIntPtrConstant(Elt1 / 2));
6771 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6772 DAG.getIntPtrConstant(i));
6776 // If Elt1 is defined, extract it from the appropriate source. If the
6777 // source byte is not also odd, shift the extracted word left 8 bits
6778 // otherwise clear the bottom 8 bits if we need to do an or.
6780 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6781 DAG.getIntPtrConstant(Elt1 / 2));
6782 if ((Elt1 & 1) == 0)
6783 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6785 TLI.getShiftAmountTy(InsElt.getValueType())));
6787 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6788 DAG.getConstant(0xFF00, MVT::i16));
6790 // If Elt0 is defined, extract it from the appropriate source. If the
6791 // source byte is not also even, shift the extracted word right 8 bits. If
6792 // Elt1 was also defined, OR the extracted values together before
6793 // inserting them in the result.
6795 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6796 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6797 if ((Elt0 & 1) != 0)
6798 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6800 TLI.getShiftAmountTy(InsElt0.getValueType())));
6802 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6803 DAG.getConstant(0x00FF, MVT::i16));
6804 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6807 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6808 DAG.getIntPtrConstant(i));
6810 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6813 // v32i8 shuffles - Translate to VPSHUFB if possible.
6815 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6816 const X86Subtarget *Subtarget,
6817 SelectionDAG &DAG) {
6818 MVT VT = SVOp->getSimpleValueType(0);
6819 SDValue V1 = SVOp->getOperand(0);
6820 SDValue V2 = SVOp->getOperand(1);
6822 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6824 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6825 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6826 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6828 // VPSHUFB may be generated if
6829 // (1) one of input vector is undefined or zeroinitializer.
6830 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6831 // And (2) the mask indexes don't cross the 128-bit lane.
6832 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6833 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6836 if (V1IsAllZero && !V2IsAllZero) {
6837 CommuteVectorShuffleMask(MaskVals, 32);
6840 return getPSHUFB(MaskVals, V1, dl, DAG);
6843 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6844 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6845 /// done when every pair / quad of shuffle mask elements point to elements in
6846 /// the right sequence. e.g.
6847 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6849 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6850 SelectionDAG &DAG) {
6851 MVT VT = SVOp->getSimpleValueType(0);
6853 unsigned NumElems = VT.getVectorNumElements();
6856 switch (VT.SimpleTy) {
6857 default: llvm_unreachable("Unexpected!");
6858 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
6859 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
6860 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
6861 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
6862 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6863 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
6866 SmallVector<int, 8> MaskVec;
6867 for (unsigned i = 0; i != NumElems; i += Scale) {
6869 for (unsigned j = 0; j != Scale; ++j) {
6870 int EltIdx = SVOp->getMaskElt(i+j);
6874 StartIdx = (EltIdx / Scale);
6875 if (EltIdx != (int)(StartIdx*Scale + j))
6878 MaskVec.push_back(StartIdx);
6881 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6882 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6883 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6886 /// getVZextMovL - Return a zero-extending vector move low node.
6888 static SDValue getVZextMovL(MVT VT, MVT OpVT,
6889 SDValue SrcOp, SelectionDAG &DAG,
6890 const X86Subtarget *Subtarget, SDLoc dl) {
6891 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6892 LoadSDNode *LD = nullptr;
6893 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6894 LD = dyn_cast<LoadSDNode>(SrcOp);
6896 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6898 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6899 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6900 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6901 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6902 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6904 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6905 return DAG.getNode(ISD::BITCAST, dl, VT,
6906 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6907 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6915 return DAG.getNode(ISD::BITCAST, dl, VT,
6916 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6917 DAG.getNode(ISD::BITCAST, dl,
6921 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6922 /// which could not be matched by any known target speficic shuffle
6924 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6926 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6927 if (NewOp.getNode())
6930 MVT VT = SVOp->getSimpleValueType(0);
6932 unsigned NumElems = VT.getVectorNumElements();
6933 unsigned NumLaneElems = NumElems / 2;
6936 MVT EltVT = VT.getVectorElementType();
6937 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6940 SmallVector<int, 16> Mask;
6941 for (unsigned l = 0; l < 2; ++l) {
6942 // Build a shuffle mask for the output, discovering on the fly which
6943 // input vectors to use as shuffle operands (recorded in InputUsed).
6944 // If building a suitable shuffle vector proves too hard, then bail
6945 // out with UseBuildVector set.
6946 bool UseBuildVector = false;
6947 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6948 unsigned LaneStart = l * NumLaneElems;
6949 for (unsigned i = 0; i != NumLaneElems; ++i) {
6950 // The mask element. This indexes into the input.
6951 int Idx = SVOp->getMaskElt(i+LaneStart);
6953 // the mask element does not index into any input vector.
6958 // The input vector this mask element indexes into.
6959 int Input = Idx / NumLaneElems;
6961 // Turn the index into an offset from the start of the input vector.
6962 Idx -= Input * NumLaneElems;
6964 // Find or create a shuffle vector operand to hold this input.
6966 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6967 if (InputUsed[OpNo] == Input)
6968 // This input vector is already an operand.
6970 if (InputUsed[OpNo] < 0) {
6971 // Create a new operand for this input vector.
6972 InputUsed[OpNo] = Input;
6977 if (OpNo >= array_lengthof(InputUsed)) {
6978 // More than two input vectors used! Give up on trying to create a
6979 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
6980 UseBuildVector = true;
6984 // Add the mask index for the new shuffle vector.
6985 Mask.push_back(Idx + OpNo * NumLaneElems);
6988 if (UseBuildVector) {
6989 SmallVector<SDValue, 16> SVOps;
6990 for (unsigned i = 0; i != NumLaneElems; ++i) {
6991 // The mask element. This indexes into the input.
6992 int Idx = SVOp->getMaskElt(i+LaneStart);
6994 SVOps.push_back(DAG.getUNDEF(EltVT));
6998 // The input vector this mask element indexes into.
6999 int Input = Idx / NumElems;
7001 // Turn the index into an offset from the start of the input vector.
7002 Idx -= Input * NumElems;
7004 // Extract the vector element by hand.
7005 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
7006 SVOp->getOperand(Input),
7007 DAG.getIntPtrConstant(Idx)));
7010 // Construct the output using a BUILD_VECTOR.
7011 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
7013 } else if (InputUsed[0] < 0) {
7014 // No input vectors were used! The result is undefined.
7015 Output[l] = DAG.getUNDEF(NVT);
7017 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
7018 (InputUsed[0] % 2) * NumLaneElems,
7020 // If only one input was used, use an undefined vector for the other.
7021 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
7022 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
7023 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
7024 // At least one input vector was used. Create a new shuffle vector.
7025 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
7031 // Concatenate the result back
7032 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
7035 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
7036 /// 4 elements, and match them with several different shuffle types.
7038 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7039 SDValue V1 = SVOp->getOperand(0);
7040 SDValue V2 = SVOp->getOperand(1);
7042 MVT VT = SVOp->getSimpleValueType(0);
7044 assert(VT.is128BitVector() && "Unsupported vector size");
7046 std::pair<int, int> Locs[4];
7047 int Mask1[] = { -1, -1, -1, -1 };
7048 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
7052 for (unsigned i = 0; i != 4; ++i) {
7053 int Idx = PermMask[i];
7055 Locs[i] = std::make_pair(-1, -1);
7057 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
7059 Locs[i] = std::make_pair(0, NumLo);
7063 Locs[i] = std::make_pair(1, NumHi);
7065 Mask1[2+NumHi] = Idx;
7071 if (NumLo <= 2 && NumHi <= 2) {
7072 // If no more than two elements come from either vector. This can be
7073 // implemented with two shuffles. First shuffle gather the elements.
7074 // The second shuffle, which takes the first shuffle as both of its
7075 // vector operands, put the elements into the right order.
7076 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7078 int Mask2[] = { -1, -1, -1, -1 };
7080 for (unsigned i = 0; i != 4; ++i)
7081 if (Locs[i].first != -1) {
7082 unsigned Idx = (i < 2) ? 0 : 4;
7083 Idx += Locs[i].first * 2 + Locs[i].second;
7087 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
7090 if (NumLo == 3 || NumHi == 3) {
7091 // Otherwise, we must have three elements from one vector, call it X, and
7092 // one element from the other, call it Y. First, use a shufps to build an
7093 // intermediate vector with the one element from Y and the element from X
7094 // that will be in the same half in the final destination (the indexes don't
7095 // matter). Then, use a shufps to build the final vector, taking the half
7096 // containing the element from Y from the intermediate, and the other half
7099 // Normalize it so the 3 elements come from V1.
7100 CommuteVectorShuffleMask(PermMask, 4);
7104 // Find the element from V2.
7106 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
7107 int Val = PermMask[HiIndex];
7114 Mask1[0] = PermMask[HiIndex];
7116 Mask1[2] = PermMask[HiIndex^1];
7118 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7121 Mask1[0] = PermMask[0];
7122 Mask1[1] = PermMask[1];
7123 Mask1[2] = HiIndex & 1 ? 6 : 4;
7124 Mask1[3] = HiIndex & 1 ? 4 : 6;
7125 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7128 Mask1[0] = HiIndex & 1 ? 2 : 0;
7129 Mask1[1] = HiIndex & 1 ? 0 : 2;
7130 Mask1[2] = PermMask[2];
7131 Mask1[3] = PermMask[3];
7136 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7139 // Break it into (shuffle shuffle_hi, shuffle_lo).
7140 int LoMask[] = { -1, -1, -1, -1 };
7141 int HiMask[] = { -1, -1, -1, -1 };
7143 int *MaskPtr = LoMask;
7144 unsigned MaskIdx = 0;
7147 for (unsigned i = 0; i != 4; ++i) {
7154 int Idx = PermMask[i];
7156 Locs[i] = std::make_pair(-1, -1);
7157 } else if (Idx < 4) {
7158 Locs[i] = std::make_pair(MaskIdx, LoIdx);
7159 MaskPtr[LoIdx] = Idx;
7162 Locs[i] = std::make_pair(MaskIdx, HiIdx);
7163 MaskPtr[HiIdx] = Idx;
7168 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7169 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7170 int MaskOps[] = { -1, -1, -1, -1 };
7171 for (unsigned i = 0; i != 4; ++i)
7172 if (Locs[i].first != -1)
7173 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7174 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7177 static bool MayFoldVectorLoad(SDValue V) {
7178 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7179 V = V.getOperand(0);
7181 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7182 V = V.getOperand(0);
7183 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7184 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7185 // BUILD_VECTOR (load), undef
7186 V = V.getOperand(0);
7188 return MayFoldLoad(V);
7192 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7193 MVT VT = Op.getSimpleValueType();
7195 // Canonizalize to v2f64.
7196 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7197 return DAG.getNode(ISD::BITCAST, dl, VT,
7198 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7203 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7205 SDValue V1 = Op.getOperand(0);
7206 SDValue V2 = Op.getOperand(1);
7207 MVT VT = Op.getSimpleValueType();
7209 assert(VT != MVT::v2i64 && "unsupported shuffle type");
7211 if (HasSSE2 && VT == MVT::v2f64)
7212 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7214 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7215 return DAG.getNode(ISD::BITCAST, dl, VT,
7216 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7217 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7218 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7222 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7223 SDValue V1 = Op.getOperand(0);
7224 SDValue V2 = Op.getOperand(1);
7225 MVT VT = Op.getSimpleValueType();
7227 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7228 "unsupported shuffle type");
7230 if (V2.getOpcode() == ISD::UNDEF)
7234 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7238 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7239 SDValue V1 = Op.getOperand(0);
7240 SDValue V2 = Op.getOperand(1);
7241 MVT VT = Op.getSimpleValueType();
7242 unsigned NumElems = VT.getVectorNumElements();
7244 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7245 // operand of these instructions is only memory, so check if there's a
7246 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7248 bool CanFoldLoad = false;
7250 // Trivial case, when V2 comes from a load.
7251 if (MayFoldVectorLoad(V2))
7254 // When V1 is a load, it can be folded later into a store in isel, example:
7255 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7257 // (MOVLPSmr addr:$src1, VR128:$src2)
7258 // So, recognize this potential and also use MOVLPS or MOVLPD
7259 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7262 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7264 if (HasSSE2 && NumElems == 2)
7265 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7268 // If we don't care about the second element, proceed to use movss.
7269 if (SVOp->getMaskElt(1) != -1)
7270 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7273 // movl and movlp will both match v2i64, but v2i64 is never matched by
7274 // movl earlier because we make it strict to avoid messing with the movlp load
7275 // folding logic (see the code above getMOVLP call). Match it here then,
7276 // this is horrible, but will stay like this until we move all shuffle
7277 // matching to x86 specific nodes. Note that for the 1st condition all
7278 // types are matched with movsd.
7280 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7281 // as to remove this logic from here, as much as possible
7282 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7283 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7284 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7287 assert(VT != MVT::v4i32 && "unsupported shuffle type");
7289 // Invert the operand order and use SHUFPS to match it.
7290 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7291 getShuffleSHUFImmediate(SVOp), DAG);
7294 // It is only safe to call this function if isINSERTPSMask is true for
7295 // this shufflevector mask.
7296 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
7297 SelectionDAG &DAG) {
7298 // Generate an insertps instruction when inserting an f32 from memory onto a
7299 // v4f32 or when copying a member from one v4f32 to another.
7300 // We also use it for transferring i32 from one register to another,
7301 // since it simply copies the same bits.
7302 // If we're transfering an i32 from memory to a specific element in a
7303 // register, we output a generic DAG that will match the PINSRD
7305 // TODO: Optimize for AVX cases too (VINSERTPS)
7306 MVT VT = SVOp->getSimpleValueType(0);
7307 MVT EVT = VT.getVectorElementType();
7308 SDValue V1 = SVOp->getOperand(0);
7309 SDValue V2 = SVOp->getOperand(1);
7310 auto Mask = SVOp->getMask();
7311 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
7312 "unsupported vector type for insertps/pinsrd");
7314 int FromV1 = std::count_if(Mask.begin(), Mask.end(),
7315 [](const int &i) { return i < 4; });
7323 DestIndex = std::find_if(Mask.begin(), Mask.end(),
7324 [](const int &i) { return i < 4; }) -
7329 DestIndex = std::find_if(Mask.begin(), Mask.end(),
7330 [](const int &i) { return i >= 4; }) -
7334 if (MayFoldLoad(From)) {
7335 // Trivial case, when From comes from a load and is only used by the
7336 // shuffle. Make it use insertps from the vector that we need from that
7338 SDValue Addr = From.getOperand(1);
7340 DAG.getNode(ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
7341 DAG.getConstant(DestIndex * EVT.getStoreSize(),
7342 Addr.getSimpleValueType()));
7344 LoadSDNode *Load = cast<LoadSDNode>(From);
7346 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
7347 DAG.getMachineFunction().getMachineMemOperand(
7348 Load->getMemOperand(), 0, EVT.getStoreSize()));
7350 if (EVT == MVT::f32) {
7351 // Create this as a scalar to vector to match the instruction pattern.
7352 SDValue LoadScalarToVector =
7353 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
7354 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
7355 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
7357 } else { // EVT == MVT::i32
7358 // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
7359 // instruction, to match the PINSRD instruction, which loads an i32 to a
7360 // certain vector element.
7361 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
7362 DAG.getConstant(DestIndex, MVT::i32));
7366 // Vector-element-to-vector
7367 unsigned SrcIndex = Mask[DestIndex] % 4;
7368 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
7369 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
7372 // Reduce a vector shuffle to zext.
7373 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7374 SelectionDAG &DAG) {
7375 // PMOVZX is only available from SSE41.
7376 if (!Subtarget->hasSSE41())
7379 MVT VT = Op.getSimpleValueType();
7381 // Only AVX2 support 256-bit vector integer extending.
7382 if (!Subtarget->hasInt256() && VT.is256BitVector())
7385 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7387 SDValue V1 = Op.getOperand(0);
7388 SDValue V2 = Op.getOperand(1);
7389 unsigned NumElems = VT.getVectorNumElements();
7391 // Extending is an unary operation and the element type of the source vector
7392 // won't be equal to or larger than i64.
7393 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7394 VT.getVectorElementType() == MVT::i64)
7397 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7398 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7399 while ((1U << Shift) < NumElems) {
7400 if (SVOp->getMaskElt(1U << Shift) == 1)
7403 // The maximal ratio is 8, i.e. from i8 to i64.
7408 // Check the shuffle mask.
7409 unsigned Mask = (1U << Shift) - 1;
7410 for (unsigned i = 0; i != NumElems; ++i) {
7411 int EltIdx = SVOp->getMaskElt(i);
7412 if ((i & Mask) != 0 && EltIdx != -1)
7414 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7418 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7419 MVT NeVT = MVT::getIntegerVT(NBits);
7420 MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7422 if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7425 // Simplify the operand as it's prepared to be fed into shuffle.
7426 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7427 if (V1.getOpcode() == ISD::BITCAST &&
7428 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7429 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7430 V1.getOperand(0).getOperand(0)
7431 .getSimpleValueType().getSizeInBits() == SignificantBits) {
7432 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7433 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7434 ConstantSDNode *CIdx =
7435 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7436 // If it's foldable, i.e. normal load with single use, we will let code
7437 // selection to fold it. Otherwise, we will short the conversion sequence.
7438 if (CIdx && CIdx->getZExtValue() == 0 &&
7439 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7440 MVT FullVT = V.getSimpleValueType();
7441 MVT V1VT = V1.getSimpleValueType();
7442 if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7443 // The "ext_vec_elt" node is wider than the result node.
7444 // In this case we should extract subvector from V.
7445 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7446 unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7447 MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7448 FullVT.getVectorNumElements()/Ratio);
7449 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7450 DAG.getIntPtrConstant(0));
7452 V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7456 return DAG.getNode(ISD::BITCAST, DL, VT,
7457 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7461 NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7462 SelectionDAG &DAG) {
7463 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7464 MVT VT = Op.getSimpleValueType();
7466 SDValue V1 = Op.getOperand(0);
7467 SDValue V2 = Op.getOperand(1);
7469 if (isZeroShuffle(SVOp))
7470 return getZeroVector(VT, Subtarget, DAG, dl);
7472 // Handle splat operations
7473 if (SVOp->isSplat()) {
7474 // Use vbroadcast whenever the splat comes from a foldable load
7475 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7476 if (Broadcast.getNode())
7480 // Check integer expanding shuffles.
7481 SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7482 if (NewOp.getNode())
7485 // If the shuffle can be profitably rewritten as a narrower shuffle, then
7487 if (VT == MVT::v8i16 || VT == MVT::v16i8 ||
7488 VT == MVT::v16i16 || VT == MVT::v32i8) {
7489 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7490 if (NewOp.getNode())
7491 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7492 } else if ((VT == MVT::v4i32 ||
7493 (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
7494 // FIXME: Figure out a cleaner way to do this.
7495 // Try to make use of movq to zero out the top part.
7496 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7497 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7498 if (NewOp.getNode()) {
7499 MVT NewVT = NewOp.getSimpleValueType();
7500 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7501 NewVT, true, false))
7502 return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
7503 DAG, Subtarget, dl);
7505 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7506 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7507 if (NewOp.getNode()) {
7508 MVT NewVT = NewOp.getSimpleValueType();
7509 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7510 return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
7511 DAG, Subtarget, dl);
7519 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7520 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7521 SDValue V1 = Op.getOperand(0);
7522 SDValue V2 = Op.getOperand(1);
7523 MVT VT = Op.getSimpleValueType();
7525 unsigned NumElems = VT.getVectorNumElements();
7526 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7527 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7528 bool V1IsSplat = false;
7529 bool V2IsSplat = false;
7530 bool HasSSE2 = Subtarget->hasSSE2();
7531 bool HasFp256 = Subtarget->hasFp256();
7532 bool HasInt256 = Subtarget->hasInt256();
7533 MachineFunction &MF = DAG.getMachineFunction();
7534 bool OptForSize = MF.getFunction()->getAttributes().
7535 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7537 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7539 if (V1IsUndef && V2IsUndef)
7540 return DAG.getUNDEF(VT);
7542 // When we create a shuffle node we put the UNDEF node to second operand,
7543 // but in some cases the first operand may be transformed to UNDEF.
7544 // In this case we should just commute the node.
7546 return CommuteVectorShuffle(SVOp, DAG);
7548 // Vector shuffle lowering takes 3 steps:
7550 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7551 // narrowing and commutation of operands should be handled.
7552 // 2) Matching of shuffles with known shuffle masks to x86 target specific
7554 // 3) Rewriting of unmatched masks into new generic shuffle operations,
7555 // so the shuffle can be broken into other shuffles and the legalizer can
7556 // try the lowering again.
7558 // The general idea is that no vector_shuffle operation should be left to
7559 // be matched during isel, all of them must be converted to a target specific
7562 // Normalize the input vectors. Here splats, zeroed vectors, profitable
7563 // narrowing and commutation of operands should be handled. The actual code
7564 // doesn't include all of those, work in progress...
7565 SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7566 if (NewOp.getNode())
7569 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7571 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7572 // unpckh_undef). Only use pshufd if speed is more important than size.
7573 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7574 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7575 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7576 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7578 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7579 V2IsUndef && MayFoldVectorLoad(V1))
7580 return getMOVDDup(Op, dl, V1, DAG);
7582 if (isMOVHLPS_v_undef_Mask(M, VT))
7583 return getMOVHighToLow(Op, dl, DAG);
7585 // Use to match splats
7586 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7587 (VT == MVT::v2f64 || VT == MVT::v2i64))
7588 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7590 if (isPSHUFDMask(M, VT)) {
7591 // The actual implementation will match the mask in the if above and then
7592 // during isel it can match several different instructions, not only pshufd
7593 // as its name says, sad but true, emulate the behavior for now...
7594 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7595 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7597 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7599 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7600 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7602 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7603 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7606 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7610 if (isPALIGNRMask(M, VT, Subtarget))
7611 return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7612 getShufflePALIGNRImmediate(SVOp),
7615 // Check if this can be converted into a logical shift.
7616 bool isLeft = false;
7619 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7620 if (isShift && ShVal.hasOneUse()) {
7621 // If the shifted value has multiple uses, it may be cheaper to use
7622 // v_set0 + movlhps or movhlps, etc.
7623 MVT EltVT = VT.getVectorElementType();
7624 ShAmt *= EltVT.getSizeInBits();
7625 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7628 if (isMOVLMask(M, VT)) {
7629 if (ISD::isBuildVectorAllZeros(V1.getNode()))
7630 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7631 if (!isMOVLPMask(M, VT)) {
7632 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7633 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7635 if (VT == MVT::v4i32 || VT == MVT::v4f32)
7636 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7640 // FIXME: fold these into legal mask.
7641 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7642 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7644 if (isMOVHLPSMask(M, VT))
7645 return getMOVHighToLow(Op, dl, DAG);
7647 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7648 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7650 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7651 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7653 if (isMOVLPMask(M, VT))
7654 return getMOVLP(Op, dl, DAG, HasSSE2);
7656 if (ShouldXformToMOVHLPS(M, VT) ||
7657 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7658 return CommuteVectorShuffle(SVOp, DAG);
7661 // No better options. Use a vshldq / vsrldq.
7662 MVT EltVT = VT.getVectorElementType();
7663 ShAmt *= EltVT.getSizeInBits();
7664 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7667 bool Commuted = false;
7668 // FIXME: This should also accept a bitcast of a splat? Be careful, not
7669 // 1,1,1,1 -> v8i16 though.
7670 V1IsSplat = isSplatVector(V1.getNode());
7671 V2IsSplat = isSplatVector(V2.getNode());
7673 // Canonicalize the splat or undef, if present, to be on the RHS.
7674 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7675 CommuteVectorShuffleMask(M, NumElems);
7677 std::swap(V1IsSplat, V2IsSplat);
7681 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7682 // Shuffling low element of v1 into undef, just return v1.
7685 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7686 // the instruction selector will not match, so get a canonical MOVL with
7687 // swapped operands to undo the commute.
7688 return getMOVL(DAG, dl, VT, V2, V1);
7691 if (isUNPCKLMask(M, VT, HasInt256))
7692 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7694 if (isUNPCKHMask(M, VT, HasInt256))
7695 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7698 // Normalize mask so all entries that point to V2 points to its first
7699 // element then try to match unpck{h|l} again. If match, return a
7700 // new vector_shuffle with the corrected mask.p
7701 SmallVector<int, 8> NewMask(M.begin(), M.end());
7702 NormalizeMask(NewMask, NumElems);
7703 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7704 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7705 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7706 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7710 // Commute is back and try unpck* again.
7711 // FIXME: this seems wrong.
7712 CommuteVectorShuffleMask(M, NumElems);
7714 std::swap(V1IsSplat, V2IsSplat);
7716 if (isUNPCKLMask(M, VT, HasInt256))
7717 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7719 if (isUNPCKHMask(M, VT, HasInt256))
7720 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7723 // Normalize the node to match x86 shuffle ops if needed
7724 if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
7725 return CommuteVectorShuffle(SVOp, DAG);
7727 // The checks below are all present in isShuffleMaskLegal, but they are
7728 // inlined here right now to enable us to directly emit target specific
7729 // nodes, and remove one by one until they don't return Op anymore.
7731 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7732 SVOp->getSplatIndex() == 0 && V2IsUndef) {
7733 if (VT == MVT::v2f64 || VT == MVT::v2i64)
7734 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7737 if (isPSHUFHWMask(M, VT, HasInt256))
7738 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7739 getShufflePSHUFHWImmediate(SVOp),
7742 if (isPSHUFLWMask(M, VT, HasInt256))
7743 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7744 getShufflePSHUFLWImmediate(SVOp),
7747 if (isSHUFPMask(M, VT))
7748 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7749 getShuffleSHUFImmediate(SVOp), DAG);
7751 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7752 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7753 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7754 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7756 //===--------------------------------------------------------------------===//
7757 // Generate target specific nodes for 128 or 256-bit shuffles only
7758 // supported in the AVX instruction set.
7761 // Handle VMOVDDUPY permutations
7762 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7763 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7765 // Handle VPERMILPS/D* permutations
7766 if (isVPERMILPMask(M, VT)) {
7767 if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
7768 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7769 getShuffleSHUFImmediate(SVOp), DAG);
7770 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7771 getShuffleSHUFImmediate(SVOp), DAG);
7774 // Handle VPERM2F128/VPERM2I128 permutations
7775 if (isVPERM2X128Mask(M, VT, HasFp256))
7776 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7777 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7779 SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7780 if (BlendOp.getNode())
7783 if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
7784 return getINSERTPS(SVOp, dl, DAG);
7787 if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
7788 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
7790 if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
7791 VT.is512BitVector()) {
7792 MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
7793 MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
7794 SmallVector<SDValue, 16> permclMask;
7795 for (unsigned i = 0; i != NumElems; ++i) {
7796 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
7799 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT,
7800 &permclMask[0], NumElems);
7802 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7803 return DAG.getNode(X86ISD::VPERMV, dl, VT,
7804 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7805 return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
7806 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
7809 //===--------------------------------------------------------------------===//
7810 // Since no target specific shuffle was selected for this generic one,
7811 // lower it into other known shuffles. FIXME: this isn't true yet, but
7812 // this is the plan.
7815 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7816 if (VT == MVT::v8i16) {
7817 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7818 if (NewOp.getNode())
7822 if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
7823 SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
7824 if (NewOp.getNode())
7828 if (VT == MVT::v16i8) {
7829 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
7830 if (NewOp.getNode())
7834 if (VT == MVT::v32i8) {
7835 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7836 if (NewOp.getNode())
7840 // Handle all 128-bit wide vectors with 4 elements, and match them with
7841 // several different shuffle types.
7842 if (NumElems == 4 && VT.is128BitVector())
7843 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7845 // Handle general 256-bit shuffles
7846 if (VT.is256BitVector())
7847 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7852 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7853 MVT VT = Op.getSimpleValueType();
7856 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
7859 if (VT.getSizeInBits() == 8) {
7860 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7861 Op.getOperand(0), Op.getOperand(1));
7862 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7863 DAG.getValueType(VT));
7864 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7867 if (VT.getSizeInBits() == 16) {
7868 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7869 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7871 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7872 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7873 DAG.getNode(ISD::BITCAST, dl,
7877 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7878 Op.getOperand(0), Op.getOperand(1));
7879 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7880 DAG.getValueType(VT));
7881 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7884 if (VT == MVT::f32) {
7885 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7886 // the result back to FR32 register. It's only worth matching if the
7887 // result has a single use which is a store or a bitcast to i32. And in
7888 // the case of a store, it's not worth it if the index is a constant 0,
7889 // because a MOVSSmr can be used instead, which is smaller and faster.
7890 if (!Op.hasOneUse())
7892 SDNode *User = *Op.getNode()->use_begin();
7893 if ((User->getOpcode() != ISD::STORE ||
7894 (isa<ConstantSDNode>(Op.getOperand(1)) &&
7895 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7896 (User->getOpcode() != ISD::BITCAST ||
7897 User->getValueType(0) != MVT::i32))
7899 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7900 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7903 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7906 if (VT == MVT::i32 || VT == MVT::i64) {
7907 // ExtractPS/pextrq works with constant index.
7908 if (isa<ConstantSDNode>(Op.getOperand(1)))
7914 /// Extract one bit from mask vector, like v16i1 or v8i1.
7915 /// AVX-512 feature.
7917 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
7918 SDValue Vec = Op.getOperand(0);
7920 MVT VecVT = Vec.getSimpleValueType();
7921 SDValue Idx = Op.getOperand(1);
7922 MVT EltVT = Op.getSimpleValueType();
7924 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
7926 // variable index can't be handled in mask registers,
7927 // extend vector to VR512
7928 if (!isa<ConstantSDNode>(Idx)) {
7929 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
7930 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
7931 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
7932 ExtVT.getVectorElementType(), Ext, Idx);
7933 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
7936 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7937 const TargetRegisterClass* rc = getRegClassFor(VecVT);
7938 unsigned MaxSift = rc->getSize()*8 - 1;
7939 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
7940 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
7941 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
7942 DAG.getConstant(MaxSift, MVT::i8));
7943 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
7944 DAG.getIntPtrConstant(0));
7948 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7949 SelectionDAG &DAG) const {
7951 SDValue Vec = Op.getOperand(0);
7952 MVT VecVT = Vec.getSimpleValueType();
7953 SDValue Idx = Op.getOperand(1);
7955 if (Op.getSimpleValueType() == MVT::i1)
7956 return ExtractBitFromMaskVector(Op, DAG);
7958 if (!isa<ConstantSDNode>(Idx)) {
7959 if (VecVT.is512BitVector() ||
7960 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
7961 VecVT.getVectorElementType().getSizeInBits() == 32)) {
7964 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
7965 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
7966 MaskEltVT.getSizeInBits());
7968 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
7969 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
7970 getZeroVector(MaskVT, Subtarget, DAG, dl),
7971 Idx, DAG.getConstant(0, getPointerTy()));
7972 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
7973 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
7974 Perm, DAG.getConstant(0, getPointerTy()));
7979 // If this is a 256-bit vector result, first extract the 128-bit vector and
7980 // then extract the element from the 128-bit vector.
7981 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
7983 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7984 // Get the 128-bit vector.
7985 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7986 MVT EltVT = VecVT.getVectorElementType();
7988 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
7990 //if (IdxVal >= NumElems/2)
7991 // IdxVal -= NumElems/2;
7992 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
7993 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7994 DAG.getConstant(IdxVal, MVT::i32));
7997 assert(VecVT.is128BitVector() && "Unexpected vector length");
7999 if (Subtarget->hasSSE41()) {
8000 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
8005 MVT VT = Op.getSimpleValueType();
8006 // TODO: handle v16i8.
8007 if (VT.getSizeInBits() == 16) {
8008 SDValue Vec = Op.getOperand(0);
8009 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8011 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8012 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8013 DAG.getNode(ISD::BITCAST, dl,
8016 // Transform it so it match pextrw which produces a 32-bit result.
8017 MVT EltVT = MVT::i32;
8018 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
8019 Op.getOperand(0), Op.getOperand(1));
8020 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
8021 DAG.getValueType(VT));
8022 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8025 if (VT.getSizeInBits() == 32) {
8026 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8030 // SHUFPS the element to the lowest double word, then movss.
8031 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
8032 MVT VVT = Op.getOperand(0).getSimpleValueType();
8033 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8034 DAG.getUNDEF(VVT), Mask);
8035 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8036 DAG.getIntPtrConstant(0));
8039 if (VT.getSizeInBits() == 64) {
8040 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
8041 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
8042 // to match extract_elt for f64.
8043 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8047 // UNPCKHPD the element to the lowest double word, then movsd.
8048 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
8049 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
8050 int Mask[2] = { 1, -1 };
8051 MVT VVT = Op.getOperand(0).getSimpleValueType();
8052 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8053 DAG.getUNDEF(VVT), Mask);
8054 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8055 DAG.getIntPtrConstant(0));
8061 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8062 MVT VT = Op.getSimpleValueType();
8063 MVT EltVT = VT.getVectorElementType();
8066 SDValue N0 = Op.getOperand(0);
8067 SDValue N1 = Op.getOperand(1);
8068 SDValue N2 = Op.getOperand(2);
8070 if (!VT.is128BitVector())
8073 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
8074 isa<ConstantSDNode>(N2)) {
8076 if (VT == MVT::v8i16)
8077 Opc = X86ISD::PINSRW;
8078 else if (VT == MVT::v16i8)
8079 Opc = X86ISD::PINSRB;
8081 Opc = X86ISD::PINSRB;
8083 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
8085 if (N1.getValueType() != MVT::i32)
8086 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8087 if (N2.getValueType() != MVT::i32)
8088 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8089 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
8092 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
8093 // Bits [7:6] of the constant are the source select. This will always be
8094 // zero here. The DAG Combiner may combine an extract_elt index into these
8095 // bits. For example (insert (extract, 3), 2) could be matched by putting
8096 // the '3' into bits [7:6] of X86ISD::INSERTPS.
8097 // Bits [5:4] of the constant are the destination select. This is the
8098 // value of the incoming immediate.
8099 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
8100 // combine either bitwise AND or insert of float 0.0 to set these bits.
8101 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
8102 // Create this as a scalar to vector..
8103 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
8104 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
8107 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
8108 // PINSR* works with constant index.
8114 /// Insert one bit to mask vector, like v16i1 or v8i1.
8115 /// AVX-512 feature.
8117 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
8119 SDValue Vec = Op.getOperand(0);
8120 SDValue Elt = Op.getOperand(1);
8121 SDValue Idx = Op.getOperand(2);
8122 MVT VecVT = Vec.getSimpleValueType();
8124 if (!isa<ConstantSDNode>(Idx)) {
8125 // Non constant index. Extend source and destination,
8126 // insert element and then truncate the result.
8127 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
8128 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
8129 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
8130 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
8131 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
8132 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
8135 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8136 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
8137 if (Vec.getOpcode() == ISD::UNDEF)
8138 return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8139 DAG.getConstant(IdxVal, MVT::i8));
8140 const TargetRegisterClass* rc = getRegClassFor(VecVT);
8141 unsigned MaxSift = rc->getSize()*8 - 1;
8142 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8143 DAG.getConstant(MaxSift, MVT::i8));
8144 EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
8145 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8146 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
8149 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
8150 MVT VT = Op.getSimpleValueType();
8151 MVT EltVT = VT.getVectorElementType();
8153 if (EltVT == MVT::i1)
8154 return InsertBitToMaskVector(Op, DAG);
8157 SDValue N0 = Op.getOperand(0);
8158 SDValue N1 = Op.getOperand(1);
8159 SDValue N2 = Op.getOperand(2);
8161 // If this is a 256-bit vector result, first extract the 128-bit vector,
8162 // insert the element into the extracted half and then place it back.
8163 if (VT.is256BitVector() || VT.is512BitVector()) {
8164 if (!isa<ConstantSDNode>(N2))
8167 // Get the desired 128-bit vector half.
8168 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
8169 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
8171 // Insert the element into the desired half.
8172 unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
8173 unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
8175 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
8176 DAG.getConstant(IdxIn128, MVT::i32));
8178 // Insert the changed part back to the 256-bit vector
8179 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
8182 if (Subtarget->hasSSE41())
8183 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
8185 if (EltVT == MVT::i8)
8188 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
8189 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
8190 // as its second argument.
8191 if (N1.getValueType() != MVT::i32)
8192 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8193 if (N2.getValueType() != MVT::i32)
8194 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8195 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
8200 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
8202 MVT OpVT = Op.getSimpleValueType();
8204 // If this is a 256-bit vector result, first insert into a 128-bit
8205 // vector and then insert into the 256-bit vector.
8206 if (!OpVT.is128BitVector()) {
8207 // Insert into a 128-bit vector.
8208 unsigned SizeFactor = OpVT.getSizeInBits()/128;
8209 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
8210 OpVT.getVectorNumElements() / SizeFactor);
8212 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
8214 // Insert the 128-bit vector.
8215 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
8218 if (OpVT == MVT::v1i64 &&
8219 Op.getOperand(0).getValueType() == MVT::i64)
8220 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
8222 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
8223 assert(OpVT.is128BitVector() && "Expected an SSE type!");
8224 return DAG.getNode(ISD::BITCAST, dl, OpVT,
8225 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
8228 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
8229 // a simple subregister reference or explicit instructions to grab
8230 // upper bits of a vector.
8231 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8232 SelectionDAG &DAG) {
8234 SDValue In = Op.getOperand(0);
8235 SDValue Idx = Op.getOperand(1);
8236 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8237 MVT ResVT = Op.getSimpleValueType();
8238 MVT InVT = In.getSimpleValueType();
8240 if (Subtarget->hasFp256()) {
8241 if (ResVT.is128BitVector() &&
8242 (InVT.is256BitVector() || InVT.is512BitVector()) &&
8243 isa<ConstantSDNode>(Idx)) {
8244 return Extract128BitVector(In, IdxVal, DAG, dl);
8246 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
8247 isa<ConstantSDNode>(Idx)) {
8248 return Extract256BitVector(In, IdxVal, DAG, dl);
8254 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
8255 // simple superregister reference or explicit instructions to insert
8256 // the upper bits of a vector.
8257 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8258 SelectionDAG &DAG) {
8259 if (Subtarget->hasFp256()) {
8260 SDLoc dl(Op.getNode());
8261 SDValue Vec = Op.getNode()->getOperand(0);
8262 SDValue SubVec = Op.getNode()->getOperand(1);
8263 SDValue Idx = Op.getNode()->getOperand(2);
8265 if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8266 Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8267 SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8268 isa<ConstantSDNode>(Idx)) {
8269 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8270 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8273 if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8274 SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8275 isa<ConstantSDNode>(Idx)) {
8276 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8277 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8283 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8284 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8285 // one of the above mentioned nodes. It has to be wrapped because otherwise
8286 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8287 // be used to form addressing mode. These wrapped nodes will be selected
8290 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8291 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8293 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8295 unsigned char OpFlag = 0;
8296 unsigned WrapperKind = X86ISD::Wrapper;
8297 CodeModel::Model M = getTargetMachine().getCodeModel();
8299 if (Subtarget->isPICStyleRIPRel() &&
8300 (M == CodeModel::Small || M == CodeModel::Kernel))
8301 WrapperKind = X86ISD::WrapperRIP;
8302 else if (Subtarget->isPICStyleGOT())
8303 OpFlag = X86II::MO_GOTOFF;
8304 else if (Subtarget->isPICStyleStubPIC())
8305 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8307 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8309 CP->getOffset(), OpFlag);
8311 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8312 // With PIC, the address is actually $g + Offset.
8314 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8315 DAG.getNode(X86ISD::GlobalBaseReg,
8316 SDLoc(), getPointerTy()),
8323 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8324 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8326 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8328 unsigned char OpFlag = 0;
8329 unsigned WrapperKind = X86ISD::Wrapper;
8330 CodeModel::Model M = getTargetMachine().getCodeModel();
8332 if (Subtarget->isPICStyleRIPRel() &&
8333 (M == CodeModel::Small || M == CodeModel::Kernel))
8334 WrapperKind = X86ISD::WrapperRIP;
8335 else if (Subtarget->isPICStyleGOT())
8336 OpFlag = X86II::MO_GOTOFF;
8337 else if (Subtarget->isPICStyleStubPIC())
8338 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8340 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8343 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8345 // With PIC, the address is actually $g + Offset.
8347 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8348 DAG.getNode(X86ISD::GlobalBaseReg,
8349 SDLoc(), getPointerTy()),
8356 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8357 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8359 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8361 unsigned char OpFlag = 0;
8362 unsigned WrapperKind = X86ISD::Wrapper;
8363 CodeModel::Model M = getTargetMachine().getCodeModel();
8365 if (Subtarget->isPICStyleRIPRel() &&
8366 (M == CodeModel::Small || M == CodeModel::Kernel)) {
8367 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8368 OpFlag = X86II::MO_GOTPCREL;
8369 WrapperKind = X86ISD::WrapperRIP;
8370 } else if (Subtarget->isPICStyleGOT()) {
8371 OpFlag = X86II::MO_GOT;
8372 } else if (Subtarget->isPICStyleStubPIC()) {
8373 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8374 } else if (Subtarget->isPICStyleStubNoDynamic()) {
8375 OpFlag = X86II::MO_DARWIN_NONLAZY;
8378 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8381 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8383 // With PIC, the address is actually $g + Offset.
8384 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
8385 !Subtarget->is64Bit()) {
8386 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8387 DAG.getNode(X86ISD::GlobalBaseReg,
8388 SDLoc(), getPointerTy()),
8392 // For symbols that require a load from a stub to get the address, emit the
8394 if (isGlobalStubReference(OpFlag))
8395 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8396 MachinePointerInfo::getGOT(), false, false, false, 0);
8402 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8403 // Create the TargetBlockAddressAddress node.
8404 unsigned char OpFlags =
8405 Subtarget->ClassifyBlockAddressReference();
8406 CodeModel::Model M = getTargetMachine().getCodeModel();
8407 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8408 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8410 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8413 if (Subtarget->isPICStyleRIPRel() &&
8414 (M == CodeModel::Small || M == CodeModel::Kernel))
8415 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8417 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8419 // With PIC, the address is actually $g + Offset.
8420 if (isGlobalRelativeToPICBase(OpFlags)) {
8421 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8422 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8430 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8431 int64_t Offset, SelectionDAG &DAG) const {
8432 // Create the TargetGlobalAddress node, folding in the constant
8433 // offset if it is legal.
8434 unsigned char OpFlags =
8435 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
8436 CodeModel::Model M = getTargetMachine().getCodeModel();
8438 if (OpFlags == X86II::MO_NO_FLAG &&
8439 X86::isOffsetSuitableForCodeModel(Offset, M)) {
8440 // A direct static reference to a global.
8441 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8444 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8447 if (Subtarget->isPICStyleRIPRel() &&
8448 (M == CodeModel::Small || M == CodeModel::Kernel))
8449 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8451 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8453 // With PIC, the address is actually $g + Offset.
8454 if (isGlobalRelativeToPICBase(OpFlags)) {
8455 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8456 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8460 // For globals that require a load from a stub to get the address, emit the
8462 if (isGlobalStubReference(OpFlags))
8463 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8464 MachinePointerInfo::getGOT(), false, false, false, 0);
8466 // If there was a non-zero offset that we didn't fold, create an explicit
8469 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8470 DAG.getConstant(Offset, getPointerTy()));
8476 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8477 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8478 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8479 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8483 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8484 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8485 unsigned char OperandFlags, bool LocalDynamic = false) {
8486 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8487 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8489 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8490 GA->getValueType(0),
8494 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8498 SDValue Ops[] = { Chain, TGA, *InFlag };
8499 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8501 SDValue Ops[] = { Chain, TGA };
8502 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8505 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8506 MFI->setAdjustsStack(true);
8508 SDValue Flag = Chain.getValue(1);
8509 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8512 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8514 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8517 SDLoc dl(GA); // ? function entry point might be better
8518 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8519 DAG.getNode(X86ISD::GlobalBaseReg,
8520 SDLoc(), PtrVT), InFlag);
8521 InFlag = Chain.getValue(1);
8523 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8526 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8528 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8530 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
8531 X86::RAX, X86II::MO_TLSGD);
8534 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8540 // Get the start address of the TLS block for this module.
8541 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8542 .getInfo<X86MachineFunctionInfo>();
8543 MFI->incNumLocalDynamicTLSAccesses();
8547 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
8548 X86II::MO_TLSLD, /*LocalDynamic=*/true);
8551 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8552 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8553 InFlag = Chain.getValue(1);
8554 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8555 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8558 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8562 unsigned char OperandFlags = X86II::MO_DTPOFF;
8563 unsigned WrapperKind = X86ISD::Wrapper;
8564 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8565 GA->getValueType(0),
8566 GA->getOffset(), OperandFlags);
8567 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8569 // Add x@dtpoff with the base.
8570 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8573 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8574 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8575 const EVT PtrVT, TLSModel::Model model,
8576 bool is64Bit, bool isPIC) {
8579 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8580 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8581 is64Bit ? 257 : 256));
8583 SDValue ThreadPointer =
8584 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
8585 MachinePointerInfo(Ptr), false, false, false, 0);
8587 unsigned char OperandFlags = 0;
8588 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
8590 unsigned WrapperKind = X86ISD::Wrapper;
8591 if (model == TLSModel::LocalExec) {
8592 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8593 } else if (model == TLSModel::InitialExec) {
8595 OperandFlags = X86II::MO_GOTTPOFF;
8596 WrapperKind = X86ISD::WrapperRIP;
8598 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8601 llvm_unreachable("Unexpected model");
8604 // emit "addl x@ntpoff,%eax" (local exec)
8605 // or "addl x@indntpoff,%eax" (initial exec)
8606 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8608 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
8609 GA->getOffset(), OperandFlags);
8610 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8612 if (model == TLSModel::InitialExec) {
8613 if (isPIC && !is64Bit) {
8614 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8615 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8619 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8620 MachinePointerInfo::getGOT(), false, false, false, 0);
8623 // The address of the thread local variable is the add of the thread
8624 // pointer with the offset of the variable.
8625 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8629 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8631 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8632 const GlobalValue *GV = GA->getGlobal();
8634 if (Subtarget->isTargetELF()) {
8635 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8638 case TLSModel::GeneralDynamic:
8639 if (Subtarget->is64Bit())
8640 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8641 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8642 case TLSModel::LocalDynamic:
8643 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8644 Subtarget->is64Bit());
8645 case TLSModel::InitialExec:
8646 case TLSModel::LocalExec:
8647 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8648 Subtarget->is64Bit(),
8649 getTargetMachine().getRelocationModel() == Reloc::PIC_);
8651 llvm_unreachable("Unknown TLS model.");
8654 if (Subtarget->isTargetDarwin()) {
8655 // Darwin only has one model of TLS. Lower to that.
8656 unsigned char OpFlag = 0;
8657 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8658 X86ISD::WrapperRIP : X86ISD::Wrapper;
8660 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8662 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8663 !Subtarget->is64Bit();
8665 OpFlag = X86II::MO_TLVP_PIC_BASE;
8667 OpFlag = X86II::MO_TLVP;
8669 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8670 GA->getValueType(0),
8671 GA->getOffset(), OpFlag);
8672 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8674 // With PIC32, the address is actually $g + Offset.
8676 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8677 DAG.getNode(X86ISD::GlobalBaseReg,
8678 SDLoc(), getPointerTy()),
8681 // Lowering the machine isd will make sure everything is in the right
8683 SDValue Chain = DAG.getEntryNode();
8684 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8685 SDValue Args[] = { Chain, Offset };
8686 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
8688 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8689 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8690 MFI->setAdjustsStack(true);
8692 // And our return value (tls address) is in the standard call return value
8694 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8695 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8699 if (Subtarget->isTargetKnownWindowsMSVC() ||
8700 Subtarget->isTargetWindowsGNU()) {
8701 // Just use the implicit TLS architecture
8702 // Need to generate someting similar to:
8703 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8705 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
8706 // mov rcx, qword [rdx+rcx*8]
8707 // mov eax, .tls$:tlsvar
8708 // [rax+rcx] contains the address
8709 // Windows 64bit: gs:0x58
8710 // Windows 32bit: fs:__tls_array
8712 // If GV is an alias then use the aliasee for determining
8713 // thread-localness.
8714 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
8715 GV = GA->getAliasedGlobal();
8717 SDValue Chain = DAG.getEntryNode();
8719 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8720 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8721 // use its literal value of 0x2C.
8722 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8723 ? Type::getInt8PtrTy(*DAG.getContext(),
8725 : Type::getInt32PtrTy(*DAG.getContext(),
8729 Subtarget->is64Bit()
8730 ? DAG.getIntPtrConstant(0x58)
8731 : (Subtarget->isTargetWindowsGNU()
8732 ? DAG.getIntPtrConstant(0x2C)
8733 : DAG.getExternalSymbol("_tls_array", getPointerTy()));
8735 SDValue ThreadPointer =
8736 DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8737 MachinePointerInfo(Ptr), false, false, false, 0);
8739 // Load the _tls_index variable
8740 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8741 if (Subtarget->is64Bit())
8742 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8743 IDX, MachinePointerInfo(), MVT::i32,
8746 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
8747 false, false, false, 0);
8749 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
8751 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
8753 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
8754 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
8755 false, false, false, 0);
8757 // Get the offset of start of .tls section
8758 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8759 GA->getValueType(0),
8760 GA->getOffset(), X86II::MO_SECREL);
8761 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
8763 // The address of the thread local variable is the add of the thread
8764 // pointer with the offset of the variable.
8765 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
8768 llvm_unreachable("TLS not implemented for this target.");
8771 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
8772 /// and take a 2 x i32 value to shift plus a shift amount.
8773 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
8774 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
8775 MVT VT = Op.getSimpleValueType();
8776 unsigned VTBits = VT.getSizeInBits();
8778 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
8779 SDValue ShOpLo = Op.getOperand(0);
8780 SDValue ShOpHi = Op.getOperand(1);
8781 SDValue ShAmt = Op.getOperand(2);
8782 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
8783 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
8785 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8786 DAG.getConstant(VTBits - 1, MVT::i8));
8787 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
8788 DAG.getConstant(VTBits - 1, MVT::i8))
8789 : DAG.getConstant(0, VT);
8792 if (Op.getOpcode() == ISD::SHL_PARTS) {
8793 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
8794 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
8796 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
8797 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
8800 // If the shift amount is larger or equal than the width of a part we can't
8801 // rely on the results of shld/shrd. Insert a test and select the appropriate
8802 // values for large shift amounts.
8803 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8804 DAG.getConstant(VTBits, MVT::i8));
8805 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8806 AndNode, DAG.getConstant(0, MVT::i8));
8809 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8810 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
8811 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
8813 if (Op.getOpcode() == ISD::SHL_PARTS) {
8814 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8815 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8817 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8818 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8821 SDValue Ops[2] = { Lo, Hi };
8822 return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
8825 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
8826 SelectionDAG &DAG) const {
8827 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
8829 if (SrcVT.isVector())
8832 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
8833 "Unknown SINT_TO_FP to lower!");
8835 // These are really Legal; return the operand so the caller accepts it as
8837 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
8839 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
8840 Subtarget->is64Bit()) {
8845 unsigned Size = SrcVT.getSizeInBits()/8;
8846 MachineFunction &MF = DAG.getMachineFunction();
8847 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8848 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8849 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8851 MachinePointerInfo::getFixedStack(SSFI),
8853 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8856 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8858 SelectionDAG &DAG) const {
8862 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8864 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8866 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8868 unsigned ByteSize = SrcVT.getSizeInBits()/8;
8870 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8871 MachineMemOperand *MMO;
8873 int SSFI = FI->getIndex();
8875 DAG.getMachineFunction()
8876 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8877 MachineMemOperand::MOLoad, ByteSize, ByteSize);
8879 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8880 StackSlot = StackSlot.getOperand(1);
8882 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8883 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8885 Tys, Ops, array_lengthof(Ops),
8889 Chain = Result.getValue(1);
8890 SDValue InFlag = Result.getValue(2);
8892 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8893 // shouldn't be necessary except that RFP cannot be live across
8894 // multiple blocks. When stackifier is fixed, they can be uncoupled.
8895 MachineFunction &MF = DAG.getMachineFunction();
8896 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8897 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8898 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8899 Tys = DAG.getVTList(MVT::Other);
8901 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8903 MachineMemOperand *MMO =
8904 DAG.getMachineFunction()
8905 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8906 MachineMemOperand::MOStore, SSFISize, SSFISize);
8908 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8909 Ops, array_lengthof(Ops),
8910 Op.getValueType(), MMO);
8911 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8912 MachinePointerInfo::getFixedStack(SSFI),
8913 false, false, false, 0);
8919 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8920 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8921 SelectionDAG &DAG) const {
8922 // This algorithm is not obvious. Here it is what we're trying to output:
8925 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8926 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8930 pshufd $0x4e, %xmm0, %xmm1
8936 LLVMContext *Context = DAG.getContext();
8938 // Build some magic constants.
8939 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8940 Constant *C0 = ConstantDataVector::get(*Context, CV0);
8941 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8943 SmallVector<Constant*,2> CV1;
8945 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8946 APInt(64, 0x4330000000000000ULL))));
8948 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8949 APInt(64, 0x4530000000000000ULL))));
8950 Constant *C1 = ConstantVector::get(CV1);
8951 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8953 // Load the 64-bit value into an XMM register.
8954 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8956 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8957 MachinePointerInfo::getConstantPool(),
8958 false, false, false, 16);
8959 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8960 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8963 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8964 MachinePointerInfo::getConstantPool(),
8965 false, false, false, 16);
8966 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8967 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8970 if (Subtarget->hasSSE3()) {
8971 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8972 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8974 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8975 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8977 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8978 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8982 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8983 DAG.getIntPtrConstant(0));
8986 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8987 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8988 SelectionDAG &DAG) const {
8990 // FP constant to bias correct the final result.
8991 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8994 // Load the 32-bit value into an XMM register.
8995 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8998 // Zero out the upper parts of the register.
8999 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
9001 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9002 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
9003 DAG.getIntPtrConstant(0));
9005 // Or the load with the bias.
9006 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
9007 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9008 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9010 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9011 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9012 MVT::v2f64, Bias)));
9013 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9014 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
9015 DAG.getIntPtrConstant(0));
9017 // Subtract the bias.
9018 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
9020 // Handle final rounding.
9021 EVT DestVT = Op.getValueType();
9023 if (DestVT.bitsLT(MVT::f64))
9024 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
9025 DAG.getIntPtrConstant(0));
9026 if (DestVT.bitsGT(MVT::f64))
9027 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
9029 // Handle final rounding.
9033 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
9034 SelectionDAG &DAG) const {
9035 SDValue N0 = Op.getOperand(0);
9036 MVT SVT = N0.getSimpleValueType();
9039 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
9040 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
9041 "Custom UINT_TO_FP is not supported!");
9043 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
9044 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
9045 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
9048 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
9049 SelectionDAG &DAG) const {
9050 SDValue N0 = Op.getOperand(0);
9053 if (Op.getValueType().isVector())
9054 return lowerUINT_TO_FP_vec(Op, DAG);
9056 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
9057 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
9058 // the optimization here.
9059 if (DAG.SignBitIsZero(N0))
9060 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
9062 MVT SrcVT = N0.getSimpleValueType();
9063 MVT DstVT = Op.getSimpleValueType();
9064 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
9065 return LowerUINT_TO_FP_i64(Op, DAG);
9066 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
9067 return LowerUINT_TO_FP_i32(Op, DAG);
9068 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
9071 // Make a 64-bit buffer, and use it to build an FILD.
9072 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
9073 if (SrcVT == MVT::i32) {
9074 SDValue WordOff = DAG.getConstant(4, getPointerTy());
9075 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
9076 getPointerTy(), StackSlot, WordOff);
9077 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9078 StackSlot, MachinePointerInfo(),
9080 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
9081 OffsetSlot, MachinePointerInfo(),
9083 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
9087 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
9088 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9089 StackSlot, MachinePointerInfo(),
9091 // For i64 source, we need to add the appropriate power of 2 if the input
9092 // was negative. This is the same as the optimization in
9093 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
9094 // we must be careful to do the computation in x87 extended precision, not
9095 // in SSE. (The generic code can't know it's OK to do this, or how to.)
9096 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
9097 MachineMemOperand *MMO =
9098 DAG.getMachineFunction()
9099 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9100 MachineMemOperand::MOLoad, 8, 8);
9102 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
9103 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
9104 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
9105 array_lengthof(Ops), MVT::i64, MMO);
9107 APInt FF(32, 0x5F800000ULL);
9109 // Check whether the sign bit is set.
9110 SDValue SignSet = DAG.getSetCC(dl,
9111 getSetCCResultType(*DAG.getContext(), MVT::i64),
9112 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
9115 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
9116 SDValue FudgePtr = DAG.getConstantPool(
9117 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
9120 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
9121 SDValue Zero = DAG.getIntPtrConstant(0);
9122 SDValue Four = DAG.getIntPtrConstant(4);
9123 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
9125 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
9127 // Load the value out, extending it from f32 to f80.
9128 // FIXME: Avoid the extend by constructing the right constant pool?
9129 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
9130 FudgePtr, MachinePointerInfo::getConstantPool(),
9131 MVT::f32, false, false, 4);
9132 // Extend everything to 80 bits to force it to be done on x87.
9133 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
9134 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
9137 std::pair<SDValue,SDValue>
9138 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
9139 bool IsSigned, bool IsReplace) const {
9142 EVT DstTy = Op.getValueType();
9144 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
9145 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
9149 assert(DstTy.getSimpleVT() <= MVT::i64 &&
9150 DstTy.getSimpleVT() >= MVT::i16 &&
9151 "Unknown FP_TO_INT to lower!");
9153 // These are really Legal.
9154 if (DstTy == MVT::i32 &&
9155 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9156 return std::make_pair(SDValue(), SDValue());
9157 if (Subtarget->is64Bit() &&
9158 DstTy == MVT::i64 &&
9159 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9160 return std::make_pair(SDValue(), SDValue());
9162 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
9163 // stack slot, or into the FTOL runtime function.
9164 MachineFunction &MF = DAG.getMachineFunction();
9165 unsigned MemSize = DstTy.getSizeInBits()/8;
9166 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9167 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9170 if (!IsSigned && isIntegerTypeFTOL(DstTy))
9171 Opc = X86ISD::WIN_FTOL;
9173 switch (DstTy.getSimpleVT().SimpleTy) {
9174 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
9175 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
9176 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
9177 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
9180 SDValue Chain = DAG.getEntryNode();
9181 SDValue Value = Op.getOperand(0);
9182 EVT TheVT = Op.getOperand(0).getValueType();
9183 // FIXME This causes a redundant load/store if the SSE-class value is already
9184 // in memory, such as if it is on the callstack.
9185 if (isScalarFPTypeInSSEReg(TheVT)) {
9186 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
9187 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
9188 MachinePointerInfo::getFixedStack(SSFI),
9190 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
9192 Chain, StackSlot, DAG.getValueType(TheVT)
9195 MachineMemOperand *MMO =
9196 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9197 MachineMemOperand::MOLoad, MemSize, MemSize);
9198 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops,
9199 array_lengthof(Ops), DstTy, MMO);
9200 Chain = Value.getValue(1);
9201 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9202 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9205 MachineMemOperand *MMO =
9206 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9207 MachineMemOperand::MOStore, MemSize, MemSize);
9209 if (Opc != X86ISD::WIN_FTOL) {
9210 // Build the FP_TO_INT*_IN_MEM
9211 SDValue Ops[] = { Chain, Value, StackSlot };
9212 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
9213 Ops, array_lengthof(Ops), DstTy,
9215 return std::make_pair(FIST, StackSlot);
9217 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
9218 DAG.getVTList(MVT::Other, MVT::Glue),
9220 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
9221 MVT::i32, ftol.getValue(1));
9222 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
9223 MVT::i32, eax.getValue(2));
9224 SDValue Ops[] = { eax, edx };
9225 SDValue pair = IsReplace
9226 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, array_lengthof(Ops))
9227 : DAG.getMergeValues(Ops, array_lengthof(Ops), DL);
9228 return std::make_pair(pair, SDValue());
9232 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
9233 const X86Subtarget *Subtarget) {
9234 MVT VT = Op->getSimpleValueType(0);
9235 SDValue In = Op->getOperand(0);
9236 MVT InVT = In.getSimpleValueType();
9239 // Optimize vectors in AVX mode:
9242 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
9243 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
9244 // Concat upper and lower parts.
9247 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
9248 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
9249 // Concat upper and lower parts.
9252 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
9253 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
9254 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
9257 if (Subtarget->hasInt256())
9258 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
9260 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
9261 SDValue Undef = DAG.getUNDEF(InVT);
9262 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9263 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9264 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9266 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9267 VT.getVectorNumElements()/2);
9269 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9270 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9272 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9275 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9276 SelectionDAG &DAG) {
9277 MVT VT = Op->getSimpleValueType(0);
9278 SDValue In = Op->getOperand(0);
9279 MVT InVT = In.getSimpleValueType();
9281 unsigned int NumElts = VT.getVectorNumElements();
9282 if (NumElts != 8 && NumElts != 16)
9285 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9286 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9288 EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9289 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9290 // Now we have only mask extension
9291 assert(InVT.getVectorElementType() == MVT::i1);
9292 SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9293 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9294 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9295 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9296 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9297 MachinePointerInfo::getConstantPool(),
9298 false, false, false, Alignment);
9300 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9301 if (VT.is512BitVector())
9303 return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9306 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9307 SelectionDAG &DAG) {
9308 if (Subtarget->hasFp256()) {
9309 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9317 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9318 SelectionDAG &DAG) {
9320 MVT VT = Op.getSimpleValueType();
9321 SDValue In = Op.getOperand(0);
9322 MVT SVT = In.getSimpleValueType();
9324 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9325 return LowerZERO_EXTEND_AVX512(Op, DAG);
9327 if (Subtarget->hasFp256()) {
9328 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9333 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9334 VT.getVectorNumElements() != SVT.getVectorNumElements());
9338 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9340 MVT VT = Op.getSimpleValueType();
9341 SDValue In = Op.getOperand(0);
9342 MVT InVT = In.getSimpleValueType();
9344 if (VT == MVT::i1) {
9345 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9346 "Invalid scalar TRUNCATE operation");
9347 if (InVT == MVT::i32)
9349 if (InVT.getSizeInBits() == 64)
9350 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9351 else if (InVT.getSizeInBits() < 32)
9352 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9353 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
9355 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9356 "Invalid TRUNCATE operation");
9358 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9359 if (VT.getVectorElementType().getSizeInBits() >=8)
9360 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9362 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9363 unsigned NumElts = InVT.getVectorNumElements();
9364 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9365 if (InVT.getSizeInBits() < 512) {
9366 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9367 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9371 SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9372 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9373 SDValue CP = DAG.getConstantPool(C, getPointerTy());
9374 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9375 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9376 MachinePointerInfo::getConstantPool(),
9377 false, false, false, Alignment);
9378 SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9379 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9380 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9383 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9384 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9385 if (Subtarget->hasInt256()) {
9386 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9387 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9388 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9390 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9391 DAG.getIntPtrConstant(0));
9394 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9395 DAG.getIntPtrConstant(0));
9396 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9397 DAG.getIntPtrConstant(2));
9398 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9399 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9400 static const int ShufMask[] = {0, 2, 4, 6};
9401 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
9404 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9405 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9406 if (Subtarget->hasInt256()) {
9407 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9409 SmallVector<SDValue,32> pshufbMask;
9410 for (unsigned i = 0; i < 2; ++i) {
9411 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9412 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9413 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9414 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9415 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9416 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9417 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9418 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9419 for (unsigned j = 0; j < 8; ++j)
9420 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9422 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
9423 &pshufbMask[0], 32);
9424 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9425 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9427 static const int ShufMask[] = {0, 2, -1, -1};
9428 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
9430 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9431 DAG.getIntPtrConstant(0));
9432 return DAG.getNode(ISD::BITCAST, DL, VT, In);
9435 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9436 DAG.getIntPtrConstant(0));
9438 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9439 DAG.getIntPtrConstant(4));
9441 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9442 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9445 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
9446 -1, -1, -1, -1, -1, -1, -1, -1};
9448 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9449 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9450 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9452 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9453 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9455 // The MOVLHPS Mask:
9456 static const int ShufMask2[] = {0, 1, 4, 5};
9457 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9458 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9461 // Handle truncation of V256 to V128 using shuffles.
9462 if (!VT.is128BitVector() || !InVT.is256BitVector())
9465 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9467 unsigned NumElems = VT.getVectorNumElements();
9468 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
9470 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9471 // Prepare truncation shuffle mask
9472 for (unsigned i = 0; i != NumElems; ++i)
9474 SDValue V = DAG.getVectorShuffle(NVT, DL,
9475 DAG.getNode(ISD::BITCAST, DL, NVT, In),
9476 DAG.getUNDEF(NVT), &MaskVec[0]);
9477 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9478 DAG.getIntPtrConstant(0));
9481 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9482 SelectionDAG &DAG) const {
9483 assert(!Op.getSimpleValueType().isVector());
9485 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9486 /*IsSigned=*/ true, /*IsReplace=*/ false);
9487 SDValue FIST = Vals.first, StackSlot = Vals.second;
9488 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9489 if (!FIST.getNode()) return Op;
9491 if (StackSlot.getNode())
9493 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9494 FIST, StackSlot, MachinePointerInfo(),
9495 false, false, false, 0);
9497 // The node is the result.
9501 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9502 SelectionDAG &DAG) const {
9503 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9504 /*IsSigned=*/ false, /*IsReplace=*/ false);
9505 SDValue FIST = Vals.first, StackSlot = Vals.second;
9506 assert(FIST.getNode() && "Unexpected failure");
9508 if (StackSlot.getNode())
9510 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9511 FIST, StackSlot, MachinePointerInfo(),
9512 false, false, false, 0);
9514 // The node is the result.
9518 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9520 MVT VT = Op.getSimpleValueType();
9521 SDValue In = Op.getOperand(0);
9522 MVT SVT = In.getSimpleValueType();
9524 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9526 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9527 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9528 In, DAG.getUNDEF(SVT)));
9531 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
9532 LLVMContext *Context = DAG.getContext();
9534 MVT VT = Op.getSimpleValueType();
9536 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9537 if (VT.isVector()) {
9538 EltVT = VT.getVectorElementType();
9539 NumElts = VT.getVectorNumElements();
9542 if (EltVT == MVT::f64)
9543 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9544 APInt(64, ~(1ULL << 63))));
9546 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9547 APInt(32, ~(1U << 31))));
9548 C = ConstantVector::getSplat(NumElts, C);
9549 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9550 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9551 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9552 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9553 MachinePointerInfo::getConstantPool(),
9554 false, false, false, Alignment);
9555 if (VT.isVector()) {
9556 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9557 return DAG.getNode(ISD::BITCAST, dl, VT,
9558 DAG.getNode(ISD::AND, dl, ANDVT,
9559 DAG.getNode(ISD::BITCAST, dl, ANDVT,
9561 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9563 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9566 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
9567 LLVMContext *Context = DAG.getContext();
9569 MVT VT = Op.getSimpleValueType();
9571 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9572 if (VT.isVector()) {
9573 EltVT = VT.getVectorElementType();
9574 NumElts = VT.getVectorNumElements();
9577 if (EltVT == MVT::f64)
9578 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9579 APInt(64, 1ULL << 63)));
9581 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9582 APInt(32, 1U << 31)));
9583 C = ConstantVector::getSplat(NumElts, C);
9584 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9585 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9586 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9587 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9588 MachinePointerInfo::getConstantPool(),
9589 false, false, false, Alignment);
9590 if (VT.isVector()) {
9591 MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
9592 return DAG.getNode(ISD::BITCAST, dl, VT,
9593 DAG.getNode(ISD::XOR, dl, XORVT,
9594 DAG.getNode(ISD::BITCAST, dl, XORVT,
9596 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9599 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9602 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
9603 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9604 LLVMContext *Context = DAG.getContext();
9605 SDValue Op0 = Op.getOperand(0);
9606 SDValue Op1 = Op.getOperand(1);
9608 MVT VT = Op.getSimpleValueType();
9609 MVT SrcVT = Op1.getSimpleValueType();
9611 // If second operand is smaller, extend it first.
9612 if (SrcVT.bitsLT(VT)) {
9613 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9616 // And if it is bigger, shrink it first.
9617 if (SrcVT.bitsGT(VT)) {
9618 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9622 // At this point the operands and the result should have the same
9623 // type, and that won't be f80 since that is not custom lowered.
9625 // First get the sign bit of second operand.
9626 SmallVector<Constant*,4> CV;
9627 if (SrcVT == MVT::f64) {
9628 const fltSemantics &Sem = APFloat::IEEEdouble;
9629 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9630 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9632 const fltSemantics &Sem = APFloat::IEEEsingle;
9633 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9634 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9635 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9636 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9638 Constant *C = ConstantVector::get(CV);
9639 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9640 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9641 MachinePointerInfo::getConstantPool(),
9642 false, false, false, 16);
9643 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9645 // Shift sign bit right or left if the two operands have different types.
9646 if (SrcVT.bitsGT(VT)) {
9647 // Op0 is MVT::f32, Op1 is MVT::f64.
9648 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9649 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9650 DAG.getConstant(32, MVT::i32));
9651 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9652 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9653 DAG.getIntPtrConstant(0));
9656 // Clear first operand sign bit.
9658 if (VT == MVT::f64) {
9659 const fltSemantics &Sem = APFloat::IEEEdouble;
9660 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9661 APInt(64, ~(1ULL << 63)))));
9662 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9664 const fltSemantics &Sem = APFloat::IEEEsingle;
9665 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9666 APInt(32, ~(1U << 31)))));
9667 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9668 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9669 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9671 C = ConstantVector::get(CV);
9672 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9673 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9674 MachinePointerInfo::getConstantPool(),
9675 false, false, false, 16);
9676 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9678 // Or the value with the sign bit.
9679 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9682 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9683 SDValue N0 = Op.getOperand(0);
9685 MVT VT = Op.getSimpleValueType();
9687 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9688 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9689 DAG.getConstant(1, VT));
9690 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9693 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9695 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
9696 SelectionDAG &DAG) {
9697 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9699 if (!Subtarget->hasSSE41())
9702 if (!Op->hasOneUse())
9705 SDNode *N = Op.getNode();
9708 SmallVector<SDValue, 8> Opnds;
9709 DenseMap<SDValue, unsigned> VecInMap;
9710 SmallVector<SDValue, 8> VecIns;
9711 EVT VT = MVT::Other;
9713 // Recognize a special case where a vector is casted into wide integer to
9715 Opnds.push_back(N->getOperand(0));
9716 Opnds.push_back(N->getOperand(1));
9718 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9719 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9720 // BFS traverse all OR'd operands.
9721 if (I->getOpcode() == ISD::OR) {
9722 Opnds.push_back(I->getOperand(0));
9723 Opnds.push_back(I->getOperand(1));
9724 // Re-evaluate the number of nodes to be traversed.
9725 e += 2; // 2 more nodes (LHS and RHS) are pushed.
9729 // Quit if a non-EXTRACT_VECTOR_ELT
9730 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9733 // Quit if without a constant index.
9734 SDValue Idx = I->getOperand(1);
9735 if (!isa<ConstantSDNode>(Idx))
9738 SDValue ExtractedFromVec = I->getOperand(0);
9739 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9740 if (M == VecInMap.end()) {
9741 VT = ExtractedFromVec.getValueType();
9742 // Quit if not 128/256-bit vector.
9743 if (!VT.is128BitVector() && !VT.is256BitVector())
9745 // Quit if not the same type.
9746 if (VecInMap.begin() != VecInMap.end() &&
9747 VT != VecInMap.begin()->first.getValueType())
9749 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9750 VecIns.push_back(ExtractedFromVec);
9752 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9755 assert((VT.is128BitVector() || VT.is256BitVector()) &&
9756 "Not extracted from 128-/256-bit vector.");
9758 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
9760 for (DenseMap<SDValue, unsigned>::const_iterator
9761 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
9762 // Quit if not all elements are used.
9763 if (I->second != FullMask)
9767 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9769 // Cast all vectors into TestVT for PTEST.
9770 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
9771 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
9773 // If more than one full vectors are evaluated, OR them first before PTEST.
9774 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
9775 // Each iteration will OR 2 nodes and append the result until there is only
9776 // 1 node left, i.e. the final OR'd value of all vectors.
9777 SDValue LHS = VecIns[Slot];
9778 SDValue RHS = VecIns[Slot + 1];
9779 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
9782 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
9783 VecIns.back(), VecIns.back());
9786 /// \brief return true if \c Op has a use that doesn't just read flags.
9787 static bool hasNonFlagsUse(SDValue Op) {
9788 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
9791 unsigned UOpNo = UI.getOperandNo();
9792 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9793 // Look pass truncate.
9794 UOpNo = User->use_begin().getOperandNo();
9795 User = *User->use_begin();
9798 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
9799 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
9805 /// Emit nodes that will be selected as "test Op0,Op0", or something
9807 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
9808 SelectionDAG &DAG) const {
9809 if (Op.getValueType() == MVT::i1)
9810 // KORTEST instruction should be selected
9811 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9812 DAG.getConstant(0, Op.getValueType()));
9814 // CF and OF aren't always set the way we want. Determine which
9815 // of these we need.
9816 bool NeedCF = false;
9817 bool NeedOF = false;
9820 case X86::COND_A: case X86::COND_AE:
9821 case X86::COND_B: case X86::COND_BE:
9824 case X86::COND_G: case X86::COND_GE:
9825 case X86::COND_L: case X86::COND_LE:
9826 case X86::COND_O: case X86::COND_NO:
9830 // See if we can use the EFLAGS value from the operand instead of
9831 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
9832 // we prove that the arithmetic won't overflow, we can't use OF or CF.
9833 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
9834 // Emit a CMP with 0, which is the TEST pattern.
9835 //if (Op.getValueType() == MVT::i1)
9836 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
9837 // DAG.getConstant(0, MVT::i1));
9838 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9839 DAG.getConstant(0, Op.getValueType()));
9841 unsigned Opcode = 0;
9842 unsigned NumOperands = 0;
9844 // Truncate operations may prevent the merge of the SETCC instruction
9845 // and the arithmetic instruction before it. Attempt to truncate the operands
9846 // of the arithmetic instruction and use a reduced bit-width instruction.
9847 bool NeedTruncation = false;
9848 SDValue ArithOp = Op;
9849 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
9850 SDValue Arith = Op->getOperand(0);
9851 // Both the trunc and the arithmetic op need to have one user each.
9852 if (Arith->hasOneUse())
9853 switch (Arith.getOpcode()) {
9860 NeedTruncation = true;
9866 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
9867 // which may be the result of a CAST. We use the variable 'Op', which is the
9868 // non-casted variable when we check for possible users.
9869 switch (ArithOp.getOpcode()) {
9871 // Due to an isel shortcoming, be conservative if this add is likely to be
9872 // selected as part of a load-modify-store instruction. When the root node
9873 // in a match is a store, isel doesn't know how to remap non-chain non-flag
9874 // uses of other nodes in the match, such as the ADD in this case. This
9875 // leads to the ADD being left around and reselected, with the result being
9876 // two adds in the output. Alas, even if none our users are stores, that
9877 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
9878 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
9879 // climbing the DAG back to the root, and it doesn't seem to be worth the
9881 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9882 UE = Op.getNode()->use_end(); UI != UE; ++UI)
9883 if (UI->getOpcode() != ISD::CopyToReg &&
9884 UI->getOpcode() != ISD::SETCC &&
9885 UI->getOpcode() != ISD::STORE)
9888 if (ConstantSDNode *C =
9889 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
9890 // An add of one will be selected as an INC.
9891 if (C->getAPIntValue() == 1) {
9892 Opcode = X86ISD::INC;
9897 // An add of negative one (subtract of one) will be selected as a DEC.
9898 if (C->getAPIntValue().isAllOnesValue()) {
9899 Opcode = X86ISD::DEC;
9905 // Otherwise use a regular EFLAGS-setting add.
9906 Opcode = X86ISD::ADD;
9911 // If we have a constant logical shift that's only used in a comparison
9912 // against zero turn it into an equivalent AND. This allows turning it into
9913 // a TEST instruction later.
9914 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) &&
9915 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
9916 EVT VT = Op.getValueType();
9917 unsigned BitWidth = VT.getSizeInBits();
9918 unsigned ShAmt = Op->getConstantOperandVal(1);
9919 if (ShAmt >= BitWidth) // Avoid undefined shifts.
9921 APInt Mask = ArithOp.getOpcode() == ISD::SRL
9922 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
9923 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
9924 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
9926 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
9927 DAG.getConstant(Mask, VT));
9928 DAG.ReplaceAllUsesWith(Op, New);
9934 // If the primary and result isn't used, don't bother using X86ISD::AND,
9935 // because a TEST instruction will be better.
9936 if (!hasNonFlagsUse(Op))
9942 // Due to the ISEL shortcoming noted above, be conservative if this op is
9943 // likely to be selected as part of a load-modify-store instruction.
9944 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9945 UE = Op.getNode()->use_end(); UI != UE; ++UI)
9946 if (UI->getOpcode() == ISD::STORE)
9949 // Otherwise use a regular EFLAGS-setting instruction.
9950 switch (ArithOp.getOpcode()) {
9951 default: llvm_unreachable("unexpected operator!");
9952 case ISD::SUB: Opcode = X86ISD::SUB; break;
9953 case ISD::XOR: Opcode = X86ISD::XOR; break;
9954 case ISD::AND: Opcode = X86ISD::AND; break;
9956 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9957 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
9958 if (EFLAGS.getNode())
9961 Opcode = X86ISD::OR;
9975 return SDValue(Op.getNode(), 1);
9981 // If we found that truncation is beneficial, perform the truncation and
9983 if (NeedTruncation) {
9984 EVT VT = Op.getValueType();
9985 SDValue WideVal = Op->getOperand(0);
9986 EVT WideVT = WideVal.getValueType();
9987 unsigned ConvertedOp = 0;
9988 // Use a target machine opcode to prevent further DAGCombine
9989 // optimizations that may separate the arithmetic operations
9990 // from the setcc node.
9991 switch (WideVal.getOpcode()) {
9993 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9994 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9995 case ISD::AND: ConvertedOp = X86ISD::AND; break;
9996 case ISD::OR: ConvertedOp = X86ISD::OR; break;
9997 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
10001 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10002 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
10003 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
10004 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
10005 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
10011 // Emit a CMP with 0, which is the TEST pattern.
10012 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10013 DAG.getConstant(0, Op.getValueType()));
10015 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10016 SmallVector<SDValue, 4> Ops;
10017 for (unsigned i = 0; i != NumOperands; ++i)
10018 Ops.push_back(Op.getOperand(i));
10020 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
10021 DAG.ReplaceAllUsesWith(Op, New);
10022 return SDValue(New.getNode(), 1);
10025 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
10027 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
10028 SDLoc dl, SelectionDAG &DAG) const {
10029 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
10030 if (C->getAPIntValue() == 0)
10031 return EmitTest(Op0, X86CC, dl, DAG);
10033 if (Op0.getValueType() == MVT::i1)
10034 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
10037 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
10038 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
10039 // Do the comparison at i32 if it's smaller, besides the Atom case.
10040 // This avoids subregister aliasing issues. Keep the smaller reference
10041 // if we're optimizing for size, however, as that'll allow better folding
10042 // of memory operations.
10043 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
10044 !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
10045 AttributeSet::FunctionIndex, Attribute::MinSize) &&
10046 !Subtarget->isAtom()) {
10047 unsigned ExtendOp =
10048 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
10049 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
10050 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
10052 // Use SUB instead of CMP to enable CSE between SUB and CMP.
10053 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
10054 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
10056 return SDValue(Sub.getNode(), 1);
10058 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
10061 /// Convert a comparison if required by the subtarget.
10062 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
10063 SelectionDAG &DAG) const {
10064 // If the subtarget does not support the FUCOMI instruction, floating-point
10065 // comparisons have to be converted.
10066 if (Subtarget->hasCMov() ||
10067 Cmp.getOpcode() != X86ISD::CMP ||
10068 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
10069 !Cmp.getOperand(1).getValueType().isFloatingPoint())
10072 // The instruction selector will select an FUCOM instruction instead of
10073 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
10074 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
10075 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
10077 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
10078 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
10079 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
10080 DAG.getConstant(8, MVT::i8));
10081 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
10082 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
10085 static bool isAllOnes(SDValue V) {
10086 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10087 return C && C->isAllOnesValue();
10090 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
10091 /// if it's possible.
10092 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
10093 SDLoc dl, SelectionDAG &DAG) const {
10094 SDValue Op0 = And.getOperand(0);
10095 SDValue Op1 = And.getOperand(1);
10096 if (Op0.getOpcode() == ISD::TRUNCATE)
10097 Op0 = Op0.getOperand(0);
10098 if (Op1.getOpcode() == ISD::TRUNCATE)
10099 Op1 = Op1.getOperand(0);
10102 if (Op1.getOpcode() == ISD::SHL)
10103 std::swap(Op0, Op1);
10104 if (Op0.getOpcode() == ISD::SHL) {
10105 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
10106 if (And00C->getZExtValue() == 1) {
10107 // If we looked past a truncate, check that it's only truncating away
10109 unsigned BitWidth = Op0.getValueSizeInBits();
10110 unsigned AndBitWidth = And.getValueSizeInBits();
10111 if (BitWidth > AndBitWidth) {
10113 DAG.ComputeMaskedBits(Op0, Zeros, Ones);
10114 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
10118 RHS = Op0.getOperand(1);
10120 } else if (Op1.getOpcode() == ISD::Constant) {
10121 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
10122 uint64_t AndRHSVal = AndRHS->getZExtValue();
10123 SDValue AndLHS = Op0;
10125 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
10126 LHS = AndLHS.getOperand(0);
10127 RHS = AndLHS.getOperand(1);
10130 // Use BT if the immediate can't be encoded in a TEST instruction.
10131 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
10133 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
10137 if (LHS.getNode()) {
10138 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
10139 // instruction. Since the shift amount is in-range-or-undefined, we know
10140 // that doing a bittest on the i32 value is ok. We extend to i32 because
10141 // the encoding for the i16 version is larger than the i32 version.
10142 // Also promote i16 to i32 for performance / code size reason.
10143 if (LHS.getValueType() == MVT::i8 ||
10144 LHS.getValueType() == MVT::i16)
10145 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
10147 // If the operand types disagree, extend the shift amount to match. Since
10148 // BT ignores high bits (like shifts) we can use anyextend.
10149 if (LHS.getValueType() != RHS.getValueType())
10150 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
10152 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
10153 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
10154 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10155 DAG.getConstant(Cond, MVT::i8), BT);
10161 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
10163 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
10168 // SSE Condition code mapping:
10177 switch (SetCCOpcode) {
10178 default: llvm_unreachable("Unexpected SETCC condition");
10180 case ISD::SETEQ: SSECC = 0; break;
10182 case ISD::SETGT: Swap = true; // Fallthrough
10184 case ISD::SETOLT: SSECC = 1; break;
10186 case ISD::SETGE: Swap = true; // Fallthrough
10188 case ISD::SETOLE: SSECC = 2; break;
10189 case ISD::SETUO: SSECC = 3; break;
10191 case ISD::SETNE: SSECC = 4; break;
10192 case ISD::SETULE: Swap = true; // Fallthrough
10193 case ISD::SETUGE: SSECC = 5; break;
10194 case ISD::SETULT: Swap = true; // Fallthrough
10195 case ISD::SETUGT: SSECC = 6; break;
10196 case ISD::SETO: SSECC = 7; break;
10198 case ISD::SETONE: SSECC = 8; break;
10201 std::swap(Op0, Op1);
10206 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
10207 // ones, and then concatenate the result back.
10208 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
10209 MVT VT = Op.getSimpleValueType();
10211 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
10212 "Unsupported value type for operation");
10214 unsigned NumElems = VT.getVectorNumElements();
10216 SDValue CC = Op.getOperand(2);
10218 // Extract the LHS vectors
10219 SDValue LHS = Op.getOperand(0);
10220 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10221 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10223 // Extract the RHS vectors
10224 SDValue RHS = Op.getOperand(1);
10225 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10226 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10228 // Issue the operation on the smaller types and concatenate the result back
10229 MVT EltVT = VT.getVectorElementType();
10230 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10231 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10232 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
10233 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
10236 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
10237 const X86Subtarget *Subtarget) {
10238 SDValue Op0 = Op.getOperand(0);
10239 SDValue Op1 = Op.getOperand(1);
10240 SDValue CC = Op.getOperand(2);
10241 MVT VT = Op.getSimpleValueType();
10244 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
10245 Op.getValueType().getScalarType() == MVT::i1 &&
10246 "Cannot set masked compare for this operation");
10248 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10250 bool Unsigned = false;
10253 switch (SetCCOpcode) {
10254 default: llvm_unreachable("Unexpected SETCC condition");
10255 case ISD::SETNE: SSECC = 4; break;
10256 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
10257 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
10258 case ISD::SETLT: Swap = true; //fall-through
10259 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
10260 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
10261 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
10262 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
10263 case ISD::SETULE: Unsigned = true; //fall-through
10264 case ISD::SETLE: SSECC = 2; break;
10268 std::swap(Op0, Op1);
10270 return DAG.getNode(Opc, dl, VT, Op0, Op1);
10271 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
10272 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10273 DAG.getConstant(SSECC, MVT::i8));
10276 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
10277 /// operand \p Op1. If non-trivial (for example because it's not constant)
10278 /// return an empty value.
10279 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
10281 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
10285 MVT VT = Op1.getSimpleValueType();
10286 MVT EVT = VT.getVectorElementType();
10287 unsigned n = VT.getVectorNumElements();
10288 SmallVector<SDValue, 8> ULTOp1;
10290 for (unsigned i = 0; i < n; ++i) {
10291 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
10292 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
10295 // Avoid underflow.
10296 APInt Val = Elt->getAPIntValue();
10300 ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
10303 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1.data(), ULTOp1.size());
10306 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
10307 SelectionDAG &DAG) {
10308 SDValue Op0 = Op.getOperand(0);
10309 SDValue Op1 = Op.getOperand(1);
10310 SDValue CC = Op.getOperand(2);
10311 MVT VT = Op.getSimpleValueType();
10312 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10313 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10318 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10319 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10322 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10323 unsigned Opc = X86ISD::CMPP;
10324 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10325 assert(VT.getVectorNumElements() <= 16);
10326 Opc = X86ISD::CMPM;
10328 // In the two special cases we can't handle, emit two comparisons.
10331 unsigned CombineOpc;
10332 if (SetCCOpcode == ISD::SETUEQ) {
10333 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10335 assert(SetCCOpcode == ISD::SETONE);
10336 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10339 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10340 DAG.getConstant(CC0, MVT::i8));
10341 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10342 DAG.getConstant(CC1, MVT::i8));
10343 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10345 // Handle all other FP comparisons here.
10346 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10347 DAG.getConstant(SSECC, MVT::i8));
10350 // Break 256-bit integer vector compare into smaller ones.
10351 if (VT.is256BitVector() && !Subtarget->hasInt256())
10352 return Lower256IntVSETCC(Op, DAG);
10354 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10355 EVT OpVT = Op1.getValueType();
10356 if (Subtarget->hasAVX512()) {
10357 if (Op1.getValueType().is512BitVector() ||
10358 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10359 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
10361 // In AVX-512 architecture setcc returns mask with i1 elements,
10362 // But there is no compare instruction for i8 and i16 elements.
10363 // We are not talking about 512-bit operands in this case, these
10364 // types are illegal.
10366 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10367 OpVT.getVectorElementType().getSizeInBits() >= 8))
10368 return DAG.getNode(ISD::TRUNCATE, dl, VT,
10369 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10372 // We are handling one of the integer comparisons here. Since SSE only has
10373 // GT and EQ comparisons for integer, swapping operands and multiple
10374 // operations may be required for some comparisons.
10376 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10377 bool Subus = false;
10379 switch (SetCCOpcode) {
10380 default: llvm_unreachable("Unexpected SETCC condition");
10381 case ISD::SETNE: Invert = true;
10382 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
10383 case ISD::SETLT: Swap = true;
10384 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
10385 case ISD::SETGE: Swap = true;
10386 case ISD::SETLE: Opc = X86ISD::PCMPGT;
10387 Invert = true; break;
10388 case ISD::SETULT: Swap = true;
10389 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
10390 FlipSigns = true; break;
10391 case ISD::SETUGE: Swap = true;
10392 case ISD::SETULE: Opc = X86ISD::PCMPGT;
10393 FlipSigns = true; Invert = true; break;
10396 // Special case: Use min/max operations for SETULE/SETUGE
10397 MVT VET = VT.getVectorElementType();
10399 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10400 || (Subtarget->hasSSE2() && (VET == MVT::i8));
10403 switch (SetCCOpcode) {
10405 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10406 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10409 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10412 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
10413 if (!MinMax && hasSubus) {
10414 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
10416 // t = psubus Op0, Op1
10417 // pcmpeq t, <0..0>
10418 switch (SetCCOpcode) {
10420 case ISD::SETULT: {
10421 // If the comparison is against a constant we can turn this into a
10422 // setule. With psubus, setule does not require a swap. This is
10423 // beneficial because the constant in the register is no longer
10424 // destructed as the destination so it can be hoisted out of a loop.
10425 // Only do this pre-AVX since vpcmp* is no longer destructive.
10426 if (Subtarget->hasAVX())
10428 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
10429 if (ULEOp1.getNode()) {
10431 Subus = true; Invert = false; Swap = false;
10435 // Psubus is better than flip-sign because it requires no inversion.
10436 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
10437 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
10441 Opc = X86ISD::SUBUS;
10447 std::swap(Op0, Op1);
10449 // Check that the operation in question is available (most are plain SSE2,
10450 // but PCMPGTQ and PCMPEQQ have different requirements).
10451 if (VT == MVT::v2i64) {
10452 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10453 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10455 // First cast everything to the right type.
10456 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10457 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10459 // Since SSE has no unsigned integer comparisons, we need to flip the sign
10460 // bits of the inputs before performing those operations. The lower
10461 // compare is always unsigned.
10464 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10466 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10467 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10468 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10469 Sign, Zero, Sign, Zero);
10471 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10472 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10474 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10475 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10476 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10478 // Create masks for only the low parts/high parts of the 64 bit integers.
10479 static const int MaskHi[] = { 1, 1, 3, 3 };
10480 static const int MaskLo[] = { 0, 0, 2, 2 };
10481 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10482 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10483 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10485 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10486 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10489 Result = DAG.getNOT(dl, Result, MVT::v4i32);
10491 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10494 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10495 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10496 // pcmpeqd + pshufd + pand.
10497 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10499 // First cast everything to the right type.
10500 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10501 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10504 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
10506 // Make sure the lower and upper halves are both all-ones.
10507 static const int Mask[] = { 1, 0, 3, 2 };
10508 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
10509 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
10512 Result = DAG.getNOT(dl, Result, MVT::v4i32);
10514 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10518 // Since SSE has no unsigned integer comparisons, we need to flip the sign
10519 // bits of the inputs before performing those operations.
10521 EVT EltVT = VT.getVectorElementType();
10522 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
10523 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
10524 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
10527 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
10529 // If the logical-not of the result is required, perform that now.
10531 Result = DAG.getNOT(dl, Result, VT);
10534 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
10537 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
10538 getZeroVector(VT, Subtarget, DAG, dl));
10543 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
10545 MVT VT = Op.getSimpleValueType();
10547 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
10549 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
10550 && "SetCC type must be 8-bit or 1-bit integer");
10551 SDValue Op0 = Op.getOperand(0);
10552 SDValue Op1 = Op.getOperand(1);
10554 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10556 // Optimize to BT if possible.
10557 // Lower (X & (1 << N)) == 0 to BT(X, N).
10558 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
10559 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
10560 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
10561 Op1.getOpcode() == ISD::Constant &&
10562 cast<ConstantSDNode>(Op1)->isNullValue() &&
10563 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10564 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
10565 if (NewSetCC.getNode())
10569 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
10571 if (Op1.getOpcode() == ISD::Constant &&
10572 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
10573 cast<ConstantSDNode>(Op1)->isNullValue()) &&
10574 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10576 // If the input is a setcc, then reuse the input setcc or use a new one with
10577 // the inverted condition.
10578 if (Op0.getOpcode() == X86ISD::SETCC) {
10579 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
10580 bool Invert = (CC == ISD::SETNE) ^
10581 cast<ConstantSDNode>(Op1)->isNullValue();
10585 CCode = X86::GetOppositeBranchCondition(CCode);
10586 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10587 DAG.getConstant(CCode, MVT::i8),
10588 Op0.getOperand(1));
10590 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10594 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
10595 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
10596 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10598 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
10599 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
10602 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
10603 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
10604 if (X86CC == X86::COND_INVALID)
10607 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
10608 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
10609 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10610 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
10612 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10616 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10617 static bool isX86LogicalCmp(SDValue Op) {
10618 unsigned Opc = Op.getNode()->getOpcode();
10619 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10620 Opc == X86ISD::SAHF)
10622 if (Op.getResNo() == 1 &&
10623 (Opc == X86ISD::ADD ||
10624 Opc == X86ISD::SUB ||
10625 Opc == X86ISD::ADC ||
10626 Opc == X86ISD::SBB ||
10627 Opc == X86ISD::SMUL ||
10628 Opc == X86ISD::UMUL ||
10629 Opc == X86ISD::INC ||
10630 Opc == X86ISD::DEC ||
10631 Opc == X86ISD::OR ||
10632 Opc == X86ISD::XOR ||
10633 Opc == X86ISD::AND))
10636 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
10642 static bool isZero(SDValue V) {
10643 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10644 return C && C->isNullValue();
10647 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
10648 if (V.getOpcode() != ISD::TRUNCATE)
10651 SDValue VOp0 = V.getOperand(0);
10652 unsigned InBits = VOp0.getValueSizeInBits();
10653 unsigned Bits = V.getValueSizeInBits();
10654 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
10657 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
10658 bool addTest = true;
10659 SDValue Cond = Op.getOperand(0);
10660 SDValue Op1 = Op.getOperand(1);
10661 SDValue Op2 = Op.getOperand(2);
10663 EVT VT = Op1.getValueType();
10666 // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
10667 // are available. Otherwise fp cmovs get lowered into a less efficient branch
10668 // sequence later on.
10669 if (Cond.getOpcode() == ISD::SETCC &&
10670 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
10671 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
10672 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
10673 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
10674 int SSECC = translateX86FSETCC(
10675 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
10678 if (Subtarget->hasAVX512()) {
10679 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
10680 DAG.getConstant(SSECC, MVT::i8));
10681 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
10683 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
10684 DAG.getConstant(SSECC, MVT::i8));
10685 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
10686 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
10687 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
10691 if (Cond.getOpcode() == ISD::SETCC) {
10692 SDValue NewCond = LowerSETCC(Cond, DAG);
10693 if (NewCond.getNode())
10697 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
10698 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
10699 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
10700 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
10701 if (Cond.getOpcode() == X86ISD::SETCC &&
10702 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
10703 isZero(Cond.getOperand(1).getOperand(1))) {
10704 SDValue Cmp = Cond.getOperand(1);
10706 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
10708 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
10709 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
10710 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
10712 SDValue CmpOp0 = Cmp.getOperand(0);
10713 // Apply further optimizations for special cases
10714 // (select (x != 0), -1, 0) -> neg & sbb
10715 // (select (x == 0), 0, -1) -> neg & sbb
10716 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
10717 if (YC->isNullValue() &&
10718 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
10719 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
10720 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
10721 DAG.getConstant(0, CmpOp0.getValueType()),
10723 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10724 DAG.getConstant(X86::COND_B, MVT::i8),
10725 SDValue(Neg.getNode(), 1));
10729 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10730 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10731 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10733 SDValue Res = // Res = 0 or -1.
10734 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10735 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
10737 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
10738 Res = DAG.getNOT(DL, Res, Res.getValueType());
10740 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
10741 if (!N2C || !N2C->isNullValue())
10742 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
10747 // Look past (and (setcc_carry (cmp ...)), 1).
10748 if (Cond.getOpcode() == ISD::AND &&
10749 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10750 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10751 if (C && C->getAPIntValue() == 1)
10752 Cond = Cond.getOperand(0);
10755 // If condition flag is set by a X86ISD::CMP, then use it as the condition
10756 // setting operand in place of the X86ISD::SETCC.
10757 unsigned CondOpcode = Cond.getOpcode();
10758 if (CondOpcode == X86ISD::SETCC ||
10759 CondOpcode == X86ISD::SETCC_CARRY) {
10760 CC = Cond.getOperand(0);
10762 SDValue Cmp = Cond.getOperand(1);
10763 unsigned Opc = Cmp.getOpcode();
10764 MVT VT = Op.getSimpleValueType();
10766 bool IllegalFPCMov = false;
10767 if (VT.isFloatingPoint() && !VT.isVector() &&
10768 !isScalarFPTypeInSSEReg(VT)) // FPStack?
10769 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
10771 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
10772 Opc == X86ISD::BT) { // FIXME
10776 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10777 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10778 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10779 Cond.getOperand(0).getValueType() != MVT::i8)) {
10780 SDValue LHS = Cond.getOperand(0);
10781 SDValue RHS = Cond.getOperand(1);
10782 unsigned X86Opcode;
10785 switch (CondOpcode) {
10786 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10787 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10788 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10789 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10790 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10791 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10792 default: llvm_unreachable("unexpected overflowing operator");
10794 if (CondOpcode == ISD::UMULO)
10795 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10798 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10800 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
10802 if (CondOpcode == ISD::UMULO)
10803 Cond = X86Op.getValue(2);
10805 Cond = X86Op.getValue(1);
10807 CC = DAG.getConstant(X86Cond, MVT::i8);
10812 // Look pass the truncate if the high bits are known zero.
10813 if (isTruncWithZeroHighBitsInput(Cond, DAG))
10814 Cond = Cond.getOperand(0);
10816 // We know the result of AND is compared against zero. Try to match
10818 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10819 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
10820 if (NewSetCC.getNode()) {
10821 CC = NewSetCC.getOperand(0);
10822 Cond = NewSetCC.getOperand(1);
10829 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10830 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
10833 // a < b ? -1 : 0 -> RES = ~setcc_carry
10834 // a < b ? 0 : -1 -> RES = setcc_carry
10835 // a >= b ? -1 : 0 -> RES = setcc_carry
10836 // a >= b ? 0 : -1 -> RES = ~setcc_carry
10837 if (Cond.getOpcode() == X86ISD::SUB) {
10838 Cond = ConvertCmpIfNecessary(Cond, DAG);
10839 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
10841 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
10842 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
10843 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10844 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
10845 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
10846 return DAG.getNOT(DL, Res, Res.getValueType());
10851 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
10852 // widen the cmov and push the truncate through. This avoids introducing a new
10853 // branch during isel and doesn't add any extensions.
10854 if (Op.getValueType() == MVT::i8 &&
10855 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
10856 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
10857 if (T1.getValueType() == T2.getValueType() &&
10858 // Blacklist CopyFromReg to avoid partial register stalls.
10859 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
10860 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
10861 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
10862 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
10866 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
10867 // condition is true.
10868 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
10869 SDValue Ops[] = { Op2, Op1, CC, Cond };
10870 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
10873 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
10874 MVT VT = Op->getSimpleValueType(0);
10875 SDValue In = Op->getOperand(0);
10876 MVT InVT = In.getSimpleValueType();
10879 unsigned int NumElts = VT.getVectorNumElements();
10880 if (NumElts != 8 && NumElts != 16)
10883 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
10884 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10886 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10887 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
10889 MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
10890 Constant *C = ConstantInt::get(*DAG.getContext(),
10891 APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
10893 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
10894 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
10895 SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
10896 MachinePointerInfo::getConstantPool(),
10897 false, false, false, Alignment);
10898 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
10899 if (VT.is512BitVector())
10901 return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
10904 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
10905 SelectionDAG &DAG) {
10906 MVT VT = Op->getSimpleValueType(0);
10907 SDValue In = Op->getOperand(0);
10908 MVT InVT = In.getSimpleValueType();
10911 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
10912 return LowerSIGN_EXTEND_AVX512(Op, DAG);
10914 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
10915 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
10916 (VT != MVT::v16i16 || InVT != MVT::v16i8))
10919 if (Subtarget->hasInt256())
10920 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10922 // Optimize vectors in AVX mode
10923 // Sign extend v8i16 to v8i32 and
10926 // Divide input vector into two parts
10927 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
10928 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
10929 // concat the vectors to original VT
10931 unsigned NumElems = InVT.getVectorNumElements();
10932 SDValue Undef = DAG.getUNDEF(InVT);
10934 SmallVector<int,8> ShufMask1(NumElems, -1);
10935 for (unsigned i = 0; i != NumElems/2; ++i)
10938 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
10940 SmallVector<int,8> ShufMask2(NumElems, -1);
10941 for (unsigned i = 0; i != NumElems/2; ++i)
10942 ShufMask2[i] = i + NumElems/2;
10944 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
10946 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
10947 VT.getVectorNumElements()/2);
10949 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
10950 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
10952 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
10955 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
10956 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
10957 // from the AND / OR.
10958 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
10959 Opc = Op.getOpcode();
10960 if (Opc != ISD::OR && Opc != ISD::AND)
10962 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10963 Op.getOperand(0).hasOneUse() &&
10964 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
10965 Op.getOperand(1).hasOneUse());
10968 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
10969 // 1 and that the SETCC node has a single use.
10970 static bool isXor1OfSetCC(SDValue Op) {
10971 if (Op.getOpcode() != ISD::XOR)
10973 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10974 if (N1C && N1C->getAPIntValue() == 1) {
10975 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10976 Op.getOperand(0).hasOneUse();
10981 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
10982 bool addTest = true;
10983 SDValue Chain = Op.getOperand(0);
10984 SDValue Cond = Op.getOperand(1);
10985 SDValue Dest = Op.getOperand(2);
10988 bool Inverted = false;
10990 if (Cond.getOpcode() == ISD::SETCC) {
10991 // Check for setcc([su]{add,sub,mul}o == 0).
10992 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
10993 isa<ConstantSDNode>(Cond.getOperand(1)) &&
10994 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
10995 Cond.getOperand(0).getResNo() == 1 &&
10996 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
10997 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
10998 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
10999 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
11000 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
11001 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
11003 Cond = Cond.getOperand(0);
11005 SDValue NewCond = LowerSETCC(Cond, DAG);
11006 if (NewCond.getNode())
11011 // FIXME: LowerXALUO doesn't handle these!!
11012 else if (Cond.getOpcode() == X86ISD::ADD ||
11013 Cond.getOpcode() == X86ISD::SUB ||
11014 Cond.getOpcode() == X86ISD::SMUL ||
11015 Cond.getOpcode() == X86ISD::UMUL)
11016 Cond = LowerXALUO(Cond, DAG);
11019 // Look pass (and (setcc_carry (cmp ...)), 1).
11020 if (Cond.getOpcode() == ISD::AND &&
11021 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
11022 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11023 if (C && C->getAPIntValue() == 1)
11024 Cond = Cond.getOperand(0);
11027 // If condition flag is set by a X86ISD::CMP, then use it as the condition
11028 // setting operand in place of the X86ISD::SETCC.
11029 unsigned CondOpcode = Cond.getOpcode();
11030 if (CondOpcode == X86ISD::SETCC ||
11031 CondOpcode == X86ISD::SETCC_CARRY) {
11032 CC = Cond.getOperand(0);
11034 SDValue Cmp = Cond.getOperand(1);
11035 unsigned Opc = Cmp.getOpcode();
11036 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
11037 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
11041 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
11045 // These can only come from an arithmetic instruction with overflow,
11046 // e.g. SADDO, UADDO.
11047 Cond = Cond.getNode()->getOperand(1);
11053 CondOpcode = Cond.getOpcode();
11054 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11055 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11056 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11057 Cond.getOperand(0).getValueType() != MVT::i8)) {
11058 SDValue LHS = Cond.getOperand(0);
11059 SDValue RHS = Cond.getOperand(1);
11060 unsigned X86Opcode;
11063 // Keep this in sync with LowerXALUO, otherwise we might create redundant
11064 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
11066 switch (CondOpcode) {
11067 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11069 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11071 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
11074 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11075 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11077 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11079 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
11082 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11083 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11084 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11085 default: llvm_unreachable("unexpected overflowing operator");
11088 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
11089 if (CondOpcode == ISD::UMULO)
11090 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11093 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11095 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
11097 if (CondOpcode == ISD::UMULO)
11098 Cond = X86Op.getValue(2);
11100 Cond = X86Op.getValue(1);
11102 CC = DAG.getConstant(X86Cond, MVT::i8);
11106 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
11107 SDValue Cmp = Cond.getOperand(0).getOperand(1);
11108 if (CondOpc == ISD::OR) {
11109 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
11110 // two branches instead of an explicit OR instruction with a
11112 if (Cmp == Cond.getOperand(1).getOperand(1) &&
11113 isX86LogicalCmp(Cmp)) {
11114 CC = Cond.getOperand(0).getOperand(0);
11115 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11116 Chain, Dest, CC, Cmp);
11117 CC = Cond.getOperand(1).getOperand(0);
11121 } else { // ISD::AND
11122 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
11123 // two branches instead of an explicit AND instruction with a
11124 // separate test. However, we only do this if this block doesn't
11125 // have a fall-through edge, because this requires an explicit
11126 // jmp when the condition is false.
11127 if (Cmp == Cond.getOperand(1).getOperand(1) &&
11128 isX86LogicalCmp(Cmp) &&
11129 Op.getNode()->hasOneUse()) {
11130 X86::CondCode CCode =
11131 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11132 CCode = X86::GetOppositeBranchCondition(CCode);
11133 CC = DAG.getConstant(CCode, MVT::i8);
11134 SDNode *User = *Op.getNode()->use_begin();
11135 // Look for an unconditional branch following this conditional branch.
11136 // We need this because we need to reverse the successors in order
11137 // to implement FCMP_OEQ.
11138 if (User->getOpcode() == ISD::BR) {
11139 SDValue FalseBB = User->getOperand(1);
11141 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11142 assert(NewBR == User);
11146 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11147 Chain, Dest, CC, Cmp);
11148 X86::CondCode CCode =
11149 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
11150 CCode = X86::GetOppositeBranchCondition(CCode);
11151 CC = DAG.getConstant(CCode, MVT::i8);
11157 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
11158 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
11159 // It should be transformed during dag combiner except when the condition
11160 // is set by a arithmetics with overflow node.
11161 X86::CondCode CCode =
11162 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11163 CCode = X86::GetOppositeBranchCondition(CCode);
11164 CC = DAG.getConstant(CCode, MVT::i8);
11165 Cond = Cond.getOperand(0).getOperand(1);
11167 } else if (Cond.getOpcode() == ISD::SETCC &&
11168 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
11169 // For FCMP_OEQ, we can emit
11170 // two branches instead of an explicit AND instruction with a
11171 // separate test. However, we only do this if this block doesn't
11172 // have a fall-through edge, because this requires an explicit
11173 // jmp when the condition is false.
11174 if (Op.getNode()->hasOneUse()) {
11175 SDNode *User = *Op.getNode()->use_begin();
11176 // Look for an unconditional branch following this conditional branch.
11177 // We need this because we need to reverse the successors in order
11178 // to implement FCMP_OEQ.
11179 if (User->getOpcode() == ISD::BR) {
11180 SDValue FalseBB = User->getOperand(1);
11182 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11183 assert(NewBR == User);
11187 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11188 Cond.getOperand(0), Cond.getOperand(1));
11189 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11190 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11191 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11192 Chain, Dest, CC, Cmp);
11193 CC = DAG.getConstant(X86::COND_P, MVT::i8);
11198 } else if (Cond.getOpcode() == ISD::SETCC &&
11199 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
11200 // For FCMP_UNE, we can emit
11201 // two branches instead of an explicit AND instruction with a
11202 // separate test. However, we only do this if this block doesn't
11203 // have a fall-through edge, because this requires an explicit
11204 // jmp when the condition is false.
11205 if (Op.getNode()->hasOneUse()) {
11206 SDNode *User = *Op.getNode()->use_begin();
11207 // Look for an unconditional branch following this conditional branch.
11208 // We need this because we need to reverse the successors in order
11209 // to implement FCMP_UNE.
11210 if (User->getOpcode() == ISD::BR) {
11211 SDValue FalseBB = User->getOperand(1);
11213 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11214 assert(NewBR == User);
11217 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11218 Cond.getOperand(0), Cond.getOperand(1));
11219 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11220 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11221 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11222 Chain, Dest, CC, Cmp);
11223 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
11233 // Look pass the truncate if the high bits are known zero.
11234 if (isTruncWithZeroHighBitsInput(Cond, DAG))
11235 Cond = Cond.getOperand(0);
11237 // We know the result of AND is compared against zero. Try to match
11239 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11240 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
11241 if (NewSetCC.getNode()) {
11242 CC = NewSetCC.getOperand(0);
11243 Cond = NewSetCC.getOperand(1);
11250 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11251 Cond = EmitTest(Cond, X86::COND_NE, dl, DAG);
11253 Cond = ConvertCmpIfNecessary(Cond, DAG);
11254 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11255 Chain, Dest, CC, Cond);
11258 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
11259 // Calls to _alloca is needed to probe the stack when allocating more than 4k
11260 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
11261 // that the guard pages used by the OS virtual memory manager are allocated in
11262 // correct sequence.
11264 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
11265 SelectionDAG &DAG) const {
11266 MachineFunction &MF = DAG.getMachineFunction();
11267 bool SplitStack = MF.shouldSplitStack();
11268 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
11273 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11274 SDNode* Node = Op.getNode();
11276 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
11277 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
11278 " not tell us which reg is the stack pointer!");
11279 EVT VT = Node->getValueType(0);
11280 SDValue Tmp1 = SDValue(Node, 0);
11281 SDValue Tmp2 = SDValue(Node, 1);
11282 SDValue Tmp3 = Node->getOperand(2);
11283 SDValue Chain = Tmp1.getOperand(0);
11285 // Chain the dynamic stack allocation so that it doesn't modify the stack
11286 // pointer when other instructions are using the stack.
11287 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
11290 SDValue Size = Tmp2.getOperand(1);
11291 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
11292 Chain = SP.getValue(1);
11293 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
11294 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
11295 unsigned StackAlign = TFI.getStackAlignment();
11296 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
11297 if (Align > StackAlign)
11298 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
11299 DAG.getConstant(-(uint64_t)Align, VT));
11300 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
11302 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
11303 DAG.getIntPtrConstant(0, true), SDValue(),
11306 SDValue Ops[2] = { Tmp1, Tmp2 };
11307 return DAG.getMergeValues(Ops, 2, dl);
11311 SDValue Chain = Op.getOperand(0);
11312 SDValue Size = Op.getOperand(1);
11313 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11314 EVT VT = Op.getNode()->getValueType(0);
11316 bool Is64Bit = Subtarget->is64Bit();
11317 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
11320 MachineRegisterInfo &MRI = MF.getRegInfo();
11323 // The 64 bit implementation of segmented stacks needs to clobber both r10
11324 // r11. This makes it impossible to use it along with nested parameters.
11325 const Function *F = MF.getFunction();
11327 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
11329 if (I->hasNestAttr())
11330 report_fatal_error("Cannot use segmented stacks with functions that "
11331 "have nested arguments.");
11334 const TargetRegisterClass *AddrRegClass =
11335 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
11336 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
11337 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
11338 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
11339 DAG.getRegister(Vreg, SPTy));
11340 SDValue Ops1[2] = { Value, Chain };
11341 return DAG.getMergeValues(Ops1, 2, dl);
11344 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
11346 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
11347 Flag = Chain.getValue(1);
11348 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11350 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
11352 const X86RegisterInfo *RegInfo =
11353 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11354 unsigned SPReg = RegInfo->getStackRegister();
11355 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
11356 Chain = SP.getValue(1);
11359 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11360 DAG.getConstant(-(uint64_t)Align, VT));
11361 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
11364 SDValue Ops1[2] = { SP, Chain };
11365 return DAG.getMergeValues(Ops1, 2, dl);
11369 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
11370 MachineFunction &MF = DAG.getMachineFunction();
11371 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
11373 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11376 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
11377 // vastart just stores the address of the VarArgsFrameIndex slot into the
11378 // memory location argument.
11379 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11381 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
11382 MachinePointerInfo(SV), false, false, 0);
11386 // gp_offset (0 - 6 * 8)
11387 // fp_offset (48 - 48 + 8 * 16)
11388 // overflow_arg_area (point to parameters coming in memory).
11390 SmallVector<SDValue, 8> MemOps;
11391 SDValue FIN = Op.getOperand(1);
11393 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
11394 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
11396 FIN, MachinePointerInfo(SV), false, false, 0);
11397 MemOps.push_back(Store);
11400 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11401 FIN, DAG.getIntPtrConstant(4));
11402 Store = DAG.getStore(Op.getOperand(0), DL,
11403 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
11405 FIN, MachinePointerInfo(SV, 4), false, false, 0);
11406 MemOps.push_back(Store);
11408 // Store ptr to overflow_arg_area
11409 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11410 FIN, DAG.getIntPtrConstant(4));
11411 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11413 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11414 MachinePointerInfo(SV, 8),
11416 MemOps.push_back(Store);
11418 // Store ptr to reg_save_area.
11419 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11420 FIN, DAG.getIntPtrConstant(8));
11421 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11423 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11424 MachinePointerInfo(SV, 16), false, false, 0);
11425 MemOps.push_back(Store);
11426 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11427 &MemOps[0], MemOps.size());
11430 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11431 assert(Subtarget->is64Bit() &&
11432 "LowerVAARG only handles 64-bit va_arg!");
11433 assert((Subtarget->isTargetLinux() ||
11434 Subtarget->isTargetDarwin()) &&
11435 "Unhandled target in LowerVAARG");
11436 assert(Op.getNode()->getNumOperands() == 4);
11437 SDValue Chain = Op.getOperand(0);
11438 SDValue SrcPtr = Op.getOperand(1);
11439 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11440 unsigned Align = Op.getConstantOperandVal(3);
11443 EVT ArgVT = Op.getNode()->getValueType(0);
11444 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11445 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11448 // Decide which area this value should be read from.
11449 // TODO: Implement the AMD64 ABI in its entirety. This simple
11450 // selection mechanism works only for the basic types.
11451 if (ArgVT == MVT::f80) {
11452 llvm_unreachable("va_arg for f80 not yet implemented");
11453 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11454 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
11455 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11456 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
11458 llvm_unreachable("Unhandled argument type in LowerVAARG");
11461 if (ArgMode == 2) {
11462 // Sanity Check: Make sure using fp_offset makes sense.
11463 assert(!getTargetMachine().Options.UseSoftFloat &&
11464 !(DAG.getMachineFunction()
11465 .getFunction()->getAttributes()
11466 .hasAttribute(AttributeSet::FunctionIndex,
11467 Attribute::NoImplicitFloat)) &&
11468 Subtarget->hasSSE1());
11471 // Insert VAARG_64 node into the DAG
11472 // VAARG_64 returns two values: Variable Argument Address, Chain
11473 SmallVector<SDValue, 11> InstOps;
11474 InstOps.push_back(Chain);
11475 InstOps.push_back(SrcPtr);
11476 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11477 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11478 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11479 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11480 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11481 VTs, &InstOps[0], InstOps.size(),
11483 MachinePointerInfo(SV),
11485 /*Volatile=*/false,
11487 /*WriteMem=*/true);
11488 Chain = VAARG.getValue(1);
11490 // Load the next argument and return it
11491 return DAG.getLoad(ArgVT, dl,
11494 MachinePointerInfo(),
11495 false, false, false, 0);
11498 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11499 SelectionDAG &DAG) {
11500 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
11501 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
11502 SDValue Chain = Op.getOperand(0);
11503 SDValue DstPtr = Op.getOperand(1);
11504 SDValue SrcPtr = Op.getOperand(2);
11505 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
11506 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11509 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
11510 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
11512 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
11515 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
11516 // amount is a constant. Takes immediate version of shift as input.
11517 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
11518 SDValue SrcOp, uint64_t ShiftAmt,
11519 SelectionDAG &DAG) {
11520 MVT ElementType = VT.getVectorElementType();
11522 // Check for ShiftAmt >= element width
11523 if (ShiftAmt >= ElementType.getSizeInBits()) {
11524 if (Opc == X86ISD::VSRAI)
11525 ShiftAmt = ElementType.getSizeInBits() - 1;
11527 return DAG.getConstant(0, VT);
11530 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
11531 && "Unknown target vector shift-by-constant node");
11533 // Fold this packed vector shift into a build vector if SrcOp is a
11534 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
11535 if (VT == SrcOp.getSimpleValueType() &&
11536 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
11537 SmallVector<SDValue, 8> Elts;
11538 unsigned NumElts = SrcOp->getNumOperands();
11539 ConstantSDNode *ND;
11542 default: llvm_unreachable(0);
11543 case X86ISD::VSHLI:
11544 for (unsigned i=0; i!=NumElts; ++i) {
11545 SDValue CurrentOp = SrcOp->getOperand(i);
11546 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11547 Elts.push_back(CurrentOp);
11550 ND = cast<ConstantSDNode>(CurrentOp);
11551 const APInt &C = ND->getAPIntValue();
11552 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
11555 case X86ISD::VSRLI:
11556 for (unsigned i=0; i!=NumElts; ++i) {
11557 SDValue CurrentOp = SrcOp->getOperand(i);
11558 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11559 Elts.push_back(CurrentOp);
11562 ND = cast<ConstantSDNode>(CurrentOp);
11563 const APInt &C = ND->getAPIntValue();
11564 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
11567 case X86ISD::VSRAI:
11568 for (unsigned i=0; i!=NumElts; ++i) {
11569 SDValue CurrentOp = SrcOp->getOperand(i);
11570 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11571 Elts.push_back(CurrentOp);
11574 ND = cast<ConstantSDNode>(CurrentOp);
11575 const APInt &C = ND->getAPIntValue();
11576 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
11581 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Elts[0], NumElts);
11584 return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
11587 // getTargetVShiftNode - Handle vector element shifts where the shift amount
11588 // may or may not be a constant. Takes immediate version of shift as input.
11589 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
11590 SDValue SrcOp, SDValue ShAmt,
11591 SelectionDAG &DAG) {
11592 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
11594 // Catch shift-by-constant.
11595 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
11596 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
11597 CShAmt->getZExtValue(), DAG);
11599 // Change opcode to non-immediate version
11601 default: llvm_unreachable("Unknown target vector shift node");
11602 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
11603 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
11604 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
11607 // Need to build a vector containing shift amount
11608 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
11611 ShOps[1] = DAG.getConstant(0, MVT::i32);
11612 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
11613 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
11615 // The return type has to be a 128-bit type with the same element
11616 // type as the input type.
11617 MVT EltVT = VT.getVectorElementType();
11618 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
11620 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
11621 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
11624 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
11626 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11628 default: return SDValue(); // Don't custom lower most intrinsics.
11629 // Comparison intrinsics.
11630 case Intrinsic::x86_sse_comieq_ss:
11631 case Intrinsic::x86_sse_comilt_ss:
11632 case Intrinsic::x86_sse_comile_ss:
11633 case Intrinsic::x86_sse_comigt_ss:
11634 case Intrinsic::x86_sse_comige_ss:
11635 case Intrinsic::x86_sse_comineq_ss:
11636 case Intrinsic::x86_sse_ucomieq_ss:
11637 case Intrinsic::x86_sse_ucomilt_ss:
11638 case Intrinsic::x86_sse_ucomile_ss:
11639 case Intrinsic::x86_sse_ucomigt_ss:
11640 case Intrinsic::x86_sse_ucomige_ss:
11641 case Intrinsic::x86_sse_ucomineq_ss:
11642 case Intrinsic::x86_sse2_comieq_sd:
11643 case Intrinsic::x86_sse2_comilt_sd:
11644 case Intrinsic::x86_sse2_comile_sd:
11645 case Intrinsic::x86_sse2_comigt_sd:
11646 case Intrinsic::x86_sse2_comige_sd:
11647 case Intrinsic::x86_sse2_comineq_sd:
11648 case Intrinsic::x86_sse2_ucomieq_sd:
11649 case Intrinsic::x86_sse2_ucomilt_sd:
11650 case Intrinsic::x86_sse2_ucomile_sd:
11651 case Intrinsic::x86_sse2_ucomigt_sd:
11652 case Intrinsic::x86_sse2_ucomige_sd:
11653 case Intrinsic::x86_sse2_ucomineq_sd: {
11657 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11658 case Intrinsic::x86_sse_comieq_ss:
11659 case Intrinsic::x86_sse2_comieq_sd:
11660 Opc = X86ISD::COMI;
11663 case Intrinsic::x86_sse_comilt_ss:
11664 case Intrinsic::x86_sse2_comilt_sd:
11665 Opc = X86ISD::COMI;
11668 case Intrinsic::x86_sse_comile_ss:
11669 case Intrinsic::x86_sse2_comile_sd:
11670 Opc = X86ISD::COMI;
11673 case Intrinsic::x86_sse_comigt_ss:
11674 case Intrinsic::x86_sse2_comigt_sd:
11675 Opc = X86ISD::COMI;
11678 case Intrinsic::x86_sse_comige_ss:
11679 case Intrinsic::x86_sse2_comige_sd:
11680 Opc = X86ISD::COMI;
11683 case Intrinsic::x86_sse_comineq_ss:
11684 case Intrinsic::x86_sse2_comineq_sd:
11685 Opc = X86ISD::COMI;
11688 case Intrinsic::x86_sse_ucomieq_ss:
11689 case Intrinsic::x86_sse2_ucomieq_sd:
11690 Opc = X86ISD::UCOMI;
11693 case Intrinsic::x86_sse_ucomilt_ss:
11694 case Intrinsic::x86_sse2_ucomilt_sd:
11695 Opc = X86ISD::UCOMI;
11698 case Intrinsic::x86_sse_ucomile_ss:
11699 case Intrinsic::x86_sse2_ucomile_sd:
11700 Opc = X86ISD::UCOMI;
11703 case Intrinsic::x86_sse_ucomigt_ss:
11704 case Intrinsic::x86_sse2_ucomigt_sd:
11705 Opc = X86ISD::UCOMI;
11708 case Intrinsic::x86_sse_ucomige_ss:
11709 case Intrinsic::x86_sse2_ucomige_sd:
11710 Opc = X86ISD::UCOMI;
11713 case Intrinsic::x86_sse_ucomineq_ss:
11714 case Intrinsic::x86_sse2_ucomineq_sd:
11715 Opc = X86ISD::UCOMI;
11720 SDValue LHS = Op.getOperand(1);
11721 SDValue RHS = Op.getOperand(2);
11722 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
11723 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
11724 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
11725 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11726 DAG.getConstant(X86CC, MVT::i8), Cond);
11727 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11730 // Arithmetic intrinsics.
11731 case Intrinsic::x86_sse2_pmulu_dq:
11732 case Intrinsic::x86_avx2_pmulu_dq:
11733 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
11734 Op.getOperand(1), Op.getOperand(2));
11736 // SSE2/AVX2 sub with unsigned saturation intrinsics
11737 case Intrinsic::x86_sse2_psubus_b:
11738 case Intrinsic::x86_sse2_psubus_w:
11739 case Intrinsic::x86_avx2_psubus_b:
11740 case Intrinsic::x86_avx2_psubus_w:
11741 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
11742 Op.getOperand(1), Op.getOperand(2));
11744 // SSE3/AVX horizontal add/sub intrinsics
11745 case Intrinsic::x86_sse3_hadd_ps:
11746 case Intrinsic::x86_sse3_hadd_pd:
11747 case Intrinsic::x86_avx_hadd_ps_256:
11748 case Intrinsic::x86_avx_hadd_pd_256:
11749 case Intrinsic::x86_sse3_hsub_ps:
11750 case Intrinsic::x86_sse3_hsub_pd:
11751 case Intrinsic::x86_avx_hsub_ps_256:
11752 case Intrinsic::x86_avx_hsub_pd_256:
11753 case Intrinsic::x86_ssse3_phadd_w_128:
11754 case Intrinsic::x86_ssse3_phadd_d_128:
11755 case Intrinsic::x86_avx2_phadd_w:
11756 case Intrinsic::x86_avx2_phadd_d:
11757 case Intrinsic::x86_ssse3_phsub_w_128:
11758 case Intrinsic::x86_ssse3_phsub_d_128:
11759 case Intrinsic::x86_avx2_phsub_w:
11760 case Intrinsic::x86_avx2_phsub_d: {
11763 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11764 case Intrinsic::x86_sse3_hadd_ps:
11765 case Intrinsic::x86_sse3_hadd_pd:
11766 case Intrinsic::x86_avx_hadd_ps_256:
11767 case Intrinsic::x86_avx_hadd_pd_256:
11768 Opcode = X86ISD::FHADD;
11770 case Intrinsic::x86_sse3_hsub_ps:
11771 case Intrinsic::x86_sse3_hsub_pd:
11772 case Intrinsic::x86_avx_hsub_ps_256:
11773 case Intrinsic::x86_avx_hsub_pd_256:
11774 Opcode = X86ISD::FHSUB;
11776 case Intrinsic::x86_ssse3_phadd_w_128:
11777 case Intrinsic::x86_ssse3_phadd_d_128:
11778 case Intrinsic::x86_avx2_phadd_w:
11779 case Intrinsic::x86_avx2_phadd_d:
11780 Opcode = X86ISD::HADD;
11782 case Intrinsic::x86_ssse3_phsub_w_128:
11783 case Intrinsic::x86_ssse3_phsub_d_128:
11784 case Intrinsic::x86_avx2_phsub_w:
11785 case Intrinsic::x86_avx2_phsub_d:
11786 Opcode = X86ISD::HSUB;
11789 return DAG.getNode(Opcode, dl, Op.getValueType(),
11790 Op.getOperand(1), Op.getOperand(2));
11793 // SSE2/SSE41/AVX2 integer max/min intrinsics.
11794 case Intrinsic::x86_sse2_pmaxu_b:
11795 case Intrinsic::x86_sse41_pmaxuw:
11796 case Intrinsic::x86_sse41_pmaxud:
11797 case Intrinsic::x86_avx2_pmaxu_b:
11798 case Intrinsic::x86_avx2_pmaxu_w:
11799 case Intrinsic::x86_avx2_pmaxu_d:
11800 case Intrinsic::x86_sse2_pminu_b:
11801 case Intrinsic::x86_sse41_pminuw:
11802 case Intrinsic::x86_sse41_pminud:
11803 case Intrinsic::x86_avx2_pminu_b:
11804 case Intrinsic::x86_avx2_pminu_w:
11805 case Intrinsic::x86_avx2_pminu_d:
11806 case Intrinsic::x86_sse41_pmaxsb:
11807 case Intrinsic::x86_sse2_pmaxs_w:
11808 case Intrinsic::x86_sse41_pmaxsd:
11809 case Intrinsic::x86_avx2_pmaxs_b:
11810 case Intrinsic::x86_avx2_pmaxs_w:
11811 case Intrinsic::x86_avx2_pmaxs_d:
11812 case Intrinsic::x86_sse41_pminsb:
11813 case Intrinsic::x86_sse2_pmins_w:
11814 case Intrinsic::x86_sse41_pminsd:
11815 case Intrinsic::x86_avx2_pmins_b:
11816 case Intrinsic::x86_avx2_pmins_w:
11817 case Intrinsic::x86_avx2_pmins_d: {
11820 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11821 case Intrinsic::x86_sse2_pmaxu_b:
11822 case Intrinsic::x86_sse41_pmaxuw:
11823 case Intrinsic::x86_sse41_pmaxud:
11824 case Intrinsic::x86_avx2_pmaxu_b:
11825 case Intrinsic::x86_avx2_pmaxu_w:
11826 case Intrinsic::x86_avx2_pmaxu_d:
11827 Opcode = X86ISD::UMAX;
11829 case Intrinsic::x86_sse2_pminu_b:
11830 case Intrinsic::x86_sse41_pminuw:
11831 case Intrinsic::x86_sse41_pminud:
11832 case Intrinsic::x86_avx2_pminu_b:
11833 case Intrinsic::x86_avx2_pminu_w:
11834 case Intrinsic::x86_avx2_pminu_d:
11835 Opcode = X86ISD::UMIN;
11837 case Intrinsic::x86_sse41_pmaxsb:
11838 case Intrinsic::x86_sse2_pmaxs_w:
11839 case Intrinsic::x86_sse41_pmaxsd:
11840 case Intrinsic::x86_avx2_pmaxs_b:
11841 case Intrinsic::x86_avx2_pmaxs_w:
11842 case Intrinsic::x86_avx2_pmaxs_d:
11843 Opcode = X86ISD::SMAX;
11845 case Intrinsic::x86_sse41_pminsb:
11846 case Intrinsic::x86_sse2_pmins_w:
11847 case Intrinsic::x86_sse41_pminsd:
11848 case Intrinsic::x86_avx2_pmins_b:
11849 case Intrinsic::x86_avx2_pmins_w:
11850 case Intrinsic::x86_avx2_pmins_d:
11851 Opcode = X86ISD::SMIN;
11854 return DAG.getNode(Opcode, dl, Op.getValueType(),
11855 Op.getOperand(1), Op.getOperand(2));
11858 // SSE/SSE2/AVX floating point max/min intrinsics.
11859 case Intrinsic::x86_sse_max_ps:
11860 case Intrinsic::x86_sse2_max_pd:
11861 case Intrinsic::x86_avx_max_ps_256:
11862 case Intrinsic::x86_avx_max_pd_256:
11863 case Intrinsic::x86_sse_min_ps:
11864 case Intrinsic::x86_sse2_min_pd:
11865 case Intrinsic::x86_avx_min_ps_256:
11866 case Intrinsic::x86_avx_min_pd_256: {
11869 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11870 case Intrinsic::x86_sse_max_ps:
11871 case Intrinsic::x86_sse2_max_pd:
11872 case Intrinsic::x86_avx_max_ps_256:
11873 case Intrinsic::x86_avx_max_pd_256:
11874 Opcode = X86ISD::FMAX;
11876 case Intrinsic::x86_sse_min_ps:
11877 case Intrinsic::x86_sse2_min_pd:
11878 case Intrinsic::x86_avx_min_ps_256:
11879 case Intrinsic::x86_avx_min_pd_256:
11880 Opcode = X86ISD::FMIN;
11883 return DAG.getNode(Opcode, dl, Op.getValueType(),
11884 Op.getOperand(1), Op.getOperand(2));
11887 // AVX2 variable shift intrinsics
11888 case Intrinsic::x86_avx2_psllv_d:
11889 case Intrinsic::x86_avx2_psllv_q:
11890 case Intrinsic::x86_avx2_psllv_d_256:
11891 case Intrinsic::x86_avx2_psllv_q_256:
11892 case Intrinsic::x86_avx2_psrlv_d:
11893 case Intrinsic::x86_avx2_psrlv_q:
11894 case Intrinsic::x86_avx2_psrlv_d_256:
11895 case Intrinsic::x86_avx2_psrlv_q_256:
11896 case Intrinsic::x86_avx2_psrav_d:
11897 case Intrinsic::x86_avx2_psrav_d_256: {
11900 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11901 case Intrinsic::x86_avx2_psllv_d:
11902 case Intrinsic::x86_avx2_psllv_q:
11903 case Intrinsic::x86_avx2_psllv_d_256:
11904 case Intrinsic::x86_avx2_psllv_q_256:
11907 case Intrinsic::x86_avx2_psrlv_d:
11908 case Intrinsic::x86_avx2_psrlv_q:
11909 case Intrinsic::x86_avx2_psrlv_d_256:
11910 case Intrinsic::x86_avx2_psrlv_q_256:
11913 case Intrinsic::x86_avx2_psrav_d:
11914 case Intrinsic::x86_avx2_psrav_d_256:
11918 return DAG.getNode(Opcode, dl, Op.getValueType(),
11919 Op.getOperand(1), Op.getOperand(2));
11922 case Intrinsic::x86_ssse3_pshuf_b_128:
11923 case Intrinsic::x86_avx2_pshuf_b:
11924 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
11925 Op.getOperand(1), Op.getOperand(2));
11927 case Intrinsic::x86_ssse3_psign_b_128:
11928 case Intrinsic::x86_ssse3_psign_w_128:
11929 case Intrinsic::x86_ssse3_psign_d_128:
11930 case Intrinsic::x86_avx2_psign_b:
11931 case Intrinsic::x86_avx2_psign_w:
11932 case Intrinsic::x86_avx2_psign_d:
11933 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
11934 Op.getOperand(1), Op.getOperand(2));
11936 case Intrinsic::x86_sse41_insertps:
11937 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
11938 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11940 case Intrinsic::x86_avx_vperm2f128_ps_256:
11941 case Intrinsic::x86_avx_vperm2f128_pd_256:
11942 case Intrinsic::x86_avx_vperm2f128_si_256:
11943 case Intrinsic::x86_avx2_vperm2i128:
11944 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
11945 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11947 case Intrinsic::x86_avx2_permd:
11948 case Intrinsic::x86_avx2_permps:
11949 // Operands intentionally swapped. Mask is last operand to intrinsic,
11950 // but second operand for node/instruction.
11951 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
11952 Op.getOperand(2), Op.getOperand(1));
11954 case Intrinsic::x86_sse_sqrt_ps:
11955 case Intrinsic::x86_sse2_sqrt_pd:
11956 case Intrinsic::x86_avx_sqrt_ps_256:
11957 case Intrinsic::x86_avx_sqrt_pd_256:
11958 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
11960 // ptest and testp intrinsics. The intrinsic these come from are designed to
11961 // return an integer value, not just an instruction so lower it to the ptest
11962 // or testp pattern and a setcc for the result.
11963 case Intrinsic::x86_sse41_ptestz:
11964 case Intrinsic::x86_sse41_ptestc:
11965 case Intrinsic::x86_sse41_ptestnzc:
11966 case Intrinsic::x86_avx_ptestz_256:
11967 case Intrinsic::x86_avx_ptestc_256:
11968 case Intrinsic::x86_avx_ptestnzc_256:
11969 case Intrinsic::x86_avx_vtestz_ps:
11970 case Intrinsic::x86_avx_vtestc_ps:
11971 case Intrinsic::x86_avx_vtestnzc_ps:
11972 case Intrinsic::x86_avx_vtestz_pd:
11973 case Intrinsic::x86_avx_vtestc_pd:
11974 case Intrinsic::x86_avx_vtestnzc_pd:
11975 case Intrinsic::x86_avx_vtestz_ps_256:
11976 case Intrinsic::x86_avx_vtestc_ps_256:
11977 case Intrinsic::x86_avx_vtestnzc_ps_256:
11978 case Intrinsic::x86_avx_vtestz_pd_256:
11979 case Intrinsic::x86_avx_vtestc_pd_256:
11980 case Intrinsic::x86_avx_vtestnzc_pd_256: {
11981 bool IsTestPacked = false;
11984 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
11985 case Intrinsic::x86_avx_vtestz_ps:
11986 case Intrinsic::x86_avx_vtestz_pd:
11987 case Intrinsic::x86_avx_vtestz_ps_256:
11988 case Intrinsic::x86_avx_vtestz_pd_256:
11989 IsTestPacked = true; // Fallthrough
11990 case Intrinsic::x86_sse41_ptestz:
11991 case Intrinsic::x86_avx_ptestz_256:
11993 X86CC = X86::COND_E;
11995 case Intrinsic::x86_avx_vtestc_ps:
11996 case Intrinsic::x86_avx_vtestc_pd:
11997 case Intrinsic::x86_avx_vtestc_ps_256:
11998 case Intrinsic::x86_avx_vtestc_pd_256:
11999 IsTestPacked = true; // Fallthrough
12000 case Intrinsic::x86_sse41_ptestc:
12001 case Intrinsic::x86_avx_ptestc_256:
12003 X86CC = X86::COND_B;
12005 case Intrinsic::x86_avx_vtestnzc_ps:
12006 case Intrinsic::x86_avx_vtestnzc_pd:
12007 case Intrinsic::x86_avx_vtestnzc_ps_256:
12008 case Intrinsic::x86_avx_vtestnzc_pd_256:
12009 IsTestPacked = true; // Fallthrough
12010 case Intrinsic::x86_sse41_ptestnzc:
12011 case Intrinsic::x86_avx_ptestnzc_256:
12013 X86CC = X86::COND_A;
12017 SDValue LHS = Op.getOperand(1);
12018 SDValue RHS = Op.getOperand(2);
12019 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
12020 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
12021 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12022 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
12023 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12025 case Intrinsic::x86_avx512_kortestz_w:
12026 case Intrinsic::x86_avx512_kortestc_w: {
12027 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
12028 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
12029 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
12030 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12031 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
12032 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
12033 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12036 // SSE/AVX shift intrinsics
12037 case Intrinsic::x86_sse2_psll_w:
12038 case Intrinsic::x86_sse2_psll_d:
12039 case Intrinsic::x86_sse2_psll_q:
12040 case Intrinsic::x86_avx2_psll_w:
12041 case Intrinsic::x86_avx2_psll_d:
12042 case Intrinsic::x86_avx2_psll_q:
12043 case Intrinsic::x86_sse2_psrl_w:
12044 case Intrinsic::x86_sse2_psrl_d:
12045 case Intrinsic::x86_sse2_psrl_q:
12046 case Intrinsic::x86_avx2_psrl_w:
12047 case Intrinsic::x86_avx2_psrl_d:
12048 case Intrinsic::x86_avx2_psrl_q:
12049 case Intrinsic::x86_sse2_psra_w:
12050 case Intrinsic::x86_sse2_psra_d:
12051 case Intrinsic::x86_avx2_psra_w:
12052 case Intrinsic::x86_avx2_psra_d: {
12055 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12056 case Intrinsic::x86_sse2_psll_w:
12057 case Intrinsic::x86_sse2_psll_d:
12058 case Intrinsic::x86_sse2_psll_q:
12059 case Intrinsic::x86_avx2_psll_w:
12060 case Intrinsic::x86_avx2_psll_d:
12061 case Intrinsic::x86_avx2_psll_q:
12062 Opcode = X86ISD::VSHL;
12064 case Intrinsic::x86_sse2_psrl_w:
12065 case Intrinsic::x86_sse2_psrl_d:
12066 case Intrinsic::x86_sse2_psrl_q:
12067 case Intrinsic::x86_avx2_psrl_w:
12068 case Intrinsic::x86_avx2_psrl_d:
12069 case Intrinsic::x86_avx2_psrl_q:
12070 Opcode = X86ISD::VSRL;
12072 case Intrinsic::x86_sse2_psra_w:
12073 case Intrinsic::x86_sse2_psra_d:
12074 case Intrinsic::x86_avx2_psra_w:
12075 case Intrinsic::x86_avx2_psra_d:
12076 Opcode = X86ISD::VSRA;
12079 return DAG.getNode(Opcode, dl, Op.getValueType(),
12080 Op.getOperand(1), Op.getOperand(2));
12083 // SSE/AVX immediate shift intrinsics
12084 case Intrinsic::x86_sse2_pslli_w:
12085 case Intrinsic::x86_sse2_pslli_d:
12086 case Intrinsic::x86_sse2_pslli_q:
12087 case Intrinsic::x86_avx2_pslli_w:
12088 case Intrinsic::x86_avx2_pslli_d:
12089 case Intrinsic::x86_avx2_pslli_q:
12090 case Intrinsic::x86_sse2_psrli_w:
12091 case Intrinsic::x86_sse2_psrli_d:
12092 case Intrinsic::x86_sse2_psrli_q:
12093 case Intrinsic::x86_avx2_psrli_w:
12094 case Intrinsic::x86_avx2_psrli_d:
12095 case Intrinsic::x86_avx2_psrli_q:
12096 case Intrinsic::x86_sse2_psrai_w:
12097 case Intrinsic::x86_sse2_psrai_d:
12098 case Intrinsic::x86_avx2_psrai_w:
12099 case Intrinsic::x86_avx2_psrai_d: {
12102 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12103 case Intrinsic::x86_sse2_pslli_w:
12104 case Intrinsic::x86_sse2_pslli_d:
12105 case Intrinsic::x86_sse2_pslli_q:
12106 case Intrinsic::x86_avx2_pslli_w:
12107 case Intrinsic::x86_avx2_pslli_d:
12108 case Intrinsic::x86_avx2_pslli_q:
12109 Opcode = X86ISD::VSHLI;
12111 case Intrinsic::x86_sse2_psrli_w:
12112 case Intrinsic::x86_sse2_psrli_d:
12113 case Intrinsic::x86_sse2_psrli_q:
12114 case Intrinsic::x86_avx2_psrli_w:
12115 case Intrinsic::x86_avx2_psrli_d:
12116 case Intrinsic::x86_avx2_psrli_q:
12117 Opcode = X86ISD::VSRLI;
12119 case Intrinsic::x86_sse2_psrai_w:
12120 case Intrinsic::x86_sse2_psrai_d:
12121 case Intrinsic::x86_avx2_psrai_w:
12122 case Intrinsic::x86_avx2_psrai_d:
12123 Opcode = X86ISD::VSRAI;
12126 return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
12127 Op.getOperand(1), Op.getOperand(2), DAG);
12130 case Intrinsic::x86_sse42_pcmpistria128:
12131 case Intrinsic::x86_sse42_pcmpestria128:
12132 case Intrinsic::x86_sse42_pcmpistric128:
12133 case Intrinsic::x86_sse42_pcmpestric128:
12134 case Intrinsic::x86_sse42_pcmpistrio128:
12135 case Intrinsic::x86_sse42_pcmpestrio128:
12136 case Intrinsic::x86_sse42_pcmpistris128:
12137 case Intrinsic::x86_sse42_pcmpestris128:
12138 case Intrinsic::x86_sse42_pcmpistriz128:
12139 case Intrinsic::x86_sse42_pcmpestriz128: {
12143 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12144 case Intrinsic::x86_sse42_pcmpistria128:
12145 Opcode = X86ISD::PCMPISTRI;
12146 X86CC = X86::COND_A;
12148 case Intrinsic::x86_sse42_pcmpestria128:
12149 Opcode = X86ISD::PCMPESTRI;
12150 X86CC = X86::COND_A;
12152 case Intrinsic::x86_sse42_pcmpistric128:
12153 Opcode = X86ISD::PCMPISTRI;
12154 X86CC = X86::COND_B;
12156 case Intrinsic::x86_sse42_pcmpestric128:
12157 Opcode = X86ISD::PCMPESTRI;
12158 X86CC = X86::COND_B;
12160 case Intrinsic::x86_sse42_pcmpistrio128:
12161 Opcode = X86ISD::PCMPISTRI;
12162 X86CC = X86::COND_O;
12164 case Intrinsic::x86_sse42_pcmpestrio128:
12165 Opcode = X86ISD::PCMPESTRI;
12166 X86CC = X86::COND_O;
12168 case Intrinsic::x86_sse42_pcmpistris128:
12169 Opcode = X86ISD::PCMPISTRI;
12170 X86CC = X86::COND_S;
12172 case Intrinsic::x86_sse42_pcmpestris128:
12173 Opcode = X86ISD::PCMPESTRI;
12174 X86CC = X86::COND_S;
12176 case Intrinsic::x86_sse42_pcmpistriz128:
12177 Opcode = X86ISD::PCMPISTRI;
12178 X86CC = X86::COND_E;
12180 case Intrinsic::x86_sse42_pcmpestriz128:
12181 Opcode = X86ISD::PCMPESTRI;
12182 X86CC = X86::COND_E;
12185 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12186 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12187 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
12188 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12189 DAG.getConstant(X86CC, MVT::i8),
12190 SDValue(PCMP.getNode(), 1));
12191 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12194 case Intrinsic::x86_sse42_pcmpistri128:
12195 case Intrinsic::x86_sse42_pcmpestri128: {
12197 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
12198 Opcode = X86ISD::PCMPISTRI;
12200 Opcode = X86ISD::PCMPESTRI;
12202 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12203 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12204 return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
12206 case Intrinsic::x86_fma_vfmadd_ps:
12207 case Intrinsic::x86_fma_vfmadd_pd:
12208 case Intrinsic::x86_fma_vfmsub_ps:
12209 case Intrinsic::x86_fma_vfmsub_pd:
12210 case Intrinsic::x86_fma_vfnmadd_ps:
12211 case Intrinsic::x86_fma_vfnmadd_pd:
12212 case Intrinsic::x86_fma_vfnmsub_ps:
12213 case Intrinsic::x86_fma_vfnmsub_pd:
12214 case Intrinsic::x86_fma_vfmaddsub_ps:
12215 case Intrinsic::x86_fma_vfmaddsub_pd:
12216 case Intrinsic::x86_fma_vfmsubadd_ps:
12217 case Intrinsic::x86_fma_vfmsubadd_pd:
12218 case Intrinsic::x86_fma_vfmadd_ps_256:
12219 case Intrinsic::x86_fma_vfmadd_pd_256:
12220 case Intrinsic::x86_fma_vfmsub_ps_256:
12221 case Intrinsic::x86_fma_vfmsub_pd_256:
12222 case Intrinsic::x86_fma_vfnmadd_ps_256:
12223 case Intrinsic::x86_fma_vfnmadd_pd_256:
12224 case Intrinsic::x86_fma_vfnmsub_ps_256:
12225 case Intrinsic::x86_fma_vfnmsub_pd_256:
12226 case Intrinsic::x86_fma_vfmaddsub_ps_256:
12227 case Intrinsic::x86_fma_vfmaddsub_pd_256:
12228 case Intrinsic::x86_fma_vfmsubadd_ps_256:
12229 case Intrinsic::x86_fma_vfmsubadd_pd_256:
12230 case Intrinsic::x86_fma_vfmadd_ps_512:
12231 case Intrinsic::x86_fma_vfmadd_pd_512:
12232 case Intrinsic::x86_fma_vfmsub_ps_512:
12233 case Intrinsic::x86_fma_vfmsub_pd_512:
12234 case Intrinsic::x86_fma_vfnmadd_ps_512:
12235 case Intrinsic::x86_fma_vfnmadd_pd_512:
12236 case Intrinsic::x86_fma_vfnmsub_ps_512:
12237 case Intrinsic::x86_fma_vfnmsub_pd_512:
12238 case Intrinsic::x86_fma_vfmaddsub_ps_512:
12239 case Intrinsic::x86_fma_vfmaddsub_pd_512:
12240 case Intrinsic::x86_fma_vfmsubadd_ps_512:
12241 case Intrinsic::x86_fma_vfmsubadd_pd_512: {
12244 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12245 case Intrinsic::x86_fma_vfmadd_ps:
12246 case Intrinsic::x86_fma_vfmadd_pd:
12247 case Intrinsic::x86_fma_vfmadd_ps_256:
12248 case Intrinsic::x86_fma_vfmadd_pd_256:
12249 case Intrinsic::x86_fma_vfmadd_ps_512:
12250 case Intrinsic::x86_fma_vfmadd_pd_512:
12251 Opc = X86ISD::FMADD;
12253 case Intrinsic::x86_fma_vfmsub_ps:
12254 case Intrinsic::x86_fma_vfmsub_pd:
12255 case Intrinsic::x86_fma_vfmsub_ps_256:
12256 case Intrinsic::x86_fma_vfmsub_pd_256:
12257 case Intrinsic::x86_fma_vfmsub_ps_512:
12258 case Intrinsic::x86_fma_vfmsub_pd_512:
12259 Opc = X86ISD::FMSUB;
12261 case Intrinsic::x86_fma_vfnmadd_ps:
12262 case Intrinsic::x86_fma_vfnmadd_pd:
12263 case Intrinsic::x86_fma_vfnmadd_ps_256:
12264 case Intrinsic::x86_fma_vfnmadd_pd_256:
12265 case Intrinsic::x86_fma_vfnmadd_ps_512:
12266 case Intrinsic::x86_fma_vfnmadd_pd_512:
12267 Opc = X86ISD::FNMADD;
12269 case Intrinsic::x86_fma_vfnmsub_ps:
12270 case Intrinsic::x86_fma_vfnmsub_pd:
12271 case Intrinsic::x86_fma_vfnmsub_ps_256:
12272 case Intrinsic::x86_fma_vfnmsub_pd_256:
12273 case Intrinsic::x86_fma_vfnmsub_ps_512:
12274 case Intrinsic::x86_fma_vfnmsub_pd_512:
12275 Opc = X86ISD::FNMSUB;
12277 case Intrinsic::x86_fma_vfmaddsub_ps:
12278 case Intrinsic::x86_fma_vfmaddsub_pd:
12279 case Intrinsic::x86_fma_vfmaddsub_ps_256:
12280 case Intrinsic::x86_fma_vfmaddsub_pd_256:
12281 case Intrinsic::x86_fma_vfmaddsub_ps_512:
12282 case Intrinsic::x86_fma_vfmaddsub_pd_512:
12283 Opc = X86ISD::FMADDSUB;
12285 case Intrinsic::x86_fma_vfmsubadd_ps:
12286 case Intrinsic::x86_fma_vfmsubadd_pd:
12287 case Intrinsic::x86_fma_vfmsubadd_ps_256:
12288 case Intrinsic::x86_fma_vfmsubadd_pd_256:
12289 case Intrinsic::x86_fma_vfmsubadd_ps_512:
12290 case Intrinsic::x86_fma_vfmsubadd_pd_512:
12291 Opc = X86ISD::FMSUBADD;
12295 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
12296 Op.getOperand(2), Op.getOperand(3));
12301 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12302 SDValue Base, SDValue Index,
12303 SDValue ScaleOp, SDValue Chain,
12304 const X86Subtarget * Subtarget) {
12306 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12307 assert(C && "Invalid scale type");
12308 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12309 SDValue Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12310 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12311 Index.getSimpleValueType().getVectorNumElements());
12312 SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12313 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12314 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12315 SDValue Segment = DAG.getRegister(0, MVT::i32);
12316 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12317 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12318 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12319 return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
12322 static SDValue getMGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12323 SDValue Src, SDValue Mask, SDValue Base,
12324 SDValue Index, SDValue ScaleOp, SDValue Chain,
12325 const X86Subtarget * Subtarget) {
12327 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12328 assert(C && "Invalid scale type");
12329 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12330 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12331 Index.getSimpleValueType().getVectorNumElements());
12332 SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12333 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12334 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12335 SDValue Segment = DAG.getRegister(0, MVT::i32);
12336 if (Src.getOpcode() == ISD::UNDEF)
12337 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12338 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12339 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12340 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12341 return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
12344 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12345 SDValue Src, SDValue Base, SDValue Index,
12346 SDValue ScaleOp, SDValue Chain) {
12348 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12349 assert(C && "Invalid scale type");
12350 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12351 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12352 SDValue Segment = DAG.getRegister(0, MVT::i32);
12353 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12354 Index.getSimpleValueType().getVectorNumElements());
12355 SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12356 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12357 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12358 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12359 return SDValue(Res, 1);
12362 static SDValue getMScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12363 SDValue Src, SDValue Mask, SDValue Base,
12364 SDValue Index, SDValue ScaleOp, SDValue Chain) {
12366 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12367 assert(C && "Invalid scale type");
12368 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12369 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12370 SDValue Segment = DAG.getRegister(0, MVT::i32);
12371 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12372 Index.getSimpleValueType().getVectorNumElements());
12373 SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12374 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12375 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12376 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12377 return SDValue(Res, 1);
12380 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
12381 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
12382 // also used to custom lower READCYCLECOUNTER nodes.
12383 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
12384 SelectionDAG &DAG, const X86Subtarget *Subtarget,
12385 SmallVectorImpl<SDValue> &Results) {
12386 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12387 SDValue TheChain = N->getOperand(0);
12388 SDValue rd = DAG.getNode(Opcode, DL, Tys, &TheChain, 1);
12391 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
12392 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
12393 // and the EAX register is loaded with the low-order 32 bits.
12394 if (Subtarget->is64Bit()) {
12395 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
12396 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
12399 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
12400 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
12403 SDValue Chain = HI.getValue(1);
12405 if (Opcode == X86ISD::RDTSCP_DAG) {
12406 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
12408 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
12409 // the ECX register. Add 'ecx' explicitly to the chain.
12410 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
12412 // Explicitly store the content of ECX at the location passed in input
12413 // to the 'rdtscp' intrinsic.
12414 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
12415 MachinePointerInfo(), false, false, 0);
12418 if (Subtarget->is64Bit()) {
12419 // The EDX register is loaded with the high-order 32 bits of the MSR, and
12420 // the EAX register is loaded with the low-order 32 bits.
12421 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
12422 DAG.getConstant(32, MVT::i8));
12423 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
12424 Results.push_back(Chain);
12428 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12429 SDValue Ops[] = { LO, HI };
12430 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops,
12431 array_lengthof(Ops));
12432 Results.push_back(Pair);
12433 Results.push_back(Chain);
12436 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12437 SelectionDAG &DAG) {
12438 SmallVector<SDValue, 2> Results;
12440 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
12442 return DAG.getMergeValues(&Results[0], Results.size(), DL);
12445 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
12446 SelectionDAG &DAG) {
12448 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12450 default: return SDValue(); // Don't custom lower most intrinsics.
12452 // RDRAND/RDSEED intrinsics.
12453 case Intrinsic::x86_rdrand_16:
12454 case Intrinsic::x86_rdrand_32:
12455 case Intrinsic::x86_rdrand_64:
12456 case Intrinsic::x86_rdseed_16:
12457 case Intrinsic::x86_rdseed_32:
12458 case Intrinsic::x86_rdseed_64: {
12459 unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
12460 IntNo == Intrinsic::x86_rdseed_32 ||
12461 IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
12463 // Emit the node with the right value type.
12464 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
12465 SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
12467 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
12468 // Otherwise return the value from Rand, which is always 0, casted to i32.
12469 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
12470 DAG.getConstant(1, Op->getValueType(1)),
12471 DAG.getConstant(X86::COND_B, MVT::i32),
12472 SDValue(Result.getNode(), 1) };
12473 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
12474 DAG.getVTList(Op->getValueType(1), MVT::Glue),
12475 Ops, array_lengthof(Ops));
12477 // Return { result, isValid, chain }.
12478 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
12479 SDValue(Result.getNode(), 2));
12481 //int_gather(index, base, scale);
12482 case Intrinsic::x86_avx512_gather_qpd_512:
12483 case Intrinsic::x86_avx512_gather_qps_512:
12484 case Intrinsic::x86_avx512_gather_dpd_512:
12485 case Intrinsic::x86_avx512_gather_qpi_512:
12486 case Intrinsic::x86_avx512_gather_qpq_512:
12487 case Intrinsic::x86_avx512_gather_dpq_512:
12488 case Intrinsic::x86_avx512_gather_dps_512:
12489 case Intrinsic::x86_avx512_gather_dpi_512: {
12492 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12493 case Intrinsic::x86_avx512_gather_qps_512: Opc = X86::VGATHERQPSZrm; break;
12494 case Intrinsic::x86_avx512_gather_qpd_512: Opc = X86::VGATHERQPDZrm; break;
12495 case Intrinsic::x86_avx512_gather_dpd_512: Opc = X86::VGATHERDPDZrm; break;
12496 case Intrinsic::x86_avx512_gather_dps_512: Opc = X86::VGATHERDPSZrm; break;
12497 case Intrinsic::x86_avx512_gather_qpi_512: Opc = X86::VPGATHERQDZrm; break;
12498 case Intrinsic::x86_avx512_gather_qpq_512: Opc = X86::VPGATHERQQZrm; break;
12499 case Intrinsic::x86_avx512_gather_dpi_512: Opc = X86::VPGATHERDDZrm; break;
12500 case Intrinsic::x86_avx512_gather_dpq_512: Opc = X86::VPGATHERDQZrm; break;
12502 SDValue Chain = Op.getOperand(0);
12503 SDValue Index = Op.getOperand(2);
12504 SDValue Base = Op.getOperand(3);
12505 SDValue Scale = Op.getOperand(4);
12506 return getGatherNode(Opc, Op, DAG, Base, Index, Scale, Chain, Subtarget);
12508 //int_gather_mask(v1, mask, index, base, scale);
12509 case Intrinsic::x86_avx512_gather_qps_mask_512:
12510 case Intrinsic::x86_avx512_gather_qpd_mask_512:
12511 case Intrinsic::x86_avx512_gather_dpd_mask_512:
12512 case Intrinsic::x86_avx512_gather_dps_mask_512:
12513 case Intrinsic::x86_avx512_gather_qpi_mask_512:
12514 case Intrinsic::x86_avx512_gather_qpq_mask_512:
12515 case Intrinsic::x86_avx512_gather_dpi_mask_512:
12516 case Intrinsic::x86_avx512_gather_dpq_mask_512: {
12519 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12520 case Intrinsic::x86_avx512_gather_qps_mask_512:
12521 Opc = X86::VGATHERQPSZrm; break;
12522 case Intrinsic::x86_avx512_gather_qpd_mask_512:
12523 Opc = X86::VGATHERQPDZrm; break;
12524 case Intrinsic::x86_avx512_gather_dpd_mask_512:
12525 Opc = X86::VGATHERDPDZrm; break;
12526 case Intrinsic::x86_avx512_gather_dps_mask_512:
12527 Opc = X86::VGATHERDPSZrm; break;
12528 case Intrinsic::x86_avx512_gather_qpi_mask_512:
12529 Opc = X86::VPGATHERQDZrm; break;
12530 case Intrinsic::x86_avx512_gather_qpq_mask_512:
12531 Opc = X86::VPGATHERQQZrm; break;
12532 case Intrinsic::x86_avx512_gather_dpi_mask_512:
12533 Opc = X86::VPGATHERDDZrm; break;
12534 case Intrinsic::x86_avx512_gather_dpq_mask_512:
12535 Opc = X86::VPGATHERDQZrm; break;
12537 SDValue Chain = Op.getOperand(0);
12538 SDValue Src = Op.getOperand(2);
12539 SDValue Mask = Op.getOperand(3);
12540 SDValue Index = Op.getOperand(4);
12541 SDValue Base = Op.getOperand(5);
12542 SDValue Scale = Op.getOperand(6);
12543 return getMGatherNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
12546 //int_scatter(base, index, v1, scale);
12547 case Intrinsic::x86_avx512_scatter_qpd_512:
12548 case Intrinsic::x86_avx512_scatter_qps_512:
12549 case Intrinsic::x86_avx512_scatter_dpd_512:
12550 case Intrinsic::x86_avx512_scatter_qpi_512:
12551 case Intrinsic::x86_avx512_scatter_qpq_512:
12552 case Intrinsic::x86_avx512_scatter_dpq_512:
12553 case Intrinsic::x86_avx512_scatter_dps_512:
12554 case Intrinsic::x86_avx512_scatter_dpi_512: {
12557 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12558 case Intrinsic::x86_avx512_scatter_qpd_512:
12559 Opc = X86::VSCATTERQPDZmr; break;
12560 case Intrinsic::x86_avx512_scatter_qps_512:
12561 Opc = X86::VSCATTERQPSZmr; break;
12562 case Intrinsic::x86_avx512_scatter_dpd_512:
12563 Opc = X86::VSCATTERDPDZmr; break;
12564 case Intrinsic::x86_avx512_scatter_dps_512:
12565 Opc = X86::VSCATTERDPSZmr; break;
12566 case Intrinsic::x86_avx512_scatter_qpi_512:
12567 Opc = X86::VPSCATTERQDZmr; break;
12568 case Intrinsic::x86_avx512_scatter_qpq_512:
12569 Opc = X86::VPSCATTERQQZmr; break;
12570 case Intrinsic::x86_avx512_scatter_dpq_512:
12571 Opc = X86::VPSCATTERDQZmr; break;
12572 case Intrinsic::x86_avx512_scatter_dpi_512:
12573 Opc = X86::VPSCATTERDDZmr; break;
12575 SDValue Chain = Op.getOperand(0);
12576 SDValue Base = Op.getOperand(2);
12577 SDValue Index = Op.getOperand(3);
12578 SDValue Src = Op.getOperand(4);
12579 SDValue Scale = Op.getOperand(5);
12580 return getScatterNode(Opc, Op, DAG, Src, Base, Index, Scale, Chain);
12582 //int_scatter_mask(base, mask, index, v1, scale);
12583 case Intrinsic::x86_avx512_scatter_qps_mask_512:
12584 case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12585 case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12586 case Intrinsic::x86_avx512_scatter_dps_mask_512:
12587 case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12588 case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12589 case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12590 case Intrinsic::x86_avx512_scatter_dpq_mask_512: {
12593 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12594 case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12595 Opc = X86::VSCATTERQPDZmr; break;
12596 case Intrinsic::x86_avx512_scatter_qps_mask_512:
12597 Opc = X86::VSCATTERQPSZmr; break;
12598 case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12599 Opc = X86::VSCATTERDPDZmr; break;
12600 case Intrinsic::x86_avx512_scatter_dps_mask_512:
12601 Opc = X86::VSCATTERDPSZmr; break;
12602 case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12603 Opc = X86::VPSCATTERQDZmr; break;
12604 case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12605 Opc = X86::VPSCATTERQQZmr; break;
12606 case Intrinsic::x86_avx512_scatter_dpq_mask_512:
12607 Opc = X86::VPSCATTERDQZmr; break;
12608 case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12609 Opc = X86::VPSCATTERDDZmr; break;
12611 SDValue Chain = Op.getOperand(0);
12612 SDValue Base = Op.getOperand(2);
12613 SDValue Mask = Op.getOperand(3);
12614 SDValue Index = Op.getOperand(4);
12615 SDValue Src = Op.getOperand(5);
12616 SDValue Scale = Op.getOperand(6);
12617 return getMScatterNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
12619 // Read Time Stamp Counter (RDTSC).
12620 case Intrinsic::x86_rdtsc:
12621 // Read Time Stamp Counter and Processor ID (RDTSCP).
12622 case Intrinsic::x86_rdtscp: {
12625 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12626 case Intrinsic::x86_rdtsc:
12627 Opc = X86ISD::RDTSC_DAG; break;
12628 case Intrinsic::x86_rdtscp:
12629 Opc = X86ISD::RDTSCP_DAG; break;
12631 SmallVector<SDValue, 2> Results;
12632 getReadTimeStampCounter(Op.getNode(), dl, Opc, DAG, Subtarget, Results);
12633 return DAG.getMergeValues(&Results[0], Results.size(), dl);
12635 // XTEST intrinsics.
12636 case Intrinsic::x86_xtest: {
12637 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
12638 SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
12639 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12640 DAG.getConstant(X86::COND_NE, MVT::i8),
12642 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
12643 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
12644 Ret, SDValue(InTrans.getNode(), 1));
12649 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
12650 SelectionDAG &DAG) const {
12651 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12652 MFI->setReturnAddressIsTaken(true);
12654 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
12657 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12659 EVT PtrVT = getPointerTy();
12662 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12663 const X86RegisterInfo *RegInfo =
12664 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12665 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
12666 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12667 DAG.getNode(ISD::ADD, dl, PtrVT,
12668 FrameAddr, Offset),
12669 MachinePointerInfo(), false, false, false, 0);
12672 // Just load the return address.
12673 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
12674 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12675 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
12678 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
12679 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12680 MFI->setFrameAddressIsTaken(true);
12682 EVT VT = Op.getValueType();
12683 SDLoc dl(Op); // FIXME probably not meaningful
12684 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12685 const X86RegisterInfo *RegInfo =
12686 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12687 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12688 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
12689 (FrameReg == X86::EBP && VT == MVT::i32)) &&
12690 "Invalid Frame Register!");
12691 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
12693 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
12694 MachinePointerInfo(),
12695 false, false, false, 0);
12699 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
12700 SelectionDAG &DAG) const {
12701 const X86RegisterInfo *RegInfo =
12702 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12703 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
12706 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
12707 SDValue Chain = Op.getOperand(0);
12708 SDValue Offset = Op.getOperand(1);
12709 SDValue Handler = Op.getOperand(2);
12712 EVT PtrVT = getPointerTy();
12713 const X86RegisterInfo *RegInfo =
12714 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12715 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12716 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
12717 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
12718 "Invalid Frame Register!");
12719 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
12720 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
12722 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
12723 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
12724 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
12725 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
12727 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
12729 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
12730 DAG.getRegister(StoreAddrReg, PtrVT));
12733 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
12734 SelectionDAG &DAG) const {
12736 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
12737 DAG.getVTList(MVT::i32, MVT::Other),
12738 Op.getOperand(0), Op.getOperand(1));
12741 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
12742 SelectionDAG &DAG) const {
12744 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
12745 Op.getOperand(0), Op.getOperand(1));
12748 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
12749 return Op.getOperand(0);
12752 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
12753 SelectionDAG &DAG) const {
12754 SDValue Root = Op.getOperand(0);
12755 SDValue Trmp = Op.getOperand(1); // trampoline
12756 SDValue FPtr = Op.getOperand(2); // nested function
12757 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
12760 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
12761 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12763 if (Subtarget->is64Bit()) {
12764 SDValue OutChains[6];
12766 // Large code-model.
12767 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
12768 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
12770 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
12771 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
12773 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
12775 // Load the pointer to the nested function into R11.
12776 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
12777 SDValue Addr = Trmp;
12778 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12779 Addr, MachinePointerInfo(TrmpAddr),
12782 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12783 DAG.getConstant(2, MVT::i64));
12784 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
12785 MachinePointerInfo(TrmpAddr, 2),
12788 // Load the 'nest' parameter value into R10.
12789 // R10 is specified in X86CallingConv.td
12790 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
12791 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12792 DAG.getConstant(10, MVT::i64));
12793 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12794 Addr, MachinePointerInfo(TrmpAddr, 10),
12797 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12798 DAG.getConstant(12, MVT::i64));
12799 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
12800 MachinePointerInfo(TrmpAddr, 12),
12803 // Jump to the nested function.
12804 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
12805 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12806 DAG.getConstant(20, MVT::i64));
12807 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12808 Addr, MachinePointerInfo(TrmpAddr, 20),
12811 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
12812 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12813 DAG.getConstant(22, MVT::i64));
12814 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
12815 MachinePointerInfo(TrmpAddr, 22),
12818 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
12820 const Function *Func =
12821 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
12822 CallingConv::ID CC = Func->getCallingConv();
12827 llvm_unreachable("Unsupported calling convention");
12828 case CallingConv::C:
12829 case CallingConv::X86_StdCall: {
12830 // Pass 'nest' parameter in ECX.
12831 // Must be kept in sync with X86CallingConv.td
12832 NestReg = X86::ECX;
12834 // Check that ECX wasn't needed by an 'inreg' parameter.
12835 FunctionType *FTy = Func->getFunctionType();
12836 const AttributeSet &Attrs = Func->getAttributes();
12838 if (!Attrs.isEmpty() && !Func->isVarArg()) {
12839 unsigned InRegCount = 0;
12842 for (FunctionType::param_iterator I = FTy->param_begin(),
12843 E = FTy->param_end(); I != E; ++I, ++Idx)
12844 if (Attrs.hasAttribute(Idx, Attribute::InReg))
12845 // FIXME: should only count parameters that are lowered to integers.
12846 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
12848 if (InRegCount > 2) {
12849 report_fatal_error("Nest register in use - reduce number of inreg"
12855 case CallingConv::X86_FastCall:
12856 case CallingConv::X86_ThisCall:
12857 case CallingConv::Fast:
12858 // Pass 'nest' parameter in EAX.
12859 // Must be kept in sync with X86CallingConv.td
12860 NestReg = X86::EAX;
12864 SDValue OutChains[4];
12865 SDValue Addr, Disp;
12867 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12868 DAG.getConstant(10, MVT::i32));
12869 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
12871 // This is storing the opcode for MOV32ri.
12872 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
12873 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
12874 OutChains[0] = DAG.getStore(Root, dl,
12875 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
12876 Trmp, MachinePointerInfo(TrmpAddr),
12879 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12880 DAG.getConstant(1, MVT::i32));
12881 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
12882 MachinePointerInfo(TrmpAddr, 1),
12885 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
12886 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12887 DAG.getConstant(5, MVT::i32));
12888 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
12889 MachinePointerInfo(TrmpAddr, 5),
12892 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12893 DAG.getConstant(6, MVT::i32));
12894 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
12895 MachinePointerInfo(TrmpAddr, 6),
12898 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
12902 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
12903 SelectionDAG &DAG) const {
12905 The rounding mode is in bits 11:10 of FPSR, and has the following
12907 00 Round to nearest
12912 FLT_ROUNDS, on the other hand, expects the following:
12919 To perform the conversion, we do:
12920 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
12923 MachineFunction &MF = DAG.getMachineFunction();
12924 const TargetMachine &TM = MF.getTarget();
12925 const TargetFrameLowering &TFI = *TM.getFrameLowering();
12926 unsigned StackAlignment = TFI.getStackAlignment();
12927 MVT VT = Op.getSimpleValueType();
12930 // Save FP Control Word to stack slot
12931 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
12932 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12934 MachineMemOperand *MMO =
12935 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12936 MachineMemOperand::MOStore, 2, 2);
12938 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
12939 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
12940 DAG.getVTList(MVT::Other),
12941 Ops, array_lengthof(Ops), MVT::i16,
12944 // Load FP Control Word from stack slot
12945 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
12946 MachinePointerInfo(), false, false, false, 0);
12948 // Transform as necessary
12950 DAG.getNode(ISD::SRL, DL, MVT::i16,
12951 DAG.getNode(ISD::AND, DL, MVT::i16,
12952 CWD, DAG.getConstant(0x800, MVT::i16)),
12953 DAG.getConstant(11, MVT::i8));
12955 DAG.getNode(ISD::SRL, DL, MVT::i16,
12956 DAG.getNode(ISD::AND, DL, MVT::i16,
12957 CWD, DAG.getConstant(0x400, MVT::i16)),
12958 DAG.getConstant(9, MVT::i8));
12961 DAG.getNode(ISD::AND, DL, MVT::i16,
12962 DAG.getNode(ISD::ADD, DL, MVT::i16,
12963 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
12964 DAG.getConstant(1, MVT::i16)),
12965 DAG.getConstant(3, MVT::i16));
12967 return DAG.getNode((VT.getSizeInBits() < 16 ?
12968 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
12971 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
12972 MVT VT = Op.getSimpleValueType();
12974 unsigned NumBits = VT.getSizeInBits();
12977 Op = Op.getOperand(0);
12978 if (VT == MVT::i8) {
12979 // Zero extend to i32 since there is not an i8 bsr.
12981 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
12984 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
12985 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12986 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
12988 // If src is zero (i.e. bsr sets ZF), returns NumBits.
12991 DAG.getConstant(NumBits+NumBits-1, OpVT),
12992 DAG.getConstant(X86::COND_E, MVT::i8),
12995 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
12997 // Finally xor with NumBits-1.
12998 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13001 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13005 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
13006 MVT VT = Op.getSimpleValueType();
13008 unsigned NumBits = VT.getSizeInBits();
13011 Op = Op.getOperand(0);
13012 if (VT == MVT::i8) {
13013 // Zero extend to i32 since there is not an i8 bsr.
13015 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13018 // Issue a bsr (scan bits in reverse).
13019 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13020 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13022 // And xor with NumBits-1.
13023 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13026 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13030 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
13031 MVT VT = Op.getSimpleValueType();
13032 unsigned NumBits = VT.getSizeInBits();
13034 Op = Op.getOperand(0);
13036 // Issue a bsf (scan bits forward) which also sets EFLAGS.
13037 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13038 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
13040 // If src is zero (i.e. bsf sets ZF), returns NumBits.
13043 DAG.getConstant(NumBits, VT),
13044 DAG.getConstant(X86::COND_E, MVT::i8),
13047 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
13050 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
13051 // ones, and then concatenate the result back.
13052 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
13053 MVT VT = Op.getSimpleValueType();
13055 assert(VT.is256BitVector() && VT.isInteger() &&
13056 "Unsupported value type for operation");
13058 unsigned NumElems = VT.getVectorNumElements();
13061 // Extract the LHS vectors
13062 SDValue LHS = Op.getOperand(0);
13063 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13064 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13066 // Extract the RHS vectors
13067 SDValue RHS = Op.getOperand(1);
13068 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13069 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13071 MVT EltVT = VT.getVectorElementType();
13072 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13074 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13075 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
13076 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
13079 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
13080 assert(Op.getSimpleValueType().is256BitVector() &&
13081 Op.getSimpleValueType().isInteger() &&
13082 "Only handle AVX 256-bit vector integer operation");
13083 return Lower256IntArith(Op, DAG);
13086 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
13087 assert(Op.getSimpleValueType().is256BitVector() &&
13088 Op.getSimpleValueType().isInteger() &&
13089 "Only handle AVX 256-bit vector integer operation");
13090 return Lower256IntArith(Op, DAG);
13093 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
13094 SelectionDAG &DAG) {
13096 MVT VT = Op.getSimpleValueType();
13098 // Decompose 256-bit ops into smaller 128-bit ops.
13099 if (VT.is256BitVector() && !Subtarget->hasInt256())
13100 return Lower256IntArith(Op, DAG);
13102 SDValue A = Op.getOperand(0);
13103 SDValue B = Op.getOperand(1);
13105 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
13106 if (VT == MVT::v4i32) {
13107 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
13108 "Should not custom lower when pmuldq is available!");
13110 // Extract the odd parts.
13111 static const int UnpackMask[] = { 1, -1, 3, -1 };
13112 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
13113 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
13115 // Multiply the even parts.
13116 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
13117 // Now multiply odd parts.
13118 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
13120 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
13121 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
13123 // Merge the two vectors back together with a shuffle. This expands into 2
13125 static const int ShufMask[] = { 0, 4, 2, 6 };
13126 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
13129 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
13130 "Only know how to lower V2I64/V4I64/V8I64 multiply");
13132 // Ahi = psrlqi(a, 32);
13133 // Bhi = psrlqi(b, 32);
13135 // AloBlo = pmuludq(a, b);
13136 // AloBhi = pmuludq(a, Bhi);
13137 // AhiBlo = pmuludq(Ahi, b);
13139 // AloBhi = psllqi(AloBhi, 32);
13140 // AhiBlo = psllqi(AhiBlo, 32);
13141 // return AloBlo + AloBhi + AhiBlo;
13143 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
13144 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
13146 // Bit cast to 32-bit vectors for MULUDQ
13147 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
13148 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
13149 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
13150 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
13151 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
13152 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
13154 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
13155 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
13156 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
13158 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
13159 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
13161 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
13162 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
13165 static SDValue LowerUMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
13166 SelectionDAG &DAG) {
13167 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
13168 EVT VT = Op0.getValueType();
13171 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
13172 (VT == MVT::v8i32 && Subtarget->hasInt256()));
13174 // Get the high parts.
13175 const int Mask[] = {1, 2, 3, 4, 5, 6, 7, 8};
13176 SDValue Hi0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
13177 SDValue Hi1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
13179 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
13181 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
13182 SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
13183 DAG.getNode(X86ISD::PMULUDQ, dl, MulVT, Op0, Op1));
13184 SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
13185 DAG.getNode(X86ISD::PMULUDQ, dl, MulVT, Hi0, Hi1));
13187 // Shuffle it back into the right order.
13188 const int HighMask[] = {1, 3, 5, 7, 9, 11, 13, 15};
13189 SDValue Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
13190 const int LowMask[] = {0, 2, 4, 6, 8, 10, 12, 14};
13191 SDValue Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
13193 return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Highs, Lows);
13196 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
13197 MVT VT = Op.getSimpleValueType();
13198 MVT EltTy = VT.getVectorElementType();
13199 unsigned NumElts = VT.getVectorNumElements();
13200 SDValue N0 = Op.getOperand(0);
13203 // Lower sdiv X, pow2-const.
13204 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
13208 APInt SplatValue, SplatUndef;
13209 unsigned SplatBitSize;
13211 if (!C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
13213 EltTy.getSizeInBits() < SplatBitSize)
13216 if ((SplatValue != 0) &&
13217 (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
13218 unsigned Lg2 = SplatValue.countTrailingZeros();
13219 // Splat the sign bit.
13220 SmallVector<SDValue, 16> Sz(NumElts,
13221 DAG.getConstant(EltTy.getSizeInBits() - 1,
13223 SDValue SGN = DAG.getNode(ISD::SRA, dl, VT, N0,
13224 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Sz[0],
13226 // Add (N0 < 0) ? abs2 - 1 : 0;
13227 SmallVector<SDValue, 16> Amt(NumElts,
13228 DAG.getConstant(EltTy.getSizeInBits() - Lg2,
13230 SDValue SRL = DAG.getNode(ISD::SRL, dl, VT, SGN,
13231 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Amt[0],
13233 SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
13234 SmallVector<SDValue, 16> Lg2Amt(NumElts, DAG.getConstant(Lg2, EltTy));
13235 SDValue SRA = DAG.getNode(ISD::SRA, dl, VT, ADD,
13236 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Lg2Amt[0],
13239 // If we're dividing by a positive value, we're done. Otherwise, we must
13240 // negate the result.
13241 if (SplatValue.isNonNegative())
13244 SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
13245 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
13246 return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
13251 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
13252 const X86Subtarget *Subtarget) {
13253 MVT VT = Op.getSimpleValueType();
13255 SDValue R = Op.getOperand(0);
13256 SDValue Amt = Op.getOperand(1);
13258 // Optimize shl/srl/sra with constant shift amount.
13259 if (isSplatVector(Amt.getNode())) {
13260 SDValue SclrAmt = Amt->getOperand(0);
13261 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
13262 uint64_t ShiftAmt = C->getZExtValue();
13264 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
13265 (Subtarget->hasInt256() &&
13266 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13267 (Subtarget->hasAVX512() &&
13268 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13269 if (Op.getOpcode() == ISD::SHL)
13270 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13272 if (Op.getOpcode() == ISD::SRL)
13273 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13275 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
13276 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13280 if (VT == MVT::v16i8) {
13281 if (Op.getOpcode() == ISD::SHL) {
13282 // Make a large shift.
13283 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13284 MVT::v8i16, R, ShiftAmt,
13286 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13287 // Zero out the rightmost bits.
13288 SmallVector<SDValue, 16> V(16,
13289 DAG.getConstant(uint8_t(-1U << ShiftAmt),
13291 return DAG.getNode(ISD::AND, dl, VT, SHL,
13292 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
13294 if (Op.getOpcode() == ISD::SRL) {
13295 // Make a large shift.
13296 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13297 MVT::v8i16, R, ShiftAmt,
13299 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13300 // Zero out the leftmost bits.
13301 SmallVector<SDValue, 16> V(16,
13302 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13304 return DAG.getNode(ISD::AND, dl, VT, SRL,
13305 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
13307 if (Op.getOpcode() == ISD::SRA) {
13308 if (ShiftAmt == 7) {
13309 // R s>> 7 === R s< 0
13310 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13311 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13314 // R s>> a === ((R u>> a) ^ m) - m
13315 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13316 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
13318 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
13319 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13320 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13323 llvm_unreachable("Unknown shift opcode.");
13326 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
13327 if (Op.getOpcode() == ISD::SHL) {
13328 // Make a large shift.
13329 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13330 MVT::v16i16, R, ShiftAmt,
13332 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13333 // Zero out the rightmost bits.
13334 SmallVector<SDValue, 32> V(32,
13335 DAG.getConstant(uint8_t(-1U << ShiftAmt),
13337 return DAG.getNode(ISD::AND, dl, VT, SHL,
13338 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
13340 if (Op.getOpcode() == ISD::SRL) {
13341 // Make a large shift.
13342 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13343 MVT::v16i16, R, ShiftAmt,
13345 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13346 // Zero out the leftmost bits.
13347 SmallVector<SDValue, 32> V(32,
13348 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13350 return DAG.getNode(ISD::AND, dl, VT, SRL,
13351 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
13353 if (Op.getOpcode() == ISD::SRA) {
13354 if (ShiftAmt == 7) {
13355 // R s>> 7 === R s< 0
13356 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13357 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13360 // R s>> a === ((R u>> a) ^ m) - m
13361 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13362 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
13364 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
13365 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13366 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13369 llvm_unreachable("Unknown shift opcode.");
13374 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13375 if (!Subtarget->is64Bit() &&
13376 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
13377 Amt.getOpcode() == ISD::BITCAST &&
13378 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13379 Amt = Amt.getOperand(0);
13380 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13381 VT.getVectorNumElements();
13382 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
13383 uint64_t ShiftAmt = 0;
13384 for (unsigned i = 0; i != Ratio; ++i) {
13385 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
13389 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
13391 // Check remaining shift amounts.
13392 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13393 uint64_t ShAmt = 0;
13394 for (unsigned j = 0; j != Ratio; ++j) {
13395 ConstantSDNode *C =
13396 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
13400 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
13402 if (ShAmt != ShiftAmt)
13405 switch (Op.getOpcode()) {
13407 llvm_unreachable("Unknown shift opcode!");
13409 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13412 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13415 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13423 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
13424 const X86Subtarget* Subtarget) {
13425 MVT VT = Op.getSimpleValueType();
13427 SDValue R = Op.getOperand(0);
13428 SDValue Amt = Op.getOperand(1);
13430 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
13431 VT == MVT::v4i32 || VT == MVT::v8i16 ||
13432 (Subtarget->hasInt256() &&
13433 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
13434 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13435 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13437 EVT EltVT = VT.getVectorElementType();
13439 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13440 unsigned NumElts = VT.getVectorNumElements();
13442 for (i = 0; i != NumElts; ++i) {
13443 if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
13447 for (j = i; j != NumElts; ++j) {
13448 SDValue Arg = Amt.getOperand(j);
13449 if (Arg.getOpcode() == ISD::UNDEF) continue;
13450 if (Arg != Amt.getOperand(i))
13453 if (i != NumElts && j == NumElts)
13454 BaseShAmt = Amt.getOperand(i);
13456 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13457 Amt = Amt.getOperand(0);
13458 if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
13459 cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
13460 SDValue InVec = Amt.getOperand(0);
13461 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13462 unsigned NumElts = InVec.getValueType().getVectorNumElements();
13464 for (; i != NumElts; ++i) {
13465 SDValue Arg = InVec.getOperand(i);
13466 if (Arg.getOpcode() == ISD::UNDEF) continue;
13470 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13471 if (ConstantSDNode *C =
13472 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13473 unsigned SplatIdx =
13474 cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
13475 if (C->getZExtValue() == SplatIdx)
13476 BaseShAmt = InVec.getOperand(1);
13479 if (!BaseShAmt.getNode())
13480 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
13481 DAG.getIntPtrConstant(0));
13485 if (BaseShAmt.getNode()) {
13486 if (EltVT.bitsGT(MVT::i32))
13487 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
13488 else if (EltVT.bitsLT(MVT::i32))
13489 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
13491 switch (Op.getOpcode()) {
13493 llvm_unreachable("Unknown shift opcode!");
13495 switch (VT.SimpleTy) {
13496 default: return SDValue();
13505 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
13508 switch (VT.SimpleTy) {
13509 default: return SDValue();
13516 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
13519 switch (VT.SimpleTy) {
13520 default: return SDValue();
13529 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
13535 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13536 if (!Subtarget->is64Bit() &&
13537 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
13538 (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
13539 Amt.getOpcode() == ISD::BITCAST &&
13540 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13541 Amt = Amt.getOperand(0);
13542 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13543 VT.getVectorNumElements();
13544 std::vector<SDValue> Vals(Ratio);
13545 for (unsigned i = 0; i != Ratio; ++i)
13546 Vals[i] = Amt.getOperand(i);
13547 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13548 for (unsigned j = 0; j != Ratio; ++j)
13549 if (Vals[j] != Amt.getOperand(i + j))
13552 switch (Op.getOpcode()) {
13554 llvm_unreachable("Unknown shift opcode!");
13556 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
13558 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
13560 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
13567 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
13568 SelectionDAG &DAG) {
13570 MVT VT = Op.getSimpleValueType();
13572 SDValue R = Op.getOperand(0);
13573 SDValue Amt = Op.getOperand(1);
13576 if (!Subtarget->hasSSE2())
13579 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
13583 V = LowerScalarVariableShift(Op, DAG, Subtarget);
13587 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
13589 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
13590 if (Subtarget->hasInt256()) {
13591 if (Op.getOpcode() == ISD::SRL &&
13592 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13593 VT == MVT::v4i64 || VT == MVT::v8i32))
13595 if (Op.getOpcode() == ISD::SHL &&
13596 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13597 VT == MVT::v4i64 || VT == MVT::v8i32))
13599 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
13603 // If possible, lower this packed shift into a vector multiply instead of
13604 // expanding it into a sequence of scalar shifts.
13605 // Do this only if the vector shift count is a constant build_vector.
13606 if (Op.getOpcode() == ISD::SHL &&
13607 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
13608 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
13609 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13610 SmallVector<SDValue, 8> Elts;
13611 EVT SVT = VT.getScalarType();
13612 unsigned SVTBits = SVT.getSizeInBits();
13613 const APInt &One = APInt(SVTBits, 1);
13614 unsigned NumElems = VT.getVectorNumElements();
13616 for (unsigned i=0; i !=NumElems; ++i) {
13617 SDValue Op = Amt->getOperand(i);
13618 if (Op->getOpcode() == ISD::UNDEF) {
13619 Elts.push_back(Op);
13623 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
13624 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
13625 uint64_t ShAmt = C.getZExtValue();
13626 if (ShAmt >= SVTBits) {
13627 Elts.push_back(DAG.getUNDEF(SVT));
13630 Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
13632 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Elts[0], NumElems);
13633 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
13636 // Lower SHL with variable shift amount.
13637 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
13638 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
13640 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
13641 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
13642 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
13643 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
13646 // If possible, lower this shift as a sequence of two shifts by
13647 // constant plus a MOVSS/MOVSD instead of scalarizing it.
13649 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
13651 // Could be rewritten as:
13652 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
13654 // The advantage is that the two shifts from the example would be
13655 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
13656 // the vector shift into four scalar shifts plus four pairs of vector
13658 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
13659 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13660 unsigned TargetOpcode = X86ISD::MOVSS;
13661 bool CanBeSimplified;
13662 // The splat value for the first packed shift (the 'X' from the example).
13663 SDValue Amt1 = Amt->getOperand(0);
13664 // The splat value for the second packed shift (the 'Y' from the example).
13665 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
13666 Amt->getOperand(2);
13668 // See if it is possible to replace this node with a sequence of
13669 // two shifts followed by a MOVSS/MOVSD
13670 if (VT == MVT::v4i32) {
13671 // Check if it is legal to use a MOVSS.
13672 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
13673 Amt2 == Amt->getOperand(3);
13674 if (!CanBeSimplified) {
13675 // Otherwise, check if we can still simplify this node using a MOVSD.
13676 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
13677 Amt->getOperand(2) == Amt->getOperand(3);
13678 TargetOpcode = X86ISD::MOVSD;
13679 Amt2 = Amt->getOperand(2);
13682 // Do similar checks for the case where the machine value type
13684 CanBeSimplified = Amt1 == Amt->getOperand(1);
13685 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
13686 CanBeSimplified = Amt2 == Amt->getOperand(i);
13688 if (!CanBeSimplified) {
13689 TargetOpcode = X86ISD::MOVSD;
13690 CanBeSimplified = true;
13691 Amt2 = Amt->getOperand(4);
13692 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
13693 CanBeSimplified = Amt1 == Amt->getOperand(i);
13694 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
13695 CanBeSimplified = Amt2 == Amt->getOperand(j);
13699 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
13700 isa<ConstantSDNode>(Amt2)) {
13701 // Replace this node with two shifts followed by a MOVSS/MOVSD.
13702 EVT CastVT = MVT::v4i32;
13704 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
13705 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
13707 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
13708 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
13709 if (TargetOpcode == X86ISD::MOVSD)
13710 CastVT = MVT::v2i64;
13711 SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
13712 SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
13713 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
13715 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13719 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
13720 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
13723 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
13724 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
13726 // Turn 'a' into a mask suitable for VSELECT
13727 SDValue VSelM = DAG.getConstant(0x80, VT);
13728 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13729 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13731 SDValue CM1 = DAG.getConstant(0x0f, VT);
13732 SDValue CM2 = DAG.getConstant(0x3f, VT);
13734 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
13735 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
13736 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
13737 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13738 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13741 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13742 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13743 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13745 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
13746 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
13747 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
13748 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13749 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13752 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13753 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13754 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13756 // return VSELECT(r, r+r, a);
13757 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
13758 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
13762 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
13763 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
13764 // solution better.
13765 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
13766 MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
13768 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
13769 R = DAG.getNode(ExtOpc, dl, NewVT, R);
13770 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
13771 return DAG.getNode(ISD::TRUNCATE, dl, VT,
13772 DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
13775 // Decompose 256-bit shifts into smaller 128-bit shifts.
13776 if (VT.is256BitVector()) {
13777 unsigned NumElems = VT.getVectorNumElements();
13778 MVT EltVT = VT.getVectorElementType();
13779 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13781 // Extract the two vectors
13782 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
13783 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
13785 // Recreate the shift amount vectors
13786 SDValue Amt1, Amt2;
13787 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13788 // Constant shift amount
13789 SmallVector<SDValue, 4> Amt1Csts;
13790 SmallVector<SDValue, 4> Amt2Csts;
13791 for (unsigned i = 0; i != NumElems/2; ++i)
13792 Amt1Csts.push_back(Amt->getOperand(i));
13793 for (unsigned i = NumElems/2; i != NumElems; ++i)
13794 Amt2Csts.push_back(Amt->getOperand(i));
13796 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
13797 &Amt1Csts[0], NumElems/2);
13798 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
13799 &Amt2Csts[0], NumElems/2);
13801 // Variable shift amount
13802 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
13803 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
13806 // Issue new vector shifts for the smaller types
13807 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
13808 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
13810 // Concatenate the result back
13811 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
13817 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
13818 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
13819 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
13820 // looks for this combo and may remove the "setcc" instruction if the "setcc"
13821 // has only one use.
13822 SDNode *N = Op.getNode();
13823 SDValue LHS = N->getOperand(0);
13824 SDValue RHS = N->getOperand(1);
13825 unsigned BaseOp = 0;
13828 switch (Op.getOpcode()) {
13829 default: llvm_unreachable("Unknown ovf instruction!");
13831 // A subtract of one will be selected as a INC. Note that INC doesn't
13832 // set CF, so we can't do this for UADDO.
13833 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13835 BaseOp = X86ISD::INC;
13836 Cond = X86::COND_O;
13839 BaseOp = X86ISD::ADD;
13840 Cond = X86::COND_O;
13843 BaseOp = X86ISD::ADD;
13844 Cond = X86::COND_B;
13847 // A subtract of one will be selected as a DEC. Note that DEC doesn't
13848 // set CF, so we can't do this for USUBO.
13849 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13851 BaseOp = X86ISD::DEC;
13852 Cond = X86::COND_O;
13855 BaseOp = X86ISD::SUB;
13856 Cond = X86::COND_O;
13859 BaseOp = X86ISD::SUB;
13860 Cond = X86::COND_B;
13863 BaseOp = X86ISD::SMUL;
13864 Cond = X86::COND_O;
13866 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
13867 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
13869 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
13872 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13873 DAG.getConstant(X86::COND_O, MVT::i32),
13874 SDValue(Sum.getNode(), 2));
13876 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13880 // Also sets EFLAGS.
13881 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
13882 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
13885 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
13886 DAG.getConstant(Cond, MVT::i32),
13887 SDValue(Sum.getNode(), 1));
13889 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13892 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
13893 SelectionDAG &DAG) const {
13895 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
13896 MVT VT = Op.getSimpleValueType();
13898 if (!Subtarget->hasSSE2() || !VT.isVector())
13901 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
13902 ExtraVT.getScalarType().getSizeInBits();
13904 switch (VT.SimpleTy) {
13905 default: return SDValue();
13908 if (!Subtarget->hasFp256())
13910 if (!Subtarget->hasInt256()) {
13911 // needs to be split
13912 unsigned NumElems = VT.getVectorNumElements();
13914 // Extract the LHS vectors
13915 SDValue LHS = Op.getOperand(0);
13916 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13917 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13919 MVT EltVT = VT.getVectorElementType();
13920 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13922 EVT ExtraEltVT = ExtraVT.getVectorElementType();
13923 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
13924 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
13926 SDValue Extra = DAG.getValueType(ExtraVT);
13928 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
13929 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
13931 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
13936 SDValue Op0 = Op.getOperand(0);
13937 SDValue Op00 = Op0.getOperand(0);
13939 // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
13940 if (Op0.getOpcode() == ISD::BITCAST &&
13941 Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
13942 // (sext (vzext x)) -> (vsext x)
13943 Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
13944 if (Tmp1.getNode()) {
13945 EVT ExtraEltVT = ExtraVT.getVectorElementType();
13946 // This folding is only valid when the in-reg type is a vector of i8,
13948 if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
13949 ExtraEltVT == MVT::i32) {
13950 SDValue Tmp1Op0 = Tmp1.getOperand(0);
13951 assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
13952 "This optimization is invalid without a VZEXT.");
13953 return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
13959 // If the above didn't work, then just use Shift-Left + Shift-Right.
13960 Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
13962 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
13968 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
13969 SelectionDAG &DAG) {
13971 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
13972 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
13973 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
13974 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
13976 // The only fence that needs an instruction is a sequentially-consistent
13977 // cross-thread fence.
13978 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
13979 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
13980 // no-sse2). There isn't any reason to disable it if the target processor
13982 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
13983 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
13985 SDValue Chain = Op.getOperand(0);
13986 SDValue Zero = DAG.getConstant(0, MVT::i32);
13988 DAG.getRegister(X86::ESP, MVT::i32), // Base
13989 DAG.getTargetConstant(1, MVT::i8), // Scale
13990 DAG.getRegister(0, MVT::i32), // Index
13991 DAG.getTargetConstant(0, MVT::i32), // Disp
13992 DAG.getRegister(0, MVT::i32), // Segment.
13996 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
13997 return SDValue(Res, 0);
14000 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
14001 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
14004 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
14005 SelectionDAG &DAG) {
14006 MVT T = Op.getSimpleValueType();
14010 switch(T.SimpleTy) {
14011 default: llvm_unreachable("Invalid value type!");
14012 case MVT::i8: Reg = X86::AL; size = 1; break;
14013 case MVT::i16: Reg = X86::AX; size = 2; break;
14014 case MVT::i32: Reg = X86::EAX; size = 4; break;
14016 assert(Subtarget->is64Bit() && "Node not type legal!");
14017 Reg = X86::RAX; size = 8;
14020 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
14021 Op.getOperand(2), SDValue());
14022 SDValue Ops[] = { cpIn.getValue(0),
14025 DAG.getTargetConstant(size, MVT::i8),
14026 cpIn.getValue(1) };
14027 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14028 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
14029 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
14030 Ops, array_lengthof(Ops), T, MMO);
14032 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
14036 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
14037 SelectionDAG &DAG) {
14038 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
14039 MVT DstVT = Op.getSimpleValueType();
14040 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
14041 Subtarget->hasMMX() && "Unexpected custom BITCAST");
14042 assert((DstVT == MVT::i64 ||
14043 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
14044 "Unexpected custom BITCAST");
14045 // i64 <=> MMX conversions are Legal.
14046 if (SrcVT==MVT::i64 && DstVT.isVector())
14048 if (DstVT==MVT::i64 && SrcVT.isVector())
14050 // MMX <=> MMX conversions are Legal.
14051 if (SrcVT.isVector() && DstVT.isVector())
14053 // All other conversions need to be expanded.
14057 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
14058 SDNode *Node = Op.getNode();
14060 EVT T = Node->getValueType(0);
14061 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
14062 DAG.getConstant(0, T), Node->getOperand(2));
14063 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
14064 cast<AtomicSDNode>(Node)->getMemoryVT(),
14065 Node->getOperand(0),
14066 Node->getOperand(1), negOp,
14067 cast<AtomicSDNode>(Node)->getMemOperand(),
14068 cast<AtomicSDNode>(Node)->getOrdering(),
14069 cast<AtomicSDNode>(Node)->getSynchScope());
14072 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
14073 SDNode *Node = Op.getNode();
14075 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14077 // Convert seq_cst store -> xchg
14078 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
14079 // FIXME: On 32-bit, store -> fist or movq would be more efficient
14080 // (The only way to get a 16-byte store is cmpxchg16b)
14081 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
14082 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
14083 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14084 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
14085 cast<AtomicSDNode>(Node)->getMemoryVT(),
14086 Node->getOperand(0),
14087 Node->getOperand(1), Node->getOperand(2),
14088 cast<AtomicSDNode>(Node)->getMemOperand(),
14089 cast<AtomicSDNode>(Node)->getOrdering(),
14090 cast<AtomicSDNode>(Node)->getSynchScope());
14091 return Swap.getValue(1);
14093 // Other atomic stores have a simple pattern.
14097 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
14098 EVT VT = Op.getNode()->getSimpleValueType(0);
14100 // Let legalize expand this if it isn't a legal type yet.
14101 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14104 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14107 bool ExtraOp = false;
14108 switch (Op.getOpcode()) {
14109 default: llvm_unreachable("Invalid code");
14110 case ISD::ADDC: Opc = X86ISD::ADD; break;
14111 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
14112 case ISD::SUBC: Opc = X86ISD::SUB; break;
14113 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
14117 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14119 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14120 Op.getOperand(1), Op.getOperand(2));
14123 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
14124 SelectionDAG &DAG) {
14125 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
14127 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
14128 // which returns the values as { float, float } (in XMM0) or
14129 // { double, double } (which is returned in XMM0, XMM1).
14131 SDValue Arg = Op.getOperand(0);
14132 EVT ArgVT = Arg.getValueType();
14133 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14135 TargetLowering::ArgListTy Args;
14136 TargetLowering::ArgListEntry Entry;
14140 Entry.isSExt = false;
14141 Entry.isZExt = false;
14142 Args.push_back(Entry);
14144 bool isF64 = ArgVT == MVT::f64;
14145 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
14146 // the small struct {f32, f32} is returned in (eax, edx). For f64,
14147 // the results are returned via SRet in memory.
14148 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
14149 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14150 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
14152 Type *RetTy = isF64
14153 ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
14154 : (Type*)VectorType::get(ArgTy, 4);
14156 CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
14157 false, false, false, false, 0,
14158 CallingConv::C, /*isTaillCall=*/false,
14159 /*doesNotRet=*/false, /*isReturnValueUsed*/true,
14160 Callee, Args, DAG, dl);
14161 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
14164 // Returned in xmm0 and xmm1.
14165 return CallResult.first;
14167 // Returned in bits 0:31 and 32:64 xmm0.
14168 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14169 CallResult.first, DAG.getIntPtrConstant(0));
14170 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14171 CallResult.first, DAG.getIntPtrConstant(1));
14172 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
14173 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
14176 /// LowerOperation - Provide custom lowering hooks for some operations.
14178 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
14179 switch (Op.getOpcode()) {
14180 default: llvm_unreachable("Should not custom lower this!");
14181 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
14182 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
14183 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op, Subtarget, DAG);
14184 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
14185 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
14186 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
14187 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
14188 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
14189 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
14190 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
14191 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
14192 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
14193 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
14194 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
14195 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
14196 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
14197 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
14198 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
14199 case ISD::SHL_PARTS:
14200 case ISD::SRA_PARTS:
14201 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
14202 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
14203 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
14204 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
14205 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
14206 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
14207 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
14208 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
14209 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
14210 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
14211 case ISD::FABS: return LowerFABS(Op, DAG);
14212 case ISD::FNEG: return LowerFNEG(Op, DAG);
14213 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
14214 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
14215 case ISD::SETCC: return LowerSETCC(Op, DAG);
14216 case ISD::SELECT: return LowerSELECT(Op, DAG);
14217 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
14218 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
14219 case ISD::VASTART: return LowerVASTART(Op, DAG);
14220 case ISD::VAARG: return LowerVAARG(Op, DAG);
14221 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
14222 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
14223 case ISD::INTRINSIC_VOID:
14224 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
14225 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
14226 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
14227 case ISD::FRAME_TO_ARGS_OFFSET:
14228 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
14229 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
14230 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
14231 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
14232 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
14233 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
14234 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
14235 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
14236 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
14237 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
14238 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
14239 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
14240 case ISD::UMUL_LOHI: return LowerUMUL_LOHI(Op, Subtarget, DAG);
14243 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
14249 case ISD::UMULO: return LowerXALUO(Op, DAG);
14250 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
14251 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
14255 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
14256 case ISD::ADD: return LowerADD(Op, DAG);
14257 case ISD::SUB: return LowerSUB(Op, DAG);
14258 case ISD::SDIV: return LowerSDIV(Op, DAG);
14259 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
14263 static void ReplaceATOMIC_LOAD(SDNode *Node,
14264 SmallVectorImpl<SDValue> &Results,
14265 SelectionDAG &DAG) {
14267 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14269 // Convert wide load -> cmpxchg8b/cmpxchg16b
14270 // FIXME: On 32-bit, load -> fild or movq would be more efficient
14271 // (The only way to get a 16-byte load is cmpxchg16b)
14272 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
14273 SDValue Zero = DAG.getConstant(0, VT);
14274 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
14275 Node->getOperand(0),
14276 Node->getOperand(1), Zero, Zero,
14277 cast<AtomicSDNode>(Node)->getMemOperand(),
14278 cast<AtomicSDNode>(Node)->getOrdering(),
14279 cast<AtomicSDNode>(Node)->getOrdering(),
14280 cast<AtomicSDNode>(Node)->getSynchScope());
14281 Results.push_back(Swap.getValue(0));
14282 Results.push_back(Swap.getValue(1));
14286 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
14287 SelectionDAG &DAG, unsigned NewOp) {
14289 assert (Node->getValueType(0) == MVT::i64 &&
14290 "Only know how to expand i64 atomics");
14292 SDValue Chain = Node->getOperand(0);
14293 SDValue In1 = Node->getOperand(1);
14294 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14295 Node->getOperand(2), DAG.getIntPtrConstant(0));
14296 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14297 Node->getOperand(2), DAG.getIntPtrConstant(1));
14298 SDValue Ops[] = { Chain, In1, In2L, In2H };
14299 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
14301 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, array_lengthof(Ops), MVT::i64,
14302 cast<MemSDNode>(Node)->getMemOperand());
14303 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
14304 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
14305 Results.push_back(Result.getValue(2));
14308 /// ReplaceNodeResults - Replace a node with an illegal result type
14309 /// with a new node built out of custom code.
14310 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
14311 SmallVectorImpl<SDValue>&Results,
14312 SelectionDAG &DAG) const {
14314 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14315 switch (N->getOpcode()) {
14317 llvm_unreachable("Do not know how to custom type legalize this operation!");
14318 case ISD::SIGN_EXTEND_INREG:
14323 // We don't want to expand or promote these.
14325 case ISD::FP_TO_SINT:
14326 case ISD::FP_TO_UINT: {
14327 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
14329 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
14332 std::pair<SDValue,SDValue> Vals =
14333 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
14334 SDValue FIST = Vals.first, StackSlot = Vals.second;
14335 if (FIST.getNode()) {
14336 EVT VT = N->getValueType(0);
14337 // Return a load from the stack slot.
14338 if (StackSlot.getNode())
14339 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
14340 MachinePointerInfo(),
14341 false, false, false, 0));
14343 Results.push_back(FIST);
14347 case ISD::UINT_TO_FP: {
14348 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14349 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
14350 N->getValueType(0) != MVT::v2f32)
14352 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
14354 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
14356 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
14357 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
14358 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
14359 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
14360 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
14361 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
14364 case ISD::FP_ROUND: {
14365 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
14367 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
14368 Results.push_back(V);
14371 case ISD::INTRINSIC_W_CHAIN: {
14372 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
14374 default : llvm_unreachable("Do not know how to custom type "
14375 "legalize this intrinsic operation!");
14376 case Intrinsic::x86_rdtsc:
14377 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14379 case Intrinsic::x86_rdtscp:
14380 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
14384 case ISD::READCYCLECOUNTER: {
14385 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14388 case ISD::ATOMIC_CMP_SWAP: {
14389 EVT T = N->getValueType(0);
14390 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
14391 bool Regs64bit = T == MVT::i128;
14392 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
14393 SDValue cpInL, cpInH;
14394 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14395 DAG.getConstant(0, HalfT));
14396 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14397 DAG.getConstant(1, HalfT));
14398 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
14399 Regs64bit ? X86::RAX : X86::EAX,
14401 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
14402 Regs64bit ? X86::RDX : X86::EDX,
14403 cpInH, cpInL.getValue(1));
14404 SDValue swapInL, swapInH;
14405 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14406 DAG.getConstant(0, HalfT));
14407 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14408 DAG.getConstant(1, HalfT));
14409 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
14410 Regs64bit ? X86::RBX : X86::EBX,
14411 swapInL, cpInH.getValue(1));
14412 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
14413 Regs64bit ? X86::RCX : X86::ECX,
14414 swapInH, swapInL.getValue(1));
14415 SDValue Ops[] = { swapInH.getValue(0),
14417 swapInH.getValue(1) };
14418 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14419 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
14420 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
14421 X86ISD::LCMPXCHG8_DAG;
14422 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
14423 Ops, array_lengthof(Ops), T, MMO);
14424 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
14425 Regs64bit ? X86::RAX : X86::EAX,
14426 HalfT, Result.getValue(1));
14427 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
14428 Regs64bit ? X86::RDX : X86::EDX,
14429 HalfT, cpOutL.getValue(2));
14430 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
14431 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
14432 Results.push_back(cpOutH.getValue(1));
14435 case ISD::ATOMIC_LOAD_ADD:
14436 case ISD::ATOMIC_LOAD_AND:
14437 case ISD::ATOMIC_LOAD_NAND:
14438 case ISD::ATOMIC_LOAD_OR:
14439 case ISD::ATOMIC_LOAD_SUB:
14440 case ISD::ATOMIC_LOAD_XOR:
14441 case ISD::ATOMIC_LOAD_MAX:
14442 case ISD::ATOMIC_LOAD_MIN:
14443 case ISD::ATOMIC_LOAD_UMAX:
14444 case ISD::ATOMIC_LOAD_UMIN:
14445 case ISD::ATOMIC_SWAP: {
14447 switch (N->getOpcode()) {
14448 default: llvm_unreachable("Unexpected opcode");
14449 case ISD::ATOMIC_LOAD_ADD:
14450 Opc = X86ISD::ATOMADD64_DAG;
14452 case ISD::ATOMIC_LOAD_AND:
14453 Opc = X86ISD::ATOMAND64_DAG;
14455 case ISD::ATOMIC_LOAD_NAND:
14456 Opc = X86ISD::ATOMNAND64_DAG;
14458 case ISD::ATOMIC_LOAD_OR:
14459 Opc = X86ISD::ATOMOR64_DAG;
14461 case ISD::ATOMIC_LOAD_SUB:
14462 Opc = X86ISD::ATOMSUB64_DAG;
14464 case ISD::ATOMIC_LOAD_XOR:
14465 Opc = X86ISD::ATOMXOR64_DAG;
14467 case ISD::ATOMIC_LOAD_MAX:
14468 Opc = X86ISD::ATOMMAX64_DAG;
14470 case ISD::ATOMIC_LOAD_MIN:
14471 Opc = X86ISD::ATOMMIN64_DAG;
14473 case ISD::ATOMIC_LOAD_UMAX:
14474 Opc = X86ISD::ATOMUMAX64_DAG;
14476 case ISD::ATOMIC_LOAD_UMIN:
14477 Opc = X86ISD::ATOMUMIN64_DAG;
14479 case ISD::ATOMIC_SWAP:
14480 Opc = X86ISD::ATOMSWAP64_DAG;
14483 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
14486 case ISD::ATOMIC_LOAD:
14487 ReplaceATOMIC_LOAD(N, Results, DAG);
14491 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
14493 default: return nullptr;
14494 case X86ISD::BSF: return "X86ISD::BSF";
14495 case X86ISD::BSR: return "X86ISD::BSR";
14496 case X86ISD::SHLD: return "X86ISD::SHLD";
14497 case X86ISD::SHRD: return "X86ISD::SHRD";
14498 case X86ISD::FAND: return "X86ISD::FAND";
14499 case X86ISD::FANDN: return "X86ISD::FANDN";
14500 case X86ISD::FOR: return "X86ISD::FOR";
14501 case X86ISD::FXOR: return "X86ISD::FXOR";
14502 case X86ISD::FSRL: return "X86ISD::FSRL";
14503 case X86ISD::FILD: return "X86ISD::FILD";
14504 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
14505 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
14506 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
14507 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
14508 case X86ISD::FLD: return "X86ISD::FLD";
14509 case X86ISD::FST: return "X86ISD::FST";
14510 case X86ISD::CALL: return "X86ISD::CALL";
14511 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
14512 case X86ISD::BT: return "X86ISD::BT";
14513 case X86ISD::CMP: return "X86ISD::CMP";
14514 case X86ISD::COMI: return "X86ISD::COMI";
14515 case X86ISD::UCOMI: return "X86ISD::UCOMI";
14516 case X86ISD::CMPM: return "X86ISD::CMPM";
14517 case X86ISD::CMPMU: return "X86ISD::CMPMU";
14518 case X86ISD::SETCC: return "X86ISD::SETCC";
14519 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
14520 case X86ISD::FSETCC: return "X86ISD::FSETCC";
14521 case X86ISD::CMOV: return "X86ISD::CMOV";
14522 case X86ISD::BRCOND: return "X86ISD::BRCOND";
14523 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
14524 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
14525 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
14526 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
14527 case X86ISD::Wrapper: return "X86ISD::Wrapper";
14528 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
14529 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
14530 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
14531 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
14532 case X86ISD::PINSRB: return "X86ISD::PINSRB";
14533 case X86ISD::PINSRW: return "X86ISD::PINSRW";
14534 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
14535 case X86ISD::ANDNP: return "X86ISD::ANDNP";
14536 case X86ISD::PSIGN: return "X86ISD::PSIGN";
14537 case X86ISD::BLENDV: return "X86ISD::BLENDV";
14538 case X86ISD::BLENDI: return "X86ISD::BLENDI";
14539 case X86ISD::SUBUS: return "X86ISD::SUBUS";
14540 case X86ISD::HADD: return "X86ISD::HADD";
14541 case X86ISD::HSUB: return "X86ISD::HSUB";
14542 case X86ISD::FHADD: return "X86ISD::FHADD";
14543 case X86ISD::FHSUB: return "X86ISD::FHSUB";
14544 case X86ISD::UMAX: return "X86ISD::UMAX";
14545 case X86ISD::UMIN: return "X86ISD::UMIN";
14546 case X86ISD::SMAX: return "X86ISD::SMAX";
14547 case X86ISD::SMIN: return "X86ISD::SMIN";
14548 case X86ISD::FMAX: return "X86ISD::FMAX";
14549 case X86ISD::FMIN: return "X86ISD::FMIN";
14550 case X86ISD::FMAXC: return "X86ISD::FMAXC";
14551 case X86ISD::FMINC: return "X86ISD::FMINC";
14552 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
14553 case X86ISD::FRCP: return "X86ISD::FRCP";
14554 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
14555 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
14556 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
14557 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
14558 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
14559 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
14560 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
14561 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
14562 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
14563 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
14564 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
14565 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
14566 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
14567 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
14568 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
14569 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
14570 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
14571 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
14572 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
14573 case X86ISD::VZEXT: return "X86ISD::VZEXT";
14574 case X86ISD::VSEXT: return "X86ISD::VSEXT";
14575 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
14576 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
14577 case X86ISD::VINSERT: return "X86ISD::VINSERT";
14578 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
14579 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
14580 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
14581 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
14582 case X86ISD::VSHL: return "X86ISD::VSHL";
14583 case X86ISD::VSRL: return "X86ISD::VSRL";
14584 case X86ISD::VSRA: return "X86ISD::VSRA";
14585 case X86ISD::VSHLI: return "X86ISD::VSHLI";
14586 case X86ISD::VSRLI: return "X86ISD::VSRLI";
14587 case X86ISD::VSRAI: return "X86ISD::VSRAI";
14588 case X86ISD::CMPP: return "X86ISD::CMPP";
14589 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
14590 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
14591 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
14592 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
14593 case X86ISD::ADD: return "X86ISD::ADD";
14594 case X86ISD::SUB: return "X86ISD::SUB";
14595 case X86ISD::ADC: return "X86ISD::ADC";
14596 case X86ISD::SBB: return "X86ISD::SBB";
14597 case X86ISD::SMUL: return "X86ISD::SMUL";
14598 case X86ISD::UMUL: return "X86ISD::UMUL";
14599 case X86ISD::INC: return "X86ISD::INC";
14600 case X86ISD::DEC: return "X86ISD::DEC";
14601 case X86ISD::OR: return "X86ISD::OR";
14602 case X86ISD::XOR: return "X86ISD::XOR";
14603 case X86ISD::AND: return "X86ISD::AND";
14604 case X86ISD::BEXTR: return "X86ISD::BEXTR";
14605 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
14606 case X86ISD::PTEST: return "X86ISD::PTEST";
14607 case X86ISD::TESTP: return "X86ISD::TESTP";
14608 case X86ISD::TESTM: return "X86ISD::TESTM";
14609 case X86ISD::TESTNM: return "X86ISD::TESTNM";
14610 case X86ISD::KORTEST: return "X86ISD::KORTEST";
14611 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
14612 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
14613 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
14614 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
14615 case X86ISD::SHUFP: return "X86ISD::SHUFP";
14616 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
14617 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
14618 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
14619 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
14620 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
14621 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
14622 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
14623 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
14624 case X86ISD::MOVSD: return "X86ISD::MOVSD";
14625 case X86ISD::MOVSS: return "X86ISD::MOVSS";
14626 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
14627 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
14628 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
14629 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
14630 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
14631 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
14632 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
14633 case X86ISD::VPERMV: return "X86ISD::VPERMV";
14634 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
14635 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
14636 case X86ISD::VPERMI: return "X86ISD::VPERMI";
14637 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
14638 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
14639 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
14640 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
14641 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
14642 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
14643 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
14644 case X86ISD::SAHF: return "X86ISD::SAHF";
14645 case X86ISD::RDRAND: return "X86ISD::RDRAND";
14646 case X86ISD::RDSEED: return "X86ISD::RDSEED";
14647 case X86ISD::FMADD: return "X86ISD::FMADD";
14648 case X86ISD::FMSUB: return "X86ISD::FMSUB";
14649 case X86ISD::FNMADD: return "X86ISD::FNMADD";
14650 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
14651 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
14652 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
14653 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
14654 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
14655 case X86ISD::XTEST: return "X86ISD::XTEST";
14659 // isLegalAddressingMode - Return true if the addressing mode represented
14660 // by AM is legal for this target, for a load/store of the specified type.
14661 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
14663 // X86 supports extremely general addressing modes.
14664 CodeModel::Model M = getTargetMachine().getCodeModel();
14665 Reloc::Model R = getTargetMachine().getRelocationModel();
14667 // X86 allows a sign-extended 32-bit immediate field as a displacement.
14668 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
14673 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
14675 // If a reference to this global requires an extra load, we can't fold it.
14676 if (isGlobalStubReference(GVFlags))
14679 // If BaseGV requires a register for the PIC base, we cannot also have a
14680 // BaseReg specified.
14681 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
14684 // If lower 4G is not available, then we must use rip-relative addressing.
14685 if ((M != CodeModel::Small || R != Reloc::Static) &&
14686 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
14690 switch (AM.Scale) {
14696 // These scales always work.
14701 // These scales are formed with basereg+scalereg. Only accept if there is
14706 default: // Other stuff never works.
14713 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
14714 unsigned Bits = Ty->getScalarSizeInBits();
14716 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
14717 // particularly cheaper than those without.
14721 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
14722 // variable shifts just as cheap as scalar ones.
14723 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
14726 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
14727 // fully general vector.
14731 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
14732 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14734 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
14735 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
14736 return NumBits1 > NumBits2;
14739 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
14740 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14743 if (!isTypeLegal(EVT::getEVT(Ty1)))
14746 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
14748 // Assuming the caller doesn't have a zeroext or signext return parameter,
14749 // truncation all the way down to i1 is valid.
14753 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
14754 return isInt<32>(Imm);
14757 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
14758 // Can also use sub to handle negated immediates.
14759 return isInt<32>(Imm);
14762 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
14763 if (!VT1.isInteger() || !VT2.isInteger())
14765 unsigned NumBits1 = VT1.getSizeInBits();
14766 unsigned NumBits2 = VT2.getSizeInBits();
14767 return NumBits1 > NumBits2;
14770 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
14771 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14772 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
14775 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
14776 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14777 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
14780 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14781 EVT VT1 = Val.getValueType();
14782 if (isZExtFree(VT1, VT2))
14785 if (Val.getOpcode() != ISD::LOAD)
14788 if (!VT1.isSimple() || !VT1.isInteger() ||
14789 !VT2.isSimple() || !VT2.isInteger())
14792 switch (VT1.getSimpleVT().SimpleTy) {
14797 // X86 has 8, 16, and 32-bit zero-extending loads.
14805 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
14806 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
14809 VT = VT.getScalarType();
14811 if (!VT.isSimple())
14814 switch (VT.getSimpleVT().SimpleTy) {
14825 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
14826 // i16 instructions are longer (0x66 prefix) and potentially slower.
14827 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
14830 /// isShuffleMaskLegal - Targets can use this to indicate that they only
14831 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
14832 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
14833 /// are assumed to be legal.
14835 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
14837 if (!VT.isSimple())
14840 MVT SVT = VT.getSimpleVT();
14842 // Very little shuffling can be done for 64-bit vectors right now.
14843 if (VT.getSizeInBits() == 64)
14846 // FIXME: pshufb, blends, shifts.
14847 return (SVT.getVectorNumElements() == 2 ||
14848 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
14849 isMOVLMask(M, SVT) ||
14850 isSHUFPMask(M, SVT) ||
14851 isPSHUFDMask(M, SVT) ||
14852 isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
14853 isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
14854 isPALIGNRMask(M, SVT, Subtarget) ||
14855 isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
14856 isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
14857 isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
14858 isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()));
14862 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
14864 if (!VT.isSimple())
14867 MVT SVT = VT.getSimpleVT();
14868 unsigned NumElts = SVT.getVectorNumElements();
14869 // FIXME: This collection of masks seems suspect.
14872 if (NumElts == 4 && SVT.is128BitVector()) {
14873 return (isMOVLMask(Mask, SVT) ||
14874 isCommutedMOVLMask(Mask, SVT, true) ||
14875 isSHUFPMask(Mask, SVT) ||
14876 isSHUFPMask(Mask, SVT, /* Commuted */ true));
14881 //===----------------------------------------------------------------------===//
14882 // X86 Scheduler Hooks
14883 //===----------------------------------------------------------------------===//
14885 /// Utility function to emit xbegin specifying the start of an RTM region.
14886 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
14887 const TargetInstrInfo *TII) {
14888 DebugLoc DL = MI->getDebugLoc();
14890 const BasicBlock *BB = MBB->getBasicBlock();
14891 MachineFunction::iterator I = MBB;
14894 // For the v = xbegin(), we generate
14905 MachineBasicBlock *thisMBB = MBB;
14906 MachineFunction *MF = MBB->getParent();
14907 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14908 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14909 MF->insert(I, mainMBB);
14910 MF->insert(I, sinkMBB);
14912 // Transfer the remainder of BB and its successor edges to sinkMBB.
14913 sinkMBB->splice(sinkMBB->begin(), MBB,
14914 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
14915 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14919 // # fallthrough to mainMBB
14920 // # abortion to sinkMBB
14921 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
14922 thisMBB->addSuccessor(mainMBB);
14923 thisMBB->addSuccessor(sinkMBB);
14927 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
14928 mainMBB->addSuccessor(sinkMBB);
14931 // EAX is live into the sinkMBB
14932 sinkMBB->addLiveIn(X86::EAX);
14933 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14934 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14937 MI->eraseFromParent();
14941 // Get CMPXCHG opcode for the specified data type.
14942 static unsigned getCmpXChgOpcode(EVT VT) {
14943 switch (VT.getSimpleVT().SimpleTy) {
14944 case MVT::i8: return X86::LCMPXCHG8;
14945 case MVT::i16: return X86::LCMPXCHG16;
14946 case MVT::i32: return X86::LCMPXCHG32;
14947 case MVT::i64: return X86::LCMPXCHG64;
14951 llvm_unreachable("Invalid operand size!");
14954 // Get LOAD opcode for the specified data type.
14955 static unsigned getLoadOpcode(EVT VT) {
14956 switch (VT.getSimpleVT().SimpleTy) {
14957 case MVT::i8: return X86::MOV8rm;
14958 case MVT::i16: return X86::MOV16rm;
14959 case MVT::i32: return X86::MOV32rm;
14960 case MVT::i64: return X86::MOV64rm;
14964 llvm_unreachable("Invalid operand size!");
14967 // Get opcode of the non-atomic one from the specified atomic instruction.
14968 static unsigned getNonAtomicOpcode(unsigned Opc) {
14970 case X86::ATOMAND8: return X86::AND8rr;
14971 case X86::ATOMAND16: return X86::AND16rr;
14972 case X86::ATOMAND32: return X86::AND32rr;
14973 case X86::ATOMAND64: return X86::AND64rr;
14974 case X86::ATOMOR8: return X86::OR8rr;
14975 case X86::ATOMOR16: return X86::OR16rr;
14976 case X86::ATOMOR32: return X86::OR32rr;
14977 case X86::ATOMOR64: return X86::OR64rr;
14978 case X86::ATOMXOR8: return X86::XOR8rr;
14979 case X86::ATOMXOR16: return X86::XOR16rr;
14980 case X86::ATOMXOR32: return X86::XOR32rr;
14981 case X86::ATOMXOR64: return X86::XOR64rr;
14983 llvm_unreachable("Unhandled atomic-load-op opcode!");
14986 // Get opcode of the non-atomic one from the specified atomic instruction with
14988 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
14989 unsigned &ExtraOpc) {
14991 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr;
14992 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr;
14993 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr;
14994 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr;
14995 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr;
14996 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
14997 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
14998 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
14999 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr;
15000 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
15001 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
15002 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
15003 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr;
15004 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
15005 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
15006 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
15007 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr;
15008 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
15009 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
15010 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
15012 llvm_unreachable("Unhandled atomic-load-op opcode!");
15015 // Get opcode of the non-atomic one from the specified atomic instruction for
15016 // 64-bit data type on 32-bit target.
15017 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
15019 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr;
15020 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr;
15021 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr;
15022 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr;
15023 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr;
15024 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
15025 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr;
15026 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr;
15027 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr;
15028 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr;
15030 llvm_unreachable("Unhandled atomic-load-op opcode!");
15033 // Get opcode of the non-atomic one from the specified atomic instruction for
15034 // 64-bit data type on 32-bit target with extra opcode.
15035 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
15037 unsigned &ExtraOpc) {
15039 case X86::ATOMNAND6432:
15040 ExtraOpc = X86::NOT32r;
15041 HiOpc = X86::AND32rr;
15042 return X86::AND32rr;
15044 llvm_unreachable("Unhandled atomic-load-op opcode!");
15047 // Get pseudo CMOV opcode from the specified data type.
15048 static unsigned getPseudoCMOVOpc(EVT VT) {
15049 switch (VT.getSimpleVT().SimpleTy) {
15050 case MVT::i8: return X86::CMOV_GR8;
15051 case MVT::i16: return X86::CMOV_GR16;
15052 case MVT::i32: return X86::CMOV_GR32;
15056 llvm_unreachable("Unknown CMOV opcode!");
15059 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
15060 // They will be translated into a spin-loop or compare-exchange loop from
15063 // dst = atomic-fetch-op MI.addr, MI.val
15069 // t1 = LOAD MI.addr
15071 // t4 = phi(t1, t3 / loop)
15072 // t2 = OP MI.val, t4
15074 // LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
15080 MachineBasicBlock *
15081 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
15082 MachineBasicBlock *MBB) const {
15083 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15084 DebugLoc DL = MI->getDebugLoc();
15086 MachineFunction *MF = MBB->getParent();
15087 MachineRegisterInfo &MRI = MF->getRegInfo();
15089 const BasicBlock *BB = MBB->getBasicBlock();
15090 MachineFunction::iterator I = MBB;
15093 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
15094 "Unexpected number of operands");
15096 assert(MI->hasOneMemOperand() &&
15097 "Expected atomic-load-op to have one memoperand");
15099 // Memory Reference
15100 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15101 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15103 unsigned DstReg, SrcReg;
15104 unsigned MemOpndSlot;
15106 unsigned CurOp = 0;
15108 DstReg = MI->getOperand(CurOp++).getReg();
15109 MemOpndSlot = CurOp;
15110 CurOp += X86::AddrNumOperands;
15111 SrcReg = MI->getOperand(CurOp++).getReg();
15113 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15114 MVT::SimpleValueType VT = *RC->vt_begin();
15115 unsigned t1 = MRI.createVirtualRegister(RC);
15116 unsigned t2 = MRI.createVirtualRegister(RC);
15117 unsigned t3 = MRI.createVirtualRegister(RC);
15118 unsigned t4 = MRI.createVirtualRegister(RC);
15119 unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
15121 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
15122 unsigned LOADOpc = getLoadOpcode(VT);
15124 // For the atomic load-arith operator, we generate
15127 // t1 = LOAD [MI.addr]
15129 // t4 = phi(t1 / thisMBB, t3 / mainMBB)
15130 // t1 = OP MI.val, EAX
15132 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
15138 MachineBasicBlock *thisMBB = MBB;
15139 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15140 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15141 MF->insert(I, mainMBB);
15142 MF->insert(I, sinkMBB);
15144 MachineInstrBuilder MIB;
15146 // Transfer the remainder of BB and its successor edges to sinkMBB.
15147 sinkMBB->splice(sinkMBB->begin(), MBB,
15148 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15149 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15152 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
15153 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15154 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15156 NewMO.setIsKill(false);
15157 MIB.addOperand(NewMO);
15159 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15160 unsigned flags = (*MMOI)->getFlags();
15161 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15162 MachineMemOperand *MMO =
15163 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15164 (*MMOI)->getSize(),
15165 (*MMOI)->getBaseAlignment(),
15166 (*MMOI)->getTBAAInfo(),
15167 (*MMOI)->getRanges());
15168 MIB.addMemOperand(MMO);
15171 thisMBB->addSuccessor(mainMBB);
15174 MachineBasicBlock *origMainMBB = mainMBB;
15177 MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
15178 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15180 unsigned Opc = MI->getOpcode();
15183 llvm_unreachable("Unhandled atomic-load-op opcode!");
15184 case X86::ATOMAND8:
15185 case X86::ATOMAND16:
15186 case X86::ATOMAND32:
15187 case X86::ATOMAND64:
15189 case X86::ATOMOR16:
15190 case X86::ATOMOR32:
15191 case X86::ATOMOR64:
15192 case X86::ATOMXOR8:
15193 case X86::ATOMXOR16:
15194 case X86::ATOMXOR32:
15195 case X86::ATOMXOR64: {
15196 unsigned ARITHOpc = getNonAtomicOpcode(Opc);
15197 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
15201 case X86::ATOMNAND8:
15202 case X86::ATOMNAND16:
15203 case X86::ATOMNAND32:
15204 case X86::ATOMNAND64: {
15205 unsigned Tmp = MRI.createVirtualRegister(RC);
15207 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
15208 BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
15210 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
15213 case X86::ATOMMAX8:
15214 case X86::ATOMMAX16:
15215 case X86::ATOMMAX32:
15216 case X86::ATOMMAX64:
15217 case X86::ATOMMIN8:
15218 case X86::ATOMMIN16:
15219 case X86::ATOMMIN32:
15220 case X86::ATOMMIN64:
15221 case X86::ATOMUMAX8:
15222 case X86::ATOMUMAX16:
15223 case X86::ATOMUMAX32:
15224 case X86::ATOMUMAX64:
15225 case X86::ATOMUMIN8:
15226 case X86::ATOMUMIN16:
15227 case X86::ATOMUMIN32:
15228 case X86::ATOMUMIN64: {
15230 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
15232 BuildMI(mainMBB, DL, TII->get(CMPOpc))
15236 if (Subtarget->hasCMov()) {
15237 if (VT != MVT::i8) {
15239 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
15243 // Promote i8 to i32 to use CMOV32
15244 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15245 const TargetRegisterClass *RC32 =
15246 TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
15247 unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
15248 unsigned AccReg32 = MRI.createVirtualRegister(RC32);
15249 unsigned Tmp = MRI.createVirtualRegister(RC32);
15251 unsigned Undef = MRI.createVirtualRegister(RC32);
15252 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
15254 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
15257 .addImm(X86::sub_8bit);
15258 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
15261 .addImm(X86::sub_8bit);
15263 BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
15267 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
15268 .addReg(Tmp, 0, X86::sub_8bit);
15271 // Use pseudo select and lower them.
15272 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
15273 "Invalid atomic-load-op transformation!");
15274 unsigned SelOpc = getPseudoCMOVOpc(VT);
15275 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
15276 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
15277 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
15278 .addReg(SrcReg).addReg(t4)
15280 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15281 // Replace the original PHI node as mainMBB is changed after CMOV
15283 BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
15284 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15285 Phi->eraseFromParent();
15291 // Copy PhyReg back from virtual register.
15292 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
15295 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15296 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15297 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15299 NewMO.setIsKill(false);
15300 MIB.addOperand(NewMO);
15303 MIB.setMemRefs(MMOBegin, MMOEnd);
15305 // Copy PhyReg back to virtual register.
15306 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
15309 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15311 mainMBB->addSuccessor(origMainMBB);
15312 mainMBB->addSuccessor(sinkMBB);
15315 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15316 TII->get(TargetOpcode::COPY), DstReg)
15319 MI->eraseFromParent();
15323 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
15324 // instructions. They will be translated into a spin-loop or compare-exchange
15328 // dst = atomic-fetch-op MI.addr, MI.val
15334 // t1L = LOAD [MI.addr + 0]
15335 // t1H = LOAD [MI.addr + 4]
15337 // t4L = phi(t1L, t3L / loop)
15338 // t4H = phi(t1H, t3H / loop)
15339 // t2L = OP MI.val.lo, t4L
15340 // t2H = OP MI.val.hi, t4H
15345 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15353 MachineBasicBlock *
15354 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
15355 MachineBasicBlock *MBB) const {
15356 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15357 DebugLoc DL = MI->getDebugLoc();
15359 MachineFunction *MF = MBB->getParent();
15360 MachineRegisterInfo &MRI = MF->getRegInfo();
15362 const BasicBlock *BB = MBB->getBasicBlock();
15363 MachineFunction::iterator I = MBB;
15366 assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
15367 "Unexpected number of operands");
15369 assert(MI->hasOneMemOperand() &&
15370 "Expected atomic-load-op32 to have one memoperand");
15372 // Memory Reference
15373 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15374 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15376 unsigned DstLoReg, DstHiReg;
15377 unsigned SrcLoReg, SrcHiReg;
15378 unsigned MemOpndSlot;
15380 unsigned CurOp = 0;
15382 DstLoReg = MI->getOperand(CurOp++).getReg();
15383 DstHiReg = MI->getOperand(CurOp++).getReg();
15384 MemOpndSlot = CurOp;
15385 CurOp += X86::AddrNumOperands;
15386 SrcLoReg = MI->getOperand(CurOp++).getReg();
15387 SrcHiReg = MI->getOperand(CurOp++).getReg();
15389 const TargetRegisterClass *RC = &X86::GR32RegClass;
15390 const TargetRegisterClass *RC8 = &X86::GR8RegClass;
15392 unsigned t1L = MRI.createVirtualRegister(RC);
15393 unsigned t1H = MRI.createVirtualRegister(RC);
15394 unsigned t2L = MRI.createVirtualRegister(RC);
15395 unsigned t2H = MRI.createVirtualRegister(RC);
15396 unsigned t3L = MRI.createVirtualRegister(RC);
15397 unsigned t3H = MRI.createVirtualRegister(RC);
15398 unsigned t4L = MRI.createVirtualRegister(RC);
15399 unsigned t4H = MRI.createVirtualRegister(RC);
15401 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
15402 unsigned LOADOpc = X86::MOV32rm;
15404 // For the atomic load-arith operator, we generate
15407 // t1L = LOAD [MI.addr + 0]
15408 // t1H = LOAD [MI.addr + 4]
15410 // t4L = phi(t1L / thisMBB, t3L / mainMBB)
15411 // t4H = phi(t1H / thisMBB, t3H / mainMBB)
15412 // t2L = OP MI.val.lo, t4L
15413 // t2H = OP MI.val.hi, t4H
15416 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15424 MachineBasicBlock *thisMBB = MBB;
15425 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15426 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15427 MF->insert(I, mainMBB);
15428 MF->insert(I, sinkMBB);
15430 MachineInstrBuilder MIB;
15432 // Transfer the remainder of BB and its successor edges to sinkMBB.
15433 sinkMBB->splice(sinkMBB->begin(), MBB,
15434 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15435 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15439 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
15440 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15441 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15443 NewMO.setIsKill(false);
15444 MIB.addOperand(NewMO);
15446 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15447 unsigned flags = (*MMOI)->getFlags();
15448 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15449 MachineMemOperand *MMO =
15450 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15451 (*MMOI)->getSize(),
15452 (*MMOI)->getBaseAlignment(),
15453 (*MMOI)->getTBAAInfo(),
15454 (*MMOI)->getRanges());
15455 MIB.addMemOperand(MMO);
15457 MachineInstr *LowMI = MIB;
15460 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
15461 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15462 if (i == X86::AddrDisp) {
15463 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
15465 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15467 NewMO.setIsKill(false);
15468 MIB.addOperand(NewMO);
15471 MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
15473 thisMBB->addSuccessor(mainMBB);
15476 MachineBasicBlock *origMainMBB = mainMBB;
15479 MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
15480 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15481 MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
15482 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15484 unsigned Opc = MI->getOpcode();
15487 llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
15488 case X86::ATOMAND6432:
15489 case X86::ATOMOR6432:
15490 case X86::ATOMXOR6432:
15491 case X86::ATOMADD6432:
15492 case X86::ATOMSUB6432: {
15494 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15495 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
15497 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
15501 case X86::ATOMNAND6432: {
15502 unsigned HiOpc, NOTOpc;
15503 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
15504 unsigned TmpL = MRI.createVirtualRegister(RC);
15505 unsigned TmpH = MRI.createVirtualRegister(RC);
15506 BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
15508 BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
15510 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
15511 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
15514 case X86::ATOMMAX6432:
15515 case X86::ATOMMIN6432:
15516 case X86::ATOMUMAX6432:
15517 case X86::ATOMUMIN6432: {
15519 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15520 unsigned cL = MRI.createVirtualRegister(RC8);
15521 unsigned cH = MRI.createVirtualRegister(RC8);
15522 unsigned cL32 = MRI.createVirtualRegister(RC);
15523 unsigned cH32 = MRI.createVirtualRegister(RC);
15524 unsigned cc = MRI.createVirtualRegister(RC);
15525 // cl := cmp src_lo, lo
15526 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15527 .addReg(SrcLoReg).addReg(t4L);
15528 BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
15529 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
15530 // ch := cmp src_hi, hi
15531 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15532 .addReg(SrcHiReg).addReg(t4H);
15533 BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
15534 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
15535 // cc := if (src_hi == hi) ? cl : ch;
15536 if (Subtarget->hasCMov()) {
15537 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
15538 .addReg(cH32).addReg(cL32);
15540 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
15541 .addReg(cH32).addReg(cL32)
15542 .addImm(X86::COND_E);
15543 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15545 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
15546 if (Subtarget->hasCMov()) {
15547 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
15548 .addReg(SrcLoReg).addReg(t4L);
15549 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
15550 .addReg(SrcHiReg).addReg(t4H);
15552 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
15553 .addReg(SrcLoReg).addReg(t4L)
15554 .addImm(X86::COND_NE);
15555 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15556 // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
15557 // 2nd CMOV lowering.
15558 mainMBB->addLiveIn(X86::EFLAGS);
15559 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
15560 .addReg(SrcHiReg).addReg(t4H)
15561 .addImm(X86::COND_NE);
15562 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15563 // Replace the original PHI node as mainMBB is changed after CMOV
15565 BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
15566 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15567 BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
15568 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15569 PhiL->eraseFromParent();
15570 PhiH->eraseFromParent();
15574 case X86::ATOMSWAP6432: {
15576 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15577 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
15578 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
15583 // Copy EDX:EAX back from HiReg:LoReg
15584 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
15585 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
15586 // Copy ECX:EBX from t1H:t1L
15587 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
15588 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
15590 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15591 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15592 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15594 NewMO.setIsKill(false);
15595 MIB.addOperand(NewMO);
15597 MIB.setMemRefs(MMOBegin, MMOEnd);
15599 // Copy EDX:EAX back to t3H:t3L
15600 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
15601 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
15603 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15605 mainMBB->addSuccessor(origMainMBB);
15606 mainMBB->addSuccessor(sinkMBB);
15609 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15610 TII->get(TargetOpcode::COPY), DstLoReg)
15612 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15613 TII->get(TargetOpcode::COPY), DstHiReg)
15616 MI->eraseFromParent();
15620 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
15621 // or XMM0_V32I8 in AVX all of this code can be replaced with that
15622 // in the .td file.
15623 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
15624 const TargetInstrInfo *TII) {
15626 switch (MI->getOpcode()) {
15627 default: llvm_unreachable("illegal opcode!");
15628 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
15629 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
15630 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
15631 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
15632 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
15633 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
15634 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
15635 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
15638 DebugLoc dl = MI->getDebugLoc();
15639 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15641 unsigned NumArgs = MI->getNumOperands();
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())
15652 .addReg(X86::XMM0);
15654 MI->eraseFromParent();
15658 // FIXME: Custom handling because TableGen doesn't support multiple implicit
15659 // defs in an instruction pattern
15660 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
15661 const TargetInstrInfo *TII) {
15663 switch (MI->getOpcode()) {
15664 default: llvm_unreachable("illegal opcode!");
15665 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
15666 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
15667 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
15668 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
15669 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
15670 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
15671 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
15672 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
15675 DebugLoc dl = MI->getDebugLoc();
15676 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15678 unsigned NumArgs = MI->getNumOperands(); // remove the results
15679 for (unsigned i = 1; i < NumArgs; ++i) {
15680 MachineOperand &Op = MI->getOperand(i);
15681 if (!(Op.isReg() && Op.isImplicit()))
15682 MIB.addOperand(Op);
15684 if (MI->hasOneMemOperand())
15685 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15687 BuildMI(*BB, MI, dl,
15688 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15691 MI->eraseFromParent();
15695 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
15696 const TargetInstrInfo *TII,
15697 const X86Subtarget* Subtarget) {
15698 DebugLoc dl = MI->getDebugLoc();
15700 // Address into RAX/EAX, other two args into ECX, EDX.
15701 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
15702 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
15703 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
15704 for (int i = 0; i < X86::AddrNumOperands; ++i)
15705 MIB.addOperand(MI->getOperand(i));
15707 unsigned ValOps = X86::AddrNumOperands;
15708 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
15709 .addReg(MI->getOperand(ValOps).getReg());
15710 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
15711 .addReg(MI->getOperand(ValOps+1).getReg());
15713 // The instruction doesn't actually take any operands though.
15714 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
15716 MI->eraseFromParent(); // The pseudo is gone now.
15720 MachineBasicBlock *
15721 X86TargetLowering::EmitVAARG64WithCustomInserter(
15723 MachineBasicBlock *MBB) const {
15724 // Emit va_arg instruction on X86-64.
15726 // Operands to this pseudo-instruction:
15727 // 0 ) Output : destination address (reg)
15728 // 1-5) Input : va_list address (addr, i64mem)
15729 // 6 ) ArgSize : Size (in bytes) of vararg type
15730 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
15731 // 8 ) Align : Alignment of type
15732 // 9 ) EFLAGS (implicit-def)
15734 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
15735 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
15737 unsigned DestReg = MI->getOperand(0).getReg();
15738 MachineOperand &Base = MI->getOperand(1);
15739 MachineOperand &Scale = MI->getOperand(2);
15740 MachineOperand &Index = MI->getOperand(3);
15741 MachineOperand &Disp = MI->getOperand(4);
15742 MachineOperand &Segment = MI->getOperand(5);
15743 unsigned ArgSize = MI->getOperand(6).getImm();
15744 unsigned ArgMode = MI->getOperand(7).getImm();
15745 unsigned Align = MI->getOperand(8).getImm();
15747 // Memory Reference
15748 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
15749 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15750 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15752 // Machine Information
15753 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15754 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
15755 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
15756 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
15757 DebugLoc DL = MI->getDebugLoc();
15759 // struct va_list {
15762 // i64 overflow_area (address)
15763 // i64 reg_save_area (address)
15765 // sizeof(va_list) = 24
15766 // alignment(va_list) = 8
15768 unsigned TotalNumIntRegs = 6;
15769 unsigned TotalNumXMMRegs = 8;
15770 bool UseGPOffset = (ArgMode == 1);
15771 bool UseFPOffset = (ArgMode == 2);
15772 unsigned MaxOffset = TotalNumIntRegs * 8 +
15773 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
15775 /* Align ArgSize to a multiple of 8 */
15776 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
15777 bool NeedsAlign = (Align > 8);
15779 MachineBasicBlock *thisMBB = MBB;
15780 MachineBasicBlock *overflowMBB;
15781 MachineBasicBlock *offsetMBB;
15782 MachineBasicBlock *endMBB;
15784 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
15785 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
15786 unsigned OffsetReg = 0;
15788 if (!UseGPOffset && !UseFPOffset) {
15789 // If we only pull from the overflow region, we don't create a branch.
15790 // We don't need to alter control flow.
15791 OffsetDestReg = 0; // unused
15792 OverflowDestReg = DestReg;
15794 offsetMBB = nullptr;
15795 overflowMBB = thisMBB;
15798 // First emit code to check if gp_offset (or fp_offset) is below the bound.
15799 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
15800 // If not, pull from overflow_area. (branch to overflowMBB)
15805 // offsetMBB overflowMBB
15810 // Registers for the PHI in endMBB
15811 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
15812 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
15814 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15815 MachineFunction *MF = MBB->getParent();
15816 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15817 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15818 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15820 MachineFunction::iterator MBBIter = MBB;
15823 // Insert the new basic blocks
15824 MF->insert(MBBIter, offsetMBB);
15825 MF->insert(MBBIter, overflowMBB);
15826 MF->insert(MBBIter, endMBB);
15828 // Transfer the remainder of MBB and its successor edges to endMBB.
15829 endMBB->splice(endMBB->begin(), thisMBB,
15830 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
15831 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
15833 // Make offsetMBB and overflowMBB successors of thisMBB
15834 thisMBB->addSuccessor(offsetMBB);
15835 thisMBB->addSuccessor(overflowMBB);
15837 // endMBB is a successor of both offsetMBB and overflowMBB
15838 offsetMBB->addSuccessor(endMBB);
15839 overflowMBB->addSuccessor(endMBB);
15841 // Load the offset value into a register
15842 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15843 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
15847 .addDisp(Disp, UseFPOffset ? 4 : 0)
15848 .addOperand(Segment)
15849 .setMemRefs(MMOBegin, MMOEnd);
15851 // Check if there is enough room left to pull this argument.
15852 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
15854 .addImm(MaxOffset + 8 - ArgSizeA8);
15856 // Branch to "overflowMBB" if offset >= max
15857 // Fall through to "offsetMBB" otherwise
15858 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
15859 .addMBB(overflowMBB);
15862 // In offsetMBB, emit code to use the reg_save_area.
15864 assert(OffsetReg != 0);
15866 // Read the reg_save_area address.
15867 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
15868 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
15873 .addOperand(Segment)
15874 .setMemRefs(MMOBegin, MMOEnd);
15876 // Zero-extend the offset
15877 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
15878 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
15881 .addImm(X86::sub_32bit);
15883 // Add the offset to the reg_save_area to get the final address.
15884 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
15885 .addReg(OffsetReg64)
15886 .addReg(RegSaveReg);
15888 // Compute the offset for the next argument
15889 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15890 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
15892 .addImm(UseFPOffset ? 16 : 8);
15894 // Store it back into the va_list.
15895 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
15899 .addDisp(Disp, UseFPOffset ? 4 : 0)
15900 .addOperand(Segment)
15901 .addReg(NextOffsetReg)
15902 .setMemRefs(MMOBegin, MMOEnd);
15905 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
15910 // Emit code to use overflow area
15913 // Load the overflow_area address into a register.
15914 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
15915 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
15920 .addOperand(Segment)
15921 .setMemRefs(MMOBegin, MMOEnd);
15923 // If we need to align it, do so. Otherwise, just copy the address
15924 // to OverflowDestReg.
15926 // Align the overflow address
15927 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
15928 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
15930 // aligned_addr = (addr + (align-1)) & ~(align-1)
15931 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
15932 .addReg(OverflowAddrReg)
15935 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
15937 .addImm(~(uint64_t)(Align-1));
15939 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
15940 .addReg(OverflowAddrReg);
15943 // Compute the next overflow address after this argument.
15944 // (the overflow address should be kept 8-byte aligned)
15945 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
15946 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
15947 .addReg(OverflowDestReg)
15948 .addImm(ArgSizeA8);
15950 // Store the new overflow address.
15951 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
15956 .addOperand(Segment)
15957 .addReg(NextAddrReg)
15958 .setMemRefs(MMOBegin, MMOEnd);
15960 // If we branched, emit the PHI to the front of endMBB.
15962 BuildMI(*endMBB, endMBB->begin(), DL,
15963 TII->get(X86::PHI), DestReg)
15964 .addReg(OffsetDestReg).addMBB(offsetMBB)
15965 .addReg(OverflowDestReg).addMBB(overflowMBB);
15968 // Erase the pseudo instruction
15969 MI->eraseFromParent();
15974 MachineBasicBlock *
15975 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
15977 MachineBasicBlock *MBB) const {
15978 // Emit code to save XMM registers to the stack. The ABI says that the
15979 // number of registers to save is given in %al, so it's theoretically
15980 // possible to do an indirect jump trick to avoid saving all of them,
15981 // however this code takes a simpler approach and just executes all
15982 // of the stores if %al is non-zero. It's less code, and it's probably
15983 // easier on the hardware branch predictor, and stores aren't all that
15984 // expensive anyway.
15986 // Create the new basic blocks. One block contains all the XMM stores,
15987 // and one block is the final destination regardless of whether any
15988 // stores were performed.
15989 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15990 MachineFunction *F = MBB->getParent();
15991 MachineFunction::iterator MBBIter = MBB;
15993 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
15994 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
15995 F->insert(MBBIter, XMMSaveMBB);
15996 F->insert(MBBIter, EndMBB);
15998 // Transfer the remainder of MBB and its successor edges to EndMBB.
15999 EndMBB->splice(EndMBB->begin(), MBB,
16000 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16001 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
16003 // The original block will now fall through to the XMM save block.
16004 MBB->addSuccessor(XMMSaveMBB);
16005 // The XMMSaveMBB will fall through to the end block.
16006 XMMSaveMBB->addSuccessor(EndMBB);
16008 // Now add the instructions.
16009 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16010 DebugLoc DL = MI->getDebugLoc();
16012 unsigned CountReg = MI->getOperand(0).getReg();
16013 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
16014 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
16016 if (!Subtarget->isTargetWin64()) {
16017 // If %al is 0, branch around the XMM save block.
16018 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
16019 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
16020 MBB->addSuccessor(EndMBB);
16023 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
16024 // that was just emitted, but clearly shouldn't be "saved".
16025 assert((MI->getNumOperands() <= 3 ||
16026 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
16027 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
16028 && "Expected last argument to be EFLAGS");
16029 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
16030 // In the XMM save block, save all the XMM argument registers.
16031 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
16032 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
16033 MachineMemOperand *MMO =
16034 F->getMachineMemOperand(
16035 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
16036 MachineMemOperand::MOStore,
16037 /*Size=*/16, /*Align=*/16);
16038 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
16039 .addFrameIndex(RegSaveFrameIndex)
16040 .addImm(/*Scale=*/1)
16041 .addReg(/*IndexReg=*/0)
16042 .addImm(/*Disp=*/Offset)
16043 .addReg(/*Segment=*/0)
16044 .addReg(MI->getOperand(i).getReg())
16045 .addMemOperand(MMO);
16048 MI->eraseFromParent(); // The pseudo instruction is gone now.
16053 // The EFLAGS operand of SelectItr might be missing a kill marker
16054 // because there were multiple uses of EFLAGS, and ISel didn't know
16055 // which to mark. Figure out whether SelectItr should have had a
16056 // kill marker, and set it if it should. Returns the correct kill
16058 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
16059 MachineBasicBlock* BB,
16060 const TargetRegisterInfo* TRI) {
16061 // Scan forward through BB for a use/def of EFLAGS.
16062 MachineBasicBlock::iterator miI(std::next(SelectItr));
16063 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
16064 const MachineInstr& mi = *miI;
16065 if (mi.readsRegister(X86::EFLAGS))
16067 if (mi.definesRegister(X86::EFLAGS))
16068 break; // Should have kill-flag - update below.
16071 // If we hit the end of the block, check whether EFLAGS is live into a
16073 if (miI == BB->end()) {
16074 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
16075 sEnd = BB->succ_end();
16076 sItr != sEnd; ++sItr) {
16077 MachineBasicBlock* succ = *sItr;
16078 if (succ->isLiveIn(X86::EFLAGS))
16083 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
16084 // out. SelectMI should have a kill flag on EFLAGS.
16085 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
16089 MachineBasicBlock *
16090 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
16091 MachineBasicBlock *BB) const {
16092 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16093 DebugLoc DL = MI->getDebugLoc();
16095 // To "insert" a SELECT_CC instruction, we actually have to insert the
16096 // diamond control-flow pattern. The incoming instruction knows the
16097 // destination vreg to set, the condition code register to branch on, the
16098 // true/false values to select between, and a branch opcode to use.
16099 const BasicBlock *LLVM_BB = BB->getBasicBlock();
16100 MachineFunction::iterator It = BB;
16106 // cmpTY ccX, r1, r2
16108 // fallthrough --> copy0MBB
16109 MachineBasicBlock *thisMBB = BB;
16110 MachineFunction *F = BB->getParent();
16111 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
16112 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
16113 F->insert(It, copy0MBB);
16114 F->insert(It, sinkMBB);
16116 // If the EFLAGS register isn't dead in the terminator, then claim that it's
16117 // live into the sink and copy blocks.
16118 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
16119 if (!MI->killsRegister(X86::EFLAGS) &&
16120 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
16121 copy0MBB->addLiveIn(X86::EFLAGS);
16122 sinkMBB->addLiveIn(X86::EFLAGS);
16125 // Transfer the remainder of BB and its successor edges to sinkMBB.
16126 sinkMBB->splice(sinkMBB->begin(), BB,
16127 std::next(MachineBasicBlock::iterator(MI)), BB->end());
16128 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
16130 // Add the true and fallthrough blocks as its successors.
16131 BB->addSuccessor(copy0MBB);
16132 BB->addSuccessor(sinkMBB);
16134 // Create the conditional branch instruction.
16136 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
16137 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
16140 // %FalseValue = ...
16141 // # fallthrough to sinkMBB
16142 copy0MBB->addSuccessor(sinkMBB);
16145 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
16147 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16148 TII->get(X86::PHI), MI->getOperand(0).getReg())
16149 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
16150 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
16152 MI->eraseFromParent(); // The pseudo instruction is gone now.
16156 MachineBasicBlock *
16157 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
16158 bool Is64Bit) const {
16159 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16160 DebugLoc DL = MI->getDebugLoc();
16161 MachineFunction *MF = BB->getParent();
16162 const BasicBlock *LLVM_BB = BB->getBasicBlock();
16164 assert(MF->shouldSplitStack());
16166 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
16167 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
16170 // ... [Till the alloca]
16171 // If stacklet is not large enough, jump to mallocMBB
16174 // Allocate by subtracting from RSP
16175 // Jump to continueMBB
16178 // Allocate by call to runtime
16182 // [rest of original BB]
16185 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16186 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16187 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16189 MachineRegisterInfo &MRI = MF->getRegInfo();
16190 const TargetRegisterClass *AddrRegClass =
16191 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
16193 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16194 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16195 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
16196 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
16197 sizeVReg = MI->getOperand(1).getReg(),
16198 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
16200 MachineFunction::iterator MBBIter = BB;
16203 MF->insert(MBBIter, bumpMBB);
16204 MF->insert(MBBIter, mallocMBB);
16205 MF->insert(MBBIter, continueMBB);
16207 continueMBB->splice(continueMBB->begin(), BB,
16208 std::next(MachineBasicBlock::iterator(MI)), BB->end());
16209 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
16211 // Add code to the main basic block to check if the stack limit has been hit,
16212 // and if so, jump to mallocMBB otherwise to bumpMBB.
16213 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
16214 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
16215 .addReg(tmpSPVReg).addReg(sizeVReg);
16216 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
16217 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
16218 .addReg(SPLimitVReg);
16219 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
16221 // bumpMBB simply decreases the stack pointer, since we know the current
16222 // stacklet has enough space.
16223 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
16224 .addReg(SPLimitVReg);
16225 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
16226 .addReg(SPLimitVReg);
16227 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16229 // Calls into a routine in libgcc to allocate more space from the heap.
16230 const uint32_t *RegMask =
16231 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16233 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
16235 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
16236 .addExternalSymbol("__morestack_allocate_stack_space")
16237 .addRegMask(RegMask)
16238 .addReg(X86::RDI, RegState::Implicit)
16239 .addReg(X86::RAX, RegState::ImplicitDefine);
16241 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
16243 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
16244 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
16245 .addExternalSymbol("__morestack_allocate_stack_space")
16246 .addRegMask(RegMask)
16247 .addReg(X86::EAX, RegState::ImplicitDefine);
16251 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
16254 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
16255 .addReg(Is64Bit ? X86::RAX : X86::EAX);
16256 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16258 // Set up the CFG correctly.
16259 BB->addSuccessor(bumpMBB);
16260 BB->addSuccessor(mallocMBB);
16261 mallocMBB->addSuccessor(continueMBB);
16262 bumpMBB->addSuccessor(continueMBB);
16264 // Take care of the PHI nodes.
16265 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
16266 MI->getOperand(0).getReg())
16267 .addReg(mallocPtrVReg).addMBB(mallocMBB)
16268 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
16270 // Delete the original pseudo instruction.
16271 MI->eraseFromParent();
16274 return continueMBB;
16277 MachineBasicBlock *
16278 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
16279 MachineBasicBlock *BB) const {
16280 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16281 DebugLoc DL = MI->getDebugLoc();
16283 assert(!Subtarget->isTargetMacho());
16285 // The lowering is pretty easy: we're just emitting the call to _alloca. The
16286 // non-trivial part is impdef of ESP.
16288 if (Subtarget->isTargetWin64()) {
16289 if (Subtarget->isTargetCygMing()) {
16290 // ___chkstk(Mingw64):
16291 // Clobbers R10, R11, RAX and EFLAGS.
16293 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16294 .addExternalSymbol("___chkstk")
16295 .addReg(X86::RAX, RegState::Implicit)
16296 .addReg(X86::RSP, RegState::Implicit)
16297 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
16298 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
16299 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16301 // __chkstk(MSVCRT): does not update stack pointer.
16302 // Clobbers R10, R11 and EFLAGS.
16303 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16304 .addExternalSymbol("__chkstk")
16305 .addReg(X86::RAX, RegState::Implicit)
16306 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16307 // RAX has the offset to be subtracted from RSP.
16308 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
16313 const char *StackProbeSymbol =
16314 Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
16316 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
16317 .addExternalSymbol(StackProbeSymbol)
16318 .addReg(X86::EAX, RegState::Implicit)
16319 .addReg(X86::ESP, RegState::Implicit)
16320 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
16321 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
16322 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16325 MI->eraseFromParent(); // The pseudo instruction is gone now.
16329 MachineBasicBlock *
16330 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
16331 MachineBasicBlock *BB) const {
16332 // This is pretty easy. We're taking the value that we received from
16333 // our load from the relocation, sticking it in either RDI (x86-64)
16334 // or EAX and doing an indirect call. The return value will then
16335 // be in the normal return register.
16336 const X86InstrInfo *TII
16337 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
16338 DebugLoc DL = MI->getDebugLoc();
16339 MachineFunction *F = BB->getParent();
16341 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
16342 assert(MI->getOperand(3).isGlobal() && "This should be a global");
16344 // Get a register mask for the lowered call.
16345 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
16346 // proper register mask.
16347 const uint32_t *RegMask =
16348 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16349 if (Subtarget->is64Bit()) {
16350 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16351 TII->get(X86::MOV64rm), X86::RDI)
16353 .addImm(0).addReg(0)
16354 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16355 MI->getOperand(3).getTargetFlags())
16357 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
16358 addDirectMem(MIB, X86::RDI);
16359 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
16360 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
16361 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16362 TII->get(X86::MOV32rm), X86::EAX)
16364 .addImm(0).addReg(0)
16365 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16366 MI->getOperand(3).getTargetFlags())
16368 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16369 addDirectMem(MIB, X86::EAX);
16370 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16372 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16373 TII->get(X86::MOV32rm), X86::EAX)
16374 .addReg(TII->getGlobalBaseReg(F))
16375 .addImm(0).addReg(0)
16376 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16377 MI->getOperand(3).getTargetFlags())
16379 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16380 addDirectMem(MIB, X86::EAX);
16381 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16384 MI->eraseFromParent(); // The pseudo instruction is gone now.
16388 MachineBasicBlock *
16389 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
16390 MachineBasicBlock *MBB) const {
16391 DebugLoc DL = MI->getDebugLoc();
16392 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16394 MachineFunction *MF = MBB->getParent();
16395 MachineRegisterInfo &MRI = MF->getRegInfo();
16397 const BasicBlock *BB = MBB->getBasicBlock();
16398 MachineFunction::iterator I = MBB;
16401 // Memory Reference
16402 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16403 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16406 unsigned MemOpndSlot = 0;
16408 unsigned CurOp = 0;
16410 DstReg = MI->getOperand(CurOp++).getReg();
16411 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
16412 assert(RC->hasType(MVT::i32) && "Invalid destination!");
16413 unsigned mainDstReg = MRI.createVirtualRegister(RC);
16414 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
16416 MemOpndSlot = CurOp;
16418 MVT PVT = getPointerTy();
16419 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16420 "Invalid Pointer Size!");
16422 // For v = setjmp(buf), we generate
16425 // buf[LabelOffset] = restoreMBB
16426 // SjLjSetup restoreMBB
16432 // v = phi(main, restore)
16437 MachineBasicBlock *thisMBB = MBB;
16438 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16439 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16440 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
16441 MF->insert(I, mainMBB);
16442 MF->insert(I, sinkMBB);
16443 MF->push_back(restoreMBB);
16445 MachineInstrBuilder MIB;
16447 // Transfer the remainder of BB and its successor edges to sinkMBB.
16448 sinkMBB->splice(sinkMBB->begin(), MBB,
16449 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16450 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16453 unsigned PtrStoreOpc = 0;
16454 unsigned LabelReg = 0;
16455 const int64_t LabelOffset = 1 * PVT.getStoreSize();
16456 Reloc::Model RM = getTargetMachine().getRelocationModel();
16457 bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
16458 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
16460 // Prepare IP either in reg or imm.
16461 if (!UseImmLabel) {
16462 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
16463 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
16464 LabelReg = MRI.createVirtualRegister(PtrRC);
16465 if (Subtarget->is64Bit()) {
16466 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
16470 .addMBB(restoreMBB)
16473 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
16474 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
16475 .addReg(XII->getGlobalBaseReg(MF))
16478 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
16482 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
16484 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
16485 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16486 if (i == X86::AddrDisp)
16487 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
16489 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
16492 MIB.addReg(LabelReg);
16494 MIB.addMBB(restoreMBB);
16495 MIB.setMemRefs(MMOBegin, MMOEnd);
16497 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
16498 .addMBB(restoreMBB);
16500 const X86RegisterInfo *RegInfo =
16501 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16502 MIB.addRegMask(RegInfo->getNoPreservedMask());
16503 thisMBB->addSuccessor(mainMBB);
16504 thisMBB->addSuccessor(restoreMBB);
16508 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
16509 mainMBB->addSuccessor(sinkMBB);
16512 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16513 TII->get(X86::PHI), DstReg)
16514 .addReg(mainDstReg).addMBB(mainMBB)
16515 .addReg(restoreDstReg).addMBB(restoreMBB);
16518 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
16519 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
16520 restoreMBB->addSuccessor(sinkMBB);
16522 MI->eraseFromParent();
16526 MachineBasicBlock *
16527 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
16528 MachineBasicBlock *MBB) const {
16529 DebugLoc DL = MI->getDebugLoc();
16530 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16532 MachineFunction *MF = MBB->getParent();
16533 MachineRegisterInfo &MRI = MF->getRegInfo();
16535 // Memory Reference
16536 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16537 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16539 MVT PVT = getPointerTy();
16540 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16541 "Invalid Pointer Size!");
16543 const TargetRegisterClass *RC =
16544 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
16545 unsigned Tmp = MRI.createVirtualRegister(RC);
16546 // Since FP is only updated here but NOT referenced, it's treated as GPR.
16547 const X86RegisterInfo *RegInfo =
16548 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16549 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
16550 unsigned SP = RegInfo->getStackRegister();
16552 MachineInstrBuilder MIB;
16554 const int64_t LabelOffset = 1 * PVT.getStoreSize();
16555 const int64_t SPOffset = 2 * PVT.getStoreSize();
16557 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
16558 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
16561 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
16562 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
16563 MIB.addOperand(MI->getOperand(i));
16564 MIB.setMemRefs(MMOBegin, MMOEnd);
16566 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
16567 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16568 if (i == X86::AddrDisp)
16569 MIB.addDisp(MI->getOperand(i), LabelOffset);
16571 MIB.addOperand(MI->getOperand(i));
16573 MIB.setMemRefs(MMOBegin, MMOEnd);
16575 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
16576 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16577 if (i == X86::AddrDisp)
16578 MIB.addDisp(MI->getOperand(i), SPOffset);
16580 MIB.addOperand(MI->getOperand(i));
16582 MIB.setMemRefs(MMOBegin, MMOEnd);
16584 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
16586 MI->eraseFromParent();
16590 // Replace 213-type (isel default) FMA3 instructions with 231-type for
16591 // accumulator loops. Writing back to the accumulator allows the coalescer
16592 // to remove extra copies in the loop.
16593 MachineBasicBlock *
16594 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
16595 MachineBasicBlock *MBB) const {
16596 MachineOperand &AddendOp = MI->getOperand(3);
16598 // Bail out early if the addend isn't a register - we can't switch these.
16599 if (!AddendOp.isReg())
16602 MachineFunction &MF = *MBB->getParent();
16603 MachineRegisterInfo &MRI = MF.getRegInfo();
16605 // Check whether the addend is defined by a PHI:
16606 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
16607 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
16608 if (!AddendDef.isPHI())
16611 // Look for the following pattern:
16613 // %addend = phi [%entry, 0], [%loop, %result]
16615 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
16619 // %addend = phi [%entry, 0], [%loop, %result]
16621 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
16623 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
16624 assert(AddendDef.getOperand(i).isReg());
16625 MachineOperand PHISrcOp = AddendDef.getOperand(i);
16626 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
16627 if (&PHISrcInst == MI) {
16628 // Found a matching instruction.
16629 unsigned NewFMAOpc = 0;
16630 switch (MI->getOpcode()) {
16631 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
16632 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
16633 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
16634 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
16635 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
16636 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
16637 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
16638 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
16639 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
16640 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
16641 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
16642 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
16643 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
16644 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
16645 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
16646 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
16647 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
16648 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
16649 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
16650 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
16651 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
16652 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
16653 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
16654 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
16655 default: llvm_unreachable("Unrecognized FMA variant.");
16658 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
16659 MachineInstrBuilder MIB =
16660 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
16661 .addOperand(MI->getOperand(0))
16662 .addOperand(MI->getOperand(3))
16663 .addOperand(MI->getOperand(2))
16664 .addOperand(MI->getOperand(1));
16665 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
16666 MI->eraseFromParent();
16673 MachineBasicBlock *
16674 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
16675 MachineBasicBlock *BB) const {
16676 switch (MI->getOpcode()) {
16677 default: llvm_unreachable("Unexpected instr type to insert");
16678 case X86::TAILJMPd64:
16679 case X86::TAILJMPr64:
16680 case X86::TAILJMPm64:
16681 llvm_unreachable("TAILJMP64 would not be touched here.");
16682 case X86::TCRETURNdi64:
16683 case X86::TCRETURNri64:
16684 case X86::TCRETURNmi64:
16686 case X86::WIN_ALLOCA:
16687 return EmitLoweredWinAlloca(MI, BB);
16688 case X86::SEG_ALLOCA_32:
16689 return EmitLoweredSegAlloca(MI, BB, false);
16690 case X86::SEG_ALLOCA_64:
16691 return EmitLoweredSegAlloca(MI, BB, true);
16692 case X86::TLSCall_32:
16693 case X86::TLSCall_64:
16694 return EmitLoweredTLSCall(MI, BB);
16695 case X86::CMOV_GR8:
16696 case X86::CMOV_FR32:
16697 case X86::CMOV_FR64:
16698 case X86::CMOV_V4F32:
16699 case X86::CMOV_V2F64:
16700 case X86::CMOV_V2I64:
16701 case X86::CMOV_V8F32:
16702 case X86::CMOV_V4F64:
16703 case X86::CMOV_V4I64:
16704 case X86::CMOV_V16F32:
16705 case X86::CMOV_V8F64:
16706 case X86::CMOV_V8I64:
16707 case X86::CMOV_GR16:
16708 case X86::CMOV_GR32:
16709 case X86::CMOV_RFP32:
16710 case X86::CMOV_RFP64:
16711 case X86::CMOV_RFP80:
16712 return EmitLoweredSelect(MI, BB);
16714 case X86::FP32_TO_INT16_IN_MEM:
16715 case X86::FP32_TO_INT32_IN_MEM:
16716 case X86::FP32_TO_INT64_IN_MEM:
16717 case X86::FP64_TO_INT16_IN_MEM:
16718 case X86::FP64_TO_INT32_IN_MEM:
16719 case X86::FP64_TO_INT64_IN_MEM:
16720 case X86::FP80_TO_INT16_IN_MEM:
16721 case X86::FP80_TO_INT32_IN_MEM:
16722 case X86::FP80_TO_INT64_IN_MEM: {
16723 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16724 DebugLoc DL = MI->getDebugLoc();
16726 // Change the floating point control register to use "round towards zero"
16727 // mode when truncating to an integer value.
16728 MachineFunction *F = BB->getParent();
16729 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
16730 addFrameReference(BuildMI(*BB, MI, DL,
16731 TII->get(X86::FNSTCW16m)), CWFrameIdx);
16733 // Load the old value of the high byte of the control word...
16735 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
16736 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
16739 // Set the high part to be round to zero...
16740 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
16743 // Reload the modified control word now...
16744 addFrameReference(BuildMI(*BB, MI, DL,
16745 TII->get(X86::FLDCW16m)), CWFrameIdx);
16747 // Restore the memory image of control word to original value
16748 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
16751 // Get the X86 opcode to use.
16753 switch (MI->getOpcode()) {
16754 default: llvm_unreachable("illegal opcode!");
16755 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
16756 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
16757 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
16758 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
16759 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
16760 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
16761 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
16762 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
16763 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
16767 MachineOperand &Op = MI->getOperand(0);
16769 AM.BaseType = X86AddressMode::RegBase;
16770 AM.Base.Reg = Op.getReg();
16772 AM.BaseType = X86AddressMode::FrameIndexBase;
16773 AM.Base.FrameIndex = Op.getIndex();
16775 Op = MI->getOperand(1);
16777 AM.Scale = Op.getImm();
16778 Op = MI->getOperand(2);
16780 AM.IndexReg = Op.getImm();
16781 Op = MI->getOperand(3);
16782 if (Op.isGlobal()) {
16783 AM.GV = Op.getGlobal();
16785 AM.Disp = Op.getImm();
16787 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
16788 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
16790 // Reload the original control word now.
16791 addFrameReference(BuildMI(*BB, MI, DL,
16792 TII->get(X86::FLDCW16m)), CWFrameIdx);
16794 MI->eraseFromParent(); // The pseudo instruction is gone now.
16797 // String/text processing lowering.
16798 case X86::PCMPISTRM128REG:
16799 case X86::VPCMPISTRM128REG:
16800 case X86::PCMPISTRM128MEM:
16801 case X86::VPCMPISTRM128MEM:
16802 case X86::PCMPESTRM128REG:
16803 case X86::VPCMPESTRM128REG:
16804 case X86::PCMPESTRM128MEM:
16805 case X86::VPCMPESTRM128MEM:
16806 assert(Subtarget->hasSSE42() &&
16807 "Target must have SSE4.2 or AVX features enabled");
16808 return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
16810 // String/text processing lowering.
16811 case X86::PCMPISTRIREG:
16812 case X86::VPCMPISTRIREG:
16813 case X86::PCMPISTRIMEM:
16814 case X86::VPCMPISTRIMEM:
16815 case X86::PCMPESTRIREG:
16816 case X86::VPCMPESTRIREG:
16817 case X86::PCMPESTRIMEM:
16818 case X86::VPCMPESTRIMEM:
16819 assert(Subtarget->hasSSE42() &&
16820 "Target must have SSE4.2 or AVX features enabled");
16821 return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
16823 // Thread synchronization.
16825 return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
16829 return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
16831 // Atomic Lowering.
16832 case X86::ATOMAND8:
16833 case X86::ATOMAND16:
16834 case X86::ATOMAND32:
16835 case X86::ATOMAND64:
16838 case X86::ATOMOR16:
16839 case X86::ATOMOR32:
16840 case X86::ATOMOR64:
16842 case X86::ATOMXOR16:
16843 case X86::ATOMXOR8:
16844 case X86::ATOMXOR32:
16845 case X86::ATOMXOR64:
16847 case X86::ATOMNAND8:
16848 case X86::ATOMNAND16:
16849 case X86::ATOMNAND32:
16850 case X86::ATOMNAND64:
16852 case X86::ATOMMAX8:
16853 case X86::ATOMMAX16:
16854 case X86::ATOMMAX32:
16855 case X86::ATOMMAX64:
16857 case X86::ATOMMIN8:
16858 case X86::ATOMMIN16:
16859 case X86::ATOMMIN32:
16860 case X86::ATOMMIN64:
16862 case X86::ATOMUMAX8:
16863 case X86::ATOMUMAX16:
16864 case X86::ATOMUMAX32:
16865 case X86::ATOMUMAX64:
16867 case X86::ATOMUMIN8:
16868 case X86::ATOMUMIN16:
16869 case X86::ATOMUMIN32:
16870 case X86::ATOMUMIN64:
16871 return EmitAtomicLoadArith(MI, BB);
16873 // This group does 64-bit operations on a 32-bit host.
16874 case X86::ATOMAND6432:
16875 case X86::ATOMOR6432:
16876 case X86::ATOMXOR6432:
16877 case X86::ATOMNAND6432:
16878 case X86::ATOMADD6432:
16879 case X86::ATOMSUB6432:
16880 case X86::ATOMMAX6432:
16881 case X86::ATOMMIN6432:
16882 case X86::ATOMUMAX6432:
16883 case X86::ATOMUMIN6432:
16884 case X86::ATOMSWAP6432:
16885 return EmitAtomicLoadArith6432(MI, BB);
16887 case X86::VASTART_SAVE_XMM_REGS:
16888 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
16890 case X86::VAARG_64:
16891 return EmitVAARG64WithCustomInserter(MI, BB);
16893 case X86::EH_SjLj_SetJmp32:
16894 case X86::EH_SjLj_SetJmp64:
16895 return emitEHSjLjSetJmp(MI, BB);
16897 case X86::EH_SjLj_LongJmp32:
16898 case X86::EH_SjLj_LongJmp64:
16899 return emitEHSjLjLongJmp(MI, BB);
16901 case TargetOpcode::STACKMAP:
16902 case TargetOpcode::PATCHPOINT:
16903 return emitPatchPoint(MI, BB);
16905 case X86::VFMADDPDr213r:
16906 case X86::VFMADDPSr213r:
16907 case X86::VFMADDSDr213r:
16908 case X86::VFMADDSSr213r:
16909 case X86::VFMSUBPDr213r:
16910 case X86::VFMSUBPSr213r:
16911 case X86::VFMSUBSDr213r:
16912 case X86::VFMSUBSSr213r:
16913 case X86::VFNMADDPDr213r:
16914 case X86::VFNMADDPSr213r:
16915 case X86::VFNMADDSDr213r:
16916 case X86::VFNMADDSSr213r:
16917 case X86::VFNMSUBPDr213r:
16918 case X86::VFNMSUBPSr213r:
16919 case X86::VFNMSUBSDr213r:
16920 case X86::VFNMSUBSSr213r:
16921 case X86::VFMADDPDr213rY:
16922 case X86::VFMADDPSr213rY:
16923 case X86::VFMSUBPDr213rY:
16924 case X86::VFMSUBPSr213rY:
16925 case X86::VFNMADDPDr213rY:
16926 case X86::VFNMADDPSr213rY:
16927 case X86::VFNMSUBPDr213rY:
16928 case X86::VFNMSUBPSr213rY:
16929 return emitFMA3Instr(MI, BB);
16933 //===----------------------------------------------------------------------===//
16934 // X86 Optimization Hooks
16935 //===----------------------------------------------------------------------===//
16937 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
16940 const SelectionDAG &DAG,
16941 unsigned Depth) const {
16942 unsigned BitWidth = KnownZero.getBitWidth();
16943 unsigned Opc = Op.getOpcode();
16944 assert((Opc >= ISD::BUILTIN_OP_END ||
16945 Opc == ISD::INTRINSIC_WO_CHAIN ||
16946 Opc == ISD::INTRINSIC_W_CHAIN ||
16947 Opc == ISD::INTRINSIC_VOID) &&
16948 "Should use MaskedValueIsZero if you don't know whether Op"
16949 " is a target node!");
16951 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
16965 // These nodes' second result is a boolean.
16966 if (Op.getResNo() == 0)
16969 case X86ISD::SETCC:
16970 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
16972 case ISD::INTRINSIC_WO_CHAIN: {
16973 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16974 unsigned NumLoBits = 0;
16977 case Intrinsic::x86_sse_movmsk_ps:
16978 case Intrinsic::x86_avx_movmsk_ps_256:
16979 case Intrinsic::x86_sse2_movmsk_pd:
16980 case Intrinsic::x86_avx_movmsk_pd_256:
16981 case Intrinsic::x86_mmx_pmovmskb:
16982 case Intrinsic::x86_sse2_pmovmskb_128:
16983 case Intrinsic::x86_avx2_pmovmskb: {
16984 // High bits of movmskp{s|d}, pmovmskb are known zero.
16986 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
16987 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
16988 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
16989 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
16990 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
16991 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
16992 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
16993 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
16995 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
17004 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
17006 const SelectionDAG &,
17007 unsigned Depth) const {
17008 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
17009 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
17010 return Op.getValueType().getScalarType().getSizeInBits();
17016 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
17017 /// node is a GlobalAddress + offset.
17018 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
17019 const GlobalValue* &GA,
17020 int64_t &Offset) const {
17021 if (N->getOpcode() == X86ISD::Wrapper) {
17022 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
17023 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
17024 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
17028 return TargetLowering::isGAPlusOffset(N, GA, Offset);
17031 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
17032 /// same as extracting the high 128-bit part of 256-bit vector and then
17033 /// inserting the result into the low part of a new 256-bit vector
17034 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
17035 EVT VT = SVOp->getValueType(0);
17036 unsigned NumElems = VT.getVectorNumElements();
17038 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17039 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
17040 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17041 SVOp->getMaskElt(j) >= 0)
17047 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
17048 /// same as extracting the low 128-bit part of 256-bit vector and then
17049 /// inserting the result into the high part of a new 256-bit vector
17050 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
17051 EVT VT = SVOp->getValueType(0);
17052 unsigned NumElems = VT.getVectorNumElements();
17054 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17055 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
17056 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17057 SVOp->getMaskElt(j) >= 0)
17063 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
17064 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
17065 TargetLowering::DAGCombinerInfo &DCI,
17066 const X86Subtarget* Subtarget) {
17068 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17069 SDValue V1 = SVOp->getOperand(0);
17070 SDValue V2 = SVOp->getOperand(1);
17071 EVT VT = SVOp->getValueType(0);
17072 unsigned NumElems = VT.getVectorNumElements();
17074 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
17075 V2.getOpcode() == ISD::CONCAT_VECTORS) {
17079 // V UNDEF BUILD_VECTOR UNDEF
17081 // CONCAT_VECTOR CONCAT_VECTOR
17084 // RESULT: V + zero extended
17086 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
17087 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
17088 V1.getOperand(1).getOpcode() != ISD::UNDEF)
17091 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
17094 // To match the shuffle mask, the first half of the mask should
17095 // be exactly the first vector, and all the rest a splat with the
17096 // first element of the second one.
17097 for (unsigned i = 0; i != NumElems/2; ++i)
17098 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
17099 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
17102 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
17103 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
17104 if (Ld->hasNUsesOfValue(1, 0)) {
17105 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
17106 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
17108 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
17109 array_lengthof(Ops),
17111 Ld->getPointerInfo(),
17112 Ld->getAlignment(),
17113 false/*isVolatile*/, true/*ReadMem*/,
17114 false/*WriteMem*/);
17116 // Make sure the newly-created LOAD is in the same position as Ld in
17117 // terms of dependency. We create a TokenFactor for Ld and ResNode,
17118 // and update uses of Ld's output chain to use the TokenFactor.
17119 if (Ld->hasAnyUseOfValue(1)) {
17120 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17121 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
17122 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
17123 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
17124 SDValue(ResNode.getNode(), 1));
17127 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
17131 // Emit a zeroed vector and insert the desired subvector on its
17133 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17134 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
17135 return DCI.CombineTo(N, InsV);
17138 //===--------------------------------------------------------------------===//
17139 // Combine some shuffles into subvector extracts and inserts:
17142 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17143 if (isShuffleHigh128VectorInsertLow(SVOp)) {
17144 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
17145 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
17146 return DCI.CombineTo(N, InsV);
17149 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17150 if (isShuffleLow128VectorInsertHigh(SVOp)) {
17151 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
17152 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
17153 return DCI.CombineTo(N, InsV);
17159 /// PerformShuffleCombine - Performs several different shuffle combines.
17160 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
17161 TargetLowering::DAGCombinerInfo &DCI,
17162 const X86Subtarget *Subtarget) {
17164 EVT VT = N->getValueType(0);
17166 // Don't create instructions with illegal types after legalize types has run.
17167 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17168 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
17171 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
17172 if (Subtarget->hasFp256() && VT.is256BitVector() &&
17173 N->getOpcode() == ISD::VECTOR_SHUFFLE)
17174 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
17176 // Only handle 128 wide vector from here on.
17177 if (!VT.is128BitVector())
17180 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
17181 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
17182 // consecutive, non-overlapping, and in the right order.
17183 SmallVector<SDValue, 16> Elts;
17184 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
17185 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
17187 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
17190 /// PerformTruncateCombine - Converts truncate operation to
17191 /// a sequence of vector shuffle operations.
17192 /// It is possible when we truncate 256-bit vector to 128-bit vector
17193 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
17194 TargetLowering::DAGCombinerInfo &DCI,
17195 const X86Subtarget *Subtarget) {
17199 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
17200 /// specific shuffle of a load can be folded into a single element load.
17201 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
17202 /// shuffles have been customed lowered so we need to handle those here.
17203 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
17204 TargetLowering::DAGCombinerInfo &DCI) {
17205 if (DCI.isBeforeLegalizeOps())
17208 SDValue InVec = N->getOperand(0);
17209 SDValue EltNo = N->getOperand(1);
17211 if (!isa<ConstantSDNode>(EltNo))
17214 EVT VT = InVec.getValueType();
17216 bool HasShuffleIntoBitcast = false;
17217 if (InVec.getOpcode() == ISD::BITCAST) {
17218 // Don't duplicate a load with other uses.
17219 if (!InVec.hasOneUse())
17221 EVT BCVT = InVec.getOperand(0).getValueType();
17222 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
17224 InVec = InVec.getOperand(0);
17225 HasShuffleIntoBitcast = true;
17228 if (!isTargetShuffle(InVec.getOpcode()))
17231 // Don't duplicate a load with other uses.
17232 if (!InVec.hasOneUse())
17235 SmallVector<int, 16> ShuffleMask;
17237 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
17241 // Select the input vector, guarding against out of range extract vector.
17242 unsigned NumElems = VT.getVectorNumElements();
17243 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
17244 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
17245 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
17246 : InVec.getOperand(1);
17248 // If inputs to shuffle are the same for both ops, then allow 2 uses
17249 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
17251 if (LdNode.getOpcode() == ISD::BITCAST) {
17252 // Don't duplicate a load with other uses.
17253 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
17256 AllowedUses = 1; // only allow 1 load use if we have a bitcast
17257 LdNode = LdNode.getOperand(0);
17260 if (!ISD::isNormalLoad(LdNode.getNode()))
17263 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
17265 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
17268 if (HasShuffleIntoBitcast) {
17269 // If there's a bitcast before the shuffle, check if the load type and
17270 // alignment is valid.
17271 unsigned Align = LN0->getAlignment();
17272 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17273 unsigned NewAlign = TLI.getDataLayout()->
17274 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
17276 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
17280 // All checks match so transform back to vector_shuffle so that DAG combiner
17281 // can finish the job
17284 // Create shuffle node taking into account the case that its a unary shuffle
17285 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
17286 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
17287 InVec.getOperand(0), Shuffle,
17289 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
17290 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
17294 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
17295 /// generation and convert it from being a bunch of shuffles and extracts
17296 /// to a simple store and scalar loads to extract the elements.
17297 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
17298 TargetLowering::DAGCombinerInfo &DCI) {
17299 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
17300 if (NewOp.getNode())
17303 SDValue InputVector = N->getOperand(0);
17305 // Detect whether we are trying to convert from mmx to i32 and the bitcast
17306 // from mmx to v2i32 has a single usage.
17307 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
17308 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
17309 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
17310 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
17311 N->getValueType(0),
17312 InputVector.getNode()->getOperand(0));
17314 // Only operate on vectors of 4 elements, where the alternative shuffling
17315 // gets to be more expensive.
17316 if (InputVector.getValueType() != MVT::v4i32)
17319 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
17320 // single use which is a sign-extend or zero-extend, and all elements are
17322 SmallVector<SDNode *, 4> Uses;
17323 unsigned ExtractedElements = 0;
17324 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
17325 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
17326 if (UI.getUse().getResNo() != InputVector.getResNo())
17329 SDNode *Extract = *UI;
17330 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
17333 if (Extract->getValueType(0) != MVT::i32)
17335 if (!Extract->hasOneUse())
17337 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
17338 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
17340 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
17343 // Record which element was extracted.
17344 ExtractedElements |=
17345 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
17347 Uses.push_back(Extract);
17350 // If not all the elements were used, this may not be worthwhile.
17351 if (ExtractedElements != 15)
17354 // Ok, we've now decided to do the transformation.
17355 SDLoc dl(InputVector);
17357 // Store the value to a temporary stack slot.
17358 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
17359 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
17360 MachinePointerInfo(), false, false, 0);
17362 // Replace each use (extract) with a load of the appropriate element.
17363 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
17364 UE = Uses.end(); UI != UE; ++UI) {
17365 SDNode *Extract = *UI;
17367 // cOMpute the element's address.
17368 SDValue Idx = Extract->getOperand(1);
17370 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
17371 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
17372 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17373 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
17375 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
17376 StackPtr, OffsetVal);
17378 // Load the scalar.
17379 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
17380 ScalarAddr, MachinePointerInfo(),
17381 false, false, false, 0);
17383 // Replace the exact with the load.
17384 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
17387 // The replacement was made in place; don't return anything.
17391 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
17392 static std::pair<unsigned, bool>
17393 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
17394 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
17395 if (!VT.isVector())
17396 return std::make_pair(0, false);
17398 bool NeedSplit = false;
17399 switch (VT.getSimpleVT().SimpleTy) {
17400 default: return std::make_pair(0, false);
17404 if (!Subtarget->hasAVX2())
17406 if (!Subtarget->hasAVX())
17407 return std::make_pair(0, false);
17412 if (!Subtarget->hasSSE2())
17413 return std::make_pair(0, false);
17416 // SSE2 has only a small subset of the operations.
17417 bool hasUnsigned = Subtarget->hasSSE41() ||
17418 (Subtarget->hasSSE2() && VT == MVT::v16i8);
17419 bool hasSigned = Subtarget->hasSSE41() ||
17420 (Subtarget->hasSSE2() && VT == MVT::v8i16);
17422 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17425 // Check for x CC y ? x : y.
17426 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17427 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17432 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17435 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17438 Opc = hasSigned ? X86ISD::SMIN : 0; break;
17441 Opc = hasSigned ? X86ISD::SMAX : 0; break;
17443 // Check for x CC y ? y : x -- a min/max with reversed arms.
17444 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17445 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17450 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17453 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17456 Opc = hasSigned ? X86ISD::SMAX : 0; break;
17459 Opc = hasSigned ? X86ISD::SMIN : 0; break;
17463 return std::make_pair(Opc, NeedSplit);
17466 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
17468 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
17469 TargetLowering::DAGCombinerInfo &DCI,
17470 const X86Subtarget *Subtarget) {
17472 SDValue Cond = N->getOperand(0);
17473 // Get the LHS/RHS of the select.
17474 SDValue LHS = N->getOperand(1);
17475 SDValue RHS = N->getOperand(2);
17476 EVT VT = LHS.getValueType();
17477 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17479 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
17480 // instructions match the semantics of the common C idiom x<y?x:y but not
17481 // x<=y?x:y, because of how they handle negative zero (which can be
17482 // ignored in unsafe-math mode).
17483 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
17484 VT != MVT::f80 && TLI.isTypeLegal(VT) &&
17485 (Subtarget->hasSSE2() ||
17486 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
17487 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17489 unsigned Opcode = 0;
17490 // Check for x CC y ? x : y.
17491 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17492 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17496 // Converting this to a min would handle NaNs incorrectly, and swapping
17497 // the operands would cause it to handle comparisons between positive
17498 // and negative zero incorrectly.
17499 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17500 if (!DAG.getTarget().Options.UnsafeFPMath &&
17501 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17503 std::swap(LHS, RHS);
17505 Opcode = X86ISD::FMIN;
17508 // Converting this to a min would handle comparisons between positive
17509 // and negative zero incorrectly.
17510 if (!DAG.getTarget().Options.UnsafeFPMath &&
17511 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17513 Opcode = X86ISD::FMIN;
17516 // Converting this to a min would handle both negative zeros and NaNs
17517 // incorrectly, but we can swap the operands to fix both.
17518 std::swap(LHS, RHS);
17522 Opcode = X86ISD::FMIN;
17526 // Converting this to a max would handle comparisons between positive
17527 // and negative zero incorrectly.
17528 if (!DAG.getTarget().Options.UnsafeFPMath &&
17529 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17531 Opcode = X86ISD::FMAX;
17534 // Converting this to a max would handle NaNs incorrectly, and swapping
17535 // the operands would cause it to handle comparisons between positive
17536 // and negative zero incorrectly.
17537 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17538 if (!DAG.getTarget().Options.UnsafeFPMath &&
17539 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17541 std::swap(LHS, RHS);
17543 Opcode = X86ISD::FMAX;
17546 // Converting this to a max would handle both negative zeros and NaNs
17547 // incorrectly, but we can swap the operands to fix both.
17548 std::swap(LHS, RHS);
17552 Opcode = X86ISD::FMAX;
17555 // Check for x CC y ? y : x -- a min/max with reversed arms.
17556 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17557 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17561 // Converting this to a min would handle comparisons between positive
17562 // and negative zero incorrectly, and swapping the operands would
17563 // cause it to handle NaNs incorrectly.
17564 if (!DAG.getTarget().Options.UnsafeFPMath &&
17565 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
17566 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17568 std::swap(LHS, RHS);
17570 Opcode = X86ISD::FMIN;
17573 // Converting this to a min would handle NaNs incorrectly.
17574 if (!DAG.getTarget().Options.UnsafeFPMath &&
17575 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
17577 Opcode = X86ISD::FMIN;
17580 // Converting this to a min would handle both negative zeros and NaNs
17581 // incorrectly, but we can swap the operands to fix both.
17582 std::swap(LHS, RHS);
17586 Opcode = X86ISD::FMIN;
17590 // Converting this to a max would handle NaNs incorrectly.
17591 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17593 Opcode = X86ISD::FMAX;
17596 // Converting this to a max would handle comparisons between positive
17597 // and negative zero incorrectly, and swapping the operands would
17598 // cause it to handle NaNs incorrectly.
17599 if (!DAG.getTarget().Options.UnsafeFPMath &&
17600 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
17601 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17603 std::swap(LHS, RHS);
17605 Opcode = X86ISD::FMAX;
17608 // Converting this to a max would handle both negative zeros and NaNs
17609 // incorrectly, but we can swap the operands to fix both.
17610 std::swap(LHS, RHS);
17614 Opcode = X86ISD::FMAX;
17620 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
17623 EVT CondVT = Cond.getValueType();
17624 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
17625 CondVT.getVectorElementType() == MVT::i1) {
17626 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
17627 // lowering on AVX-512. In this case we convert it to
17628 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
17629 // The same situation for all 128 and 256-bit vectors of i8 and i16
17630 EVT OpVT = LHS.getValueType();
17631 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
17632 (OpVT.getVectorElementType() == MVT::i8 ||
17633 OpVT.getVectorElementType() == MVT::i16)) {
17634 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
17635 DCI.AddToWorklist(Cond.getNode());
17636 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
17639 // If this is a select between two integer constants, try to do some
17641 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
17642 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
17643 // Don't do this for crazy integer types.
17644 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
17645 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
17646 // so that TrueC (the true value) is larger than FalseC.
17647 bool NeedsCondInvert = false;
17649 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
17650 // Efficiently invertible.
17651 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
17652 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
17653 isa<ConstantSDNode>(Cond.getOperand(1))))) {
17654 NeedsCondInvert = true;
17655 std::swap(TrueC, FalseC);
17658 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
17659 if (FalseC->getAPIntValue() == 0 &&
17660 TrueC->getAPIntValue().isPowerOf2()) {
17661 if (NeedsCondInvert) // Invert the condition if needed.
17662 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17663 DAG.getConstant(1, Cond.getValueType()));
17665 // Zero extend the condition if needed.
17666 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
17668 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17669 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
17670 DAG.getConstant(ShAmt, MVT::i8));
17673 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
17674 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17675 if (NeedsCondInvert) // Invert the condition if needed.
17676 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17677 DAG.getConstant(1, Cond.getValueType()));
17679 // Zero extend the condition if needed.
17680 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17681 FalseC->getValueType(0), Cond);
17682 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17683 SDValue(FalseC, 0));
17686 // Optimize cases that will turn into an LEA instruction. This requires
17687 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17688 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17689 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17690 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17692 bool isFastMultiplier = false;
17694 switch ((unsigned char)Diff) {
17696 case 1: // result = add base, cond
17697 case 2: // result = lea base( , cond*2)
17698 case 3: // result = lea base(cond, cond*2)
17699 case 4: // result = lea base( , cond*4)
17700 case 5: // result = lea base(cond, cond*4)
17701 case 8: // result = lea base( , cond*8)
17702 case 9: // result = lea base(cond, cond*8)
17703 isFastMultiplier = true;
17708 if (isFastMultiplier) {
17709 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
17710 if (NeedsCondInvert) // Invert the condition if needed.
17711 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17712 DAG.getConstant(1, Cond.getValueType()));
17714 // Zero extend the condition if needed.
17715 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
17717 // Scale the condition by the difference.
17719 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
17720 DAG.getConstant(Diff, Cond.getValueType()));
17722 // Add the base if non-zero.
17723 if (FalseC->getAPIntValue() != 0)
17724 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17725 SDValue(FalseC, 0));
17732 // Canonicalize max and min:
17733 // (x > y) ? x : y -> (x >= y) ? x : y
17734 // (x < y) ? x : y -> (x <= y) ? x : y
17735 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
17736 // the need for an extra compare
17737 // against zero. e.g.
17738 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
17740 // testl %edi, %edi
17742 // cmovgl %edi, %eax
17746 // cmovsl %eax, %edi
17747 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
17748 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17749 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17750 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17755 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
17756 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
17757 Cond.getOperand(0), Cond.getOperand(1), NewCC);
17758 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
17763 // Early exit check
17764 if (!TLI.isTypeLegal(VT))
17767 // Match VSELECTs into subs with unsigned saturation.
17768 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17769 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
17770 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
17771 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
17772 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17774 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
17775 // left side invert the predicate to simplify logic below.
17777 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
17779 CC = ISD::getSetCCInverse(CC, true);
17780 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
17784 if (Other.getNode() && Other->getNumOperands() == 2 &&
17785 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
17786 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
17787 SDValue CondRHS = Cond->getOperand(1);
17789 // Look for a general sub with unsigned saturation first.
17790 // x >= y ? x-y : 0 --> subus x, y
17791 // x > y ? x-y : 0 --> subus x, y
17792 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
17793 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
17794 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17796 // If the RHS is a constant we have to reverse the const canonicalization.
17797 // x > C-1 ? x+-C : 0 --> subus x, C
17798 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
17799 isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
17800 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17801 if (CondRHS.getConstantOperandVal(0) == -A-1)
17802 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
17803 DAG.getConstant(-A, VT));
17806 // Another special case: If C was a sign bit, the sub has been
17807 // canonicalized into a xor.
17808 // FIXME: Would it be better to use ComputeMaskedBits to determine whether
17809 // it's safe to decanonicalize the xor?
17810 // x s< 0 ? x^C : 0 --> subus x, C
17811 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
17812 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
17813 isSplatVector(OpRHS.getNode())) {
17814 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17816 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17821 // Try to match a min/max vector operation.
17822 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
17823 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
17824 unsigned Opc = ret.first;
17825 bool NeedSplit = ret.second;
17827 if (Opc && NeedSplit) {
17828 unsigned NumElems = VT.getVectorNumElements();
17829 // Extract the LHS vectors
17830 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
17831 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
17833 // Extract the RHS vectors
17834 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
17835 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
17837 // Create min/max for each subvector
17838 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
17839 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
17841 // Merge the result
17842 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
17844 return DAG.getNode(Opc, DL, VT, LHS, RHS);
17847 // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
17848 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17849 // Check if SETCC has already been promoted
17850 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
17851 // Check that condition value type matches vselect operand type
17854 assert(Cond.getValueType().isVector() &&
17855 "vector select expects a vector selector!");
17857 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
17858 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
17860 if (!TValIsAllOnes && !FValIsAllZeros) {
17861 // Try invert the condition if true value is not all 1s and false value
17863 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
17864 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
17866 if (TValIsAllZeros || FValIsAllOnes) {
17867 SDValue CC = Cond.getOperand(2);
17868 ISD::CondCode NewCC =
17869 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
17870 Cond.getOperand(0).getValueType().isInteger());
17871 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
17872 std::swap(LHS, RHS);
17873 TValIsAllOnes = FValIsAllOnes;
17874 FValIsAllZeros = TValIsAllZeros;
17878 if (TValIsAllOnes || FValIsAllZeros) {
17881 if (TValIsAllOnes && FValIsAllZeros)
17883 else if (TValIsAllOnes)
17884 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
17885 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
17886 else if (FValIsAllZeros)
17887 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
17888 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
17890 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
17894 // Try to fold this VSELECT into a MOVSS/MOVSD
17895 if (N->getOpcode() == ISD::VSELECT &&
17896 Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
17897 if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
17898 (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
17899 bool CanFold = false;
17900 unsigned NumElems = Cond.getNumOperands();
17904 if (isZero(Cond.getOperand(0))) {
17907 // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
17908 // fold (vselect <0,-1> -> (movsd A, B)
17909 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17910 CanFold = isAllOnes(Cond.getOperand(i));
17911 } else if (isAllOnes(Cond.getOperand(0))) {
17915 // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
17916 // fold (vselect <-1,0> -> (movsd B, A)
17917 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17918 CanFold = isZero(Cond.getOperand(i));
17922 if (VT == MVT::v4i32 || VT == MVT::v4f32)
17923 return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
17924 return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
17927 if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
17928 // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
17929 // (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
17930 // (v2i64 (bitcast B)))))
17932 // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
17933 // (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
17934 // (v2f64 (bitcast B)))))
17936 // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
17937 // (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
17938 // (v2i64 (bitcast A)))))
17940 // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
17941 // (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
17942 // (v2f64 (bitcast A)))))
17944 CanFold = (isZero(Cond.getOperand(0)) &&
17945 isZero(Cond.getOperand(1)) &&
17946 isAllOnes(Cond.getOperand(2)) &&
17947 isAllOnes(Cond.getOperand(3)));
17949 if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
17950 isAllOnes(Cond.getOperand(1)) &&
17951 isZero(Cond.getOperand(2)) &&
17952 isZero(Cond.getOperand(3))) {
17954 std::swap(LHS, RHS);
17958 EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
17959 SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
17960 SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
17961 SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
17963 return DAG.getNode(ISD::BITCAST, DL, VT, Select);
17969 // If we know that this node is legal then we know that it is going to be
17970 // matched by one of the SSE/AVX BLEND instructions. These instructions only
17971 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
17972 // to simplify previous instructions.
17973 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
17974 !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
17975 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
17977 // Don't optimize vector selects that map to mask-registers.
17981 // Check all uses of that condition operand to check whether it will be
17982 // consumed by non-BLEND instructions, which may depend on all bits are set
17984 for (SDNode::use_iterator I = Cond->use_begin(),
17985 E = Cond->use_end(); I != E; ++I)
17986 if (I->getOpcode() != ISD::VSELECT)
17987 // TODO: Add other opcodes eventually lowered into BLEND.
17990 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
17991 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
17993 APInt KnownZero, KnownOne;
17994 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
17995 DCI.isBeforeLegalizeOps());
17996 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
17997 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
17998 DCI.CommitTargetLoweringOpt(TLO);
18004 // Check whether a boolean test is testing a boolean value generated by
18005 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
18008 // Simplify the following patterns:
18009 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
18010 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
18011 // to (Op EFLAGS Cond)
18013 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
18014 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
18015 // to (Op EFLAGS !Cond)
18017 // where Op could be BRCOND or CMOV.
18019 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
18020 // Quit if not CMP and SUB with its value result used.
18021 if (Cmp.getOpcode() != X86ISD::CMP &&
18022 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
18025 // Quit if not used as a boolean value.
18026 if (CC != X86::COND_E && CC != X86::COND_NE)
18029 // Check CMP operands. One of them should be 0 or 1 and the other should be
18030 // an SetCC or extended from it.
18031 SDValue Op1 = Cmp.getOperand(0);
18032 SDValue Op2 = Cmp.getOperand(1);
18035 const ConstantSDNode* C = nullptr;
18036 bool needOppositeCond = (CC == X86::COND_E);
18037 bool checkAgainstTrue = false; // Is it a comparison against 1?
18039 if ((C = dyn_cast<ConstantSDNode>(Op1)))
18041 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
18043 else // Quit if all operands are not constants.
18046 if (C->getZExtValue() == 1) {
18047 needOppositeCond = !needOppositeCond;
18048 checkAgainstTrue = true;
18049 } else if (C->getZExtValue() != 0)
18050 // Quit if the constant is neither 0 or 1.
18053 bool truncatedToBoolWithAnd = false;
18054 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
18055 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
18056 SetCC.getOpcode() == ISD::TRUNCATE ||
18057 SetCC.getOpcode() == ISD::AND) {
18058 if (SetCC.getOpcode() == ISD::AND) {
18060 ConstantSDNode *CS;
18061 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
18062 CS->getZExtValue() == 1)
18064 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
18065 CS->getZExtValue() == 1)
18069 SetCC = SetCC.getOperand(OpIdx);
18070 truncatedToBoolWithAnd = true;
18072 SetCC = SetCC.getOperand(0);
18075 switch (SetCC.getOpcode()) {
18076 case X86ISD::SETCC_CARRY:
18077 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
18078 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
18079 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
18080 // truncated to i1 using 'and'.
18081 if (checkAgainstTrue && !truncatedToBoolWithAnd)
18083 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
18084 "Invalid use of SETCC_CARRY!");
18086 case X86ISD::SETCC:
18087 // Set the condition code or opposite one if necessary.
18088 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
18089 if (needOppositeCond)
18090 CC = X86::GetOppositeBranchCondition(CC);
18091 return SetCC.getOperand(1);
18092 case X86ISD::CMOV: {
18093 // Check whether false/true value has canonical one, i.e. 0 or 1.
18094 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
18095 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
18096 // Quit if true value is not a constant.
18099 // Quit if false value is not a constant.
18101 SDValue Op = SetCC.getOperand(0);
18102 // Skip 'zext' or 'trunc' node.
18103 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
18104 Op.getOpcode() == ISD::TRUNCATE)
18105 Op = Op.getOperand(0);
18106 // A special case for rdrand/rdseed, where 0 is set if false cond is
18108 if ((Op.getOpcode() != X86ISD::RDRAND &&
18109 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
18112 // Quit if false value is not the constant 0 or 1.
18113 bool FValIsFalse = true;
18114 if (FVal && FVal->getZExtValue() != 0) {
18115 if (FVal->getZExtValue() != 1)
18117 // If FVal is 1, opposite cond is needed.
18118 needOppositeCond = !needOppositeCond;
18119 FValIsFalse = false;
18121 // Quit if TVal is not the constant opposite of FVal.
18122 if (FValIsFalse && TVal->getZExtValue() != 1)
18124 if (!FValIsFalse && TVal->getZExtValue() != 0)
18126 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
18127 if (needOppositeCond)
18128 CC = X86::GetOppositeBranchCondition(CC);
18129 return SetCC.getOperand(3);
18136 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
18137 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
18138 TargetLowering::DAGCombinerInfo &DCI,
18139 const X86Subtarget *Subtarget) {
18142 // If the flag operand isn't dead, don't touch this CMOV.
18143 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
18146 SDValue FalseOp = N->getOperand(0);
18147 SDValue TrueOp = N->getOperand(1);
18148 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
18149 SDValue Cond = N->getOperand(3);
18151 if (CC == X86::COND_E || CC == X86::COND_NE) {
18152 switch (Cond.getOpcode()) {
18156 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
18157 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
18158 return (CC == X86::COND_E) ? FalseOp : TrueOp;
18164 Flags = checkBoolTestSetCCCombine(Cond, CC);
18165 if (Flags.getNode() &&
18166 // Extra check as FCMOV only supports a subset of X86 cond.
18167 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
18168 SDValue Ops[] = { FalseOp, TrueOp,
18169 DAG.getConstant(CC, MVT::i8), Flags };
18170 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
18171 Ops, array_lengthof(Ops));
18174 // If this is a select between two integer constants, try to do some
18175 // optimizations. Note that the operands are ordered the opposite of SELECT
18177 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
18178 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
18179 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
18180 // larger than FalseC (the false value).
18181 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
18182 CC = X86::GetOppositeBranchCondition(CC);
18183 std::swap(TrueC, FalseC);
18184 std::swap(TrueOp, FalseOp);
18187 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
18188 // This is efficient for any integer data type (including i8/i16) and
18190 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
18191 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18192 DAG.getConstant(CC, MVT::i8), Cond);
18194 // Zero extend the condition if needed.
18195 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
18197 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18198 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
18199 DAG.getConstant(ShAmt, MVT::i8));
18200 if (N->getNumValues() == 2) // Dead flag value?
18201 return DCI.CombineTo(N, Cond, SDValue());
18205 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
18206 // for any integer data type, including i8/i16.
18207 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18208 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18209 DAG.getConstant(CC, MVT::i8), Cond);
18211 // Zero extend the condition if needed.
18212 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18213 FalseC->getValueType(0), Cond);
18214 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18215 SDValue(FalseC, 0));
18217 if (N->getNumValues() == 2) // Dead flag value?
18218 return DCI.CombineTo(N, Cond, SDValue());
18222 // Optimize cases that will turn into an LEA instruction. This requires
18223 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18224 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18225 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18226 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18228 bool isFastMultiplier = false;
18230 switch ((unsigned char)Diff) {
18232 case 1: // result = add base, cond
18233 case 2: // result = lea base( , cond*2)
18234 case 3: // result = lea base(cond, cond*2)
18235 case 4: // result = lea base( , cond*4)
18236 case 5: // result = lea base(cond, cond*4)
18237 case 8: // result = lea base( , cond*8)
18238 case 9: // result = lea base(cond, cond*8)
18239 isFastMultiplier = true;
18244 if (isFastMultiplier) {
18245 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18246 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18247 DAG.getConstant(CC, MVT::i8), Cond);
18248 // Zero extend the condition if needed.
18249 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18251 // Scale the condition by the difference.
18253 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18254 DAG.getConstant(Diff, Cond.getValueType()));
18256 // Add the base if non-zero.
18257 if (FalseC->getAPIntValue() != 0)
18258 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18259 SDValue(FalseC, 0));
18260 if (N->getNumValues() == 2) // Dead flag value?
18261 return DCI.CombineTo(N, Cond, SDValue());
18268 // Handle these cases:
18269 // (select (x != c), e, c) -> select (x != c), e, x),
18270 // (select (x == c), c, e) -> select (x == c), x, e)
18271 // where the c is an integer constant, and the "select" is the combination
18272 // of CMOV and CMP.
18274 // The rationale for this change is that the conditional-move from a constant
18275 // needs two instructions, however, conditional-move from a register needs
18276 // only one instruction.
18278 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
18279 // some instruction-combining opportunities. This opt needs to be
18280 // postponed as late as possible.
18282 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
18283 // the DCI.xxxx conditions are provided to postpone the optimization as
18284 // late as possible.
18286 ConstantSDNode *CmpAgainst = nullptr;
18287 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
18288 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
18289 !isa<ConstantSDNode>(Cond.getOperand(0))) {
18291 if (CC == X86::COND_NE &&
18292 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
18293 CC = X86::GetOppositeBranchCondition(CC);
18294 std::swap(TrueOp, FalseOp);
18297 if (CC == X86::COND_E &&
18298 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
18299 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
18300 DAG.getConstant(CC, MVT::i8), Cond };
18301 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
18302 array_lengthof(Ops));
18310 /// PerformMulCombine - Optimize a single multiply with constant into two
18311 /// in order to implement it with two cheaper instructions, e.g.
18312 /// LEA + SHL, LEA + LEA.
18313 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
18314 TargetLowering::DAGCombinerInfo &DCI) {
18315 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
18318 EVT VT = N->getValueType(0);
18319 if (VT != MVT::i64)
18322 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
18325 uint64_t MulAmt = C->getZExtValue();
18326 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
18329 uint64_t MulAmt1 = 0;
18330 uint64_t MulAmt2 = 0;
18331 if ((MulAmt % 9) == 0) {
18333 MulAmt2 = MulAmt / 9;
18334 } else if ((MulAmt % 5) == 0) {
18336 MulAmt2 = MulAmt / 5;
18337 } else if ((MulAmt % 3) == 0) {
18339 MulAmt2 = MulAmt / 3;
18342 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
18345 if (isPowerOf2_64(MulAmt2) &&
18346 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
18347 // If second multiplifer is pow2, issue it first. We want the multiply by
18348 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
18350 std::swap(MulAmt1, MulAmt2);
18353 if (isPowerOf2_64(MulAmt1))
18354 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
18355 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
18357 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
18358 DAG.getConstant(MulAmt1, VT));
18360 if (isPowerOf2_64(MulAmt2))
18361 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
18362 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
18364 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
18365 DAG.getConstant(MulAmt2, VT));
18367 // Do not add new nodes to DAG combiner worklist.
18368 DCI.CombineTo(N, NewMul, false);
18373 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
18374 SDValue N0 = N->getOperand(0);
18375 SDValue N1 = N->getOperand(1);
18376 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
18377 EVT VT = N0.getValueType();
18379 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
18380 // since the result of setcc_c is all zero's or all ones.
18381 if (VT.isInteger() && !VT.isVector() &&
18382 N1C && N0.getOpcode() == ISD::AND &&
18383 N0.getOperand(1).getOpcode() == ISD::Constant) {
18384 SDValue N00 = N0.getOperand(0);
18385 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
18386 ((N00.getOpcode() == ISD::ANY_EXTEND ||
18387 N00.getOpcode() == ISD::ZERO_EXTEND) &&
18388 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
18389 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
18390 APInt ShAmt = N1C->getAPIntValue();
18391 Mask = Mask.shl(ShAmt);
18393 return DAG.getNode(ISD::AND, SDLoc(N), VT,
18394 N00, DAG.getConstant(Mask, VT));
18398 // Hardware support for vector shifts is sparse which makes us scalarize the
18399 // vector operations in many cases. Also, on sandybridge ADD is faster than
18401 // (shl V, 1) -> add V,V
18402 if (isSplatVector(N1.getNode())) {
18403 assert(N0.getValueType().isVector() && "Invalid vector shift type");
18404 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
18405 // We shift all of the values by one. In many cases we do not have
18406 // hardware support for this operation. This is better expressed as an ADD
18408 if (N1C && (1 == N1C->getZExtValue())) {
18409 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
18416 /// \brief Returns a vector of 0s if the node in input is a vector logical
18417 /// shift by a constant amount which is known to be bigger than or equal
18418 /// to the vector element size in bits.
18419 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
18420 const X86Subtarget *Subtarget) {
18421 EVT VT = N->getValueType(0);
18423 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
18424 (!Subtarget->hasInt256() ||
18425 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
18428 SDValue Amt = N->getOperand(1);
18430 if (isSplatVector(Amt.getNode())) {
18431 SDValue SclrAmt = Amt->getOperand(0);
18432 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
18433 APInt ShiftAmt = C->getAPIntValue();
18434 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
18436 // SSE2/AVX2 logical shifts always return a vector of 0s
18437 // if the shift amount is bigger than or equal to
18438 // the element size. The constant shift amount will be
18439 // encoded as a 8-bit immediate.
18440 if (ShiftAmt.trunc(8).uge(MaxAmount))
18441 return getZeroVector(VT, Subtarget, DAG, DL);
18448 /// PerformShiftCombine - Combine shifts.
18449 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
18450 TargetLowering::DAGCombinerInfo &DCI,
18451 const X86Subtarget *Subtarget) {
18452 if (N->getOpcode() == ISD::SHL) {
18453 SDValue V = PerformSHLCombine(N, DAG);
18454 if (V.getNode()) return V;
18457 if (N->getOpcode() != ISD::SRA) {
18458 // Try to fold this logical shift into a zero vector.
18459 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
18460 if (V.getNode()) return V;
18466 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
18467 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
18468 // and friends. Likewise for OR -> CMPNEQSS.
18469 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
18470 TargetLowering::DAGCombinerInfo &DCI,
18471 const X86Subtarget *Subtarget) {
18474 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
18475 // we're requiring SSE2 for both.
18476 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
18477 SDValue N0 = N->getOperand(0);
18478 SDValue N1 = N->getOperand(1);
18479 SDValue CMP0 = N0->getOperand(1);
18480 SDValue CMP1 = N1->getOperand(1);
18483 // The SETCCs should both refer to the same CMP.
18484 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
18487 SDValue CMP00 = CMP0->getOperand(0);
18488 SDValue CMP01 = CMP0->getOperand(1);
18489 EVT VT = CMP00.getValueType();
18491 if (VT == MVT::f32 || VT == MVT::f64) {
18492 bool ExpectingFlags = false;
18493 // Check for any users that want flags:
18494 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
18495 !ExpectingFlags && UI != UE; ++UI)
18496 switch (UI->getOpcode()) {
18501 ExpectingFlags = true;
18503 case ISD::CopyToReg:
18504 case ISD::SIGN_EXTEND:
18505 case ISD::ZERO_EXTEND:
18506 case ISD::ANY_EXTEND:
18510 if (!ExpectingFlags) {
18511 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
18512 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
18514 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
18515 X86::CondCode tmp = cc0;
18520 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
18521 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
18522 // FIXME: need symbolic constants for these magic numbers.
18523 // See X86ATTInstPrinter.cpp:printSSECC().
18524 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
18525 if (Subtarget->hasAVX512()) {
18526 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
18527 CMP01, DAG.getConstant(x86cc, MVT::i8));
18528 if (N->getValueType(0) != MVT::i1)
18529 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
18533 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
18534 CMP00.getValueType(), CMP00, CMP01,
18535 DAG.getConstant(x86cc, MVT::i8));
18537 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
18538 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
18540 if (is64BitFP && !Subtarget->is64Bit()) {
18541 // On a 32-bit target, we cannot bitcast the 64-bit float to a
18542 // 64-bit integer, since that's not a legal type. Since
18543 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
18544 // bits, but can do this little dance to extract the lowest 32 bits
18545 // and work with those going forward.
18546 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
18548 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
18550 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
18551 Vector32, DAG.getIntPtrConstant(0));
18555 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
18556 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
18557 DAG.getConstant(1, IntVT));
18558 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
18559 return OneBitOfTruth;
18567 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
18568 /// so it can be folded inside ANDNP.
18569 static bool CanFoldXORWithAllOnes(const SDNode *N) {
18570 EVT VT = N->getValueType(0);
18572 // Match direct AllOnes for 128 and 256-bit vectors
18573 if (ISD::isBuildVectorAllOnes(N))
18576 // Look through a bit convert.
18577 if (N->getOpcode() == ISD::BITCAST)
18578 N = N->getOperand(0).getNode();
18580 // Sometimes the operand may come from a insert_subvector building a 256-bit
18582 if (VT.is256BitVector() &&
18583 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
18584 SDValue V1 = N->getOperand(0);
18585 SDValue V2 = N->getOperand(1);
18587 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
18588 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
18589 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
18590 ISD::isBuildVectorAllOnes(V2.getNode()))
18597 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
18598 // register. In most cases we actually compare or select YMM-sized registers
18599 // and mixing the two types creates horrible code. This method optimizes
18600 // some of the transition sequences.
18601 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
18602 TargetLowering::DAGCombinerInfo &DCI,
18603 const X86Subtarget *Subtarget) {
18604 EVT VT = N->getValueType(0);
18605 if (!VT.is256BitVector())
18608 assert((N->getOpcode() == ISD::ANY_EXTEND ||
18609 N->getOpcode() == ISD::ZERO_EXTEND ||
18610 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
18612 SDValue Narrow = N->getOperand(0);
18613 EVT NarrowVT = Narrow->getValueType(0);
18614 if (!NarrowVT.is128BitVector())
18617 if (Narrow->getOpcode() != ISD::XOR &&
18618 Narrow->getOpcode() != ISD::AND &&
18619 Narrow->getOpcode() != ISD::OR)
18622 SDValue N0 = Narrow->getOperand(0);
18623 SDValue N1 = Narrow->getOperand(1);
18626 // The Left side has to be a trunc.
18627 if (N0.getOpcode() != ISD::TRUNCATE)
18630 // The type of the truncated inputs.
18631 EVT WideVT = N0->getOperand(0)->getValueType(0);
18635 // The right side has to be a 'trunc' or a constant vector.
18636 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
18637 bool RHSConst = (isSplatVector(N1.getNode()) &&
18638 isa<ConstantSDNode>(N1->getOperand(0)));
18639 if (!RHSTrunc && !RHSConst)
18642 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18644 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
18647 // Set N0 and N1 to hold the inputs to the new wide operation.
18648 N0 = N0->getOperand(0);
18650 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
18651 N1->getOperand(0));
18652 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
18653 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
18654 } else if (RHSTrunc) {
18655 N1 = N1->getOperand(0);
18658 // Generate the wide operation.
18659 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
18660 unsigned Opcode = N->getOpcode();
18662 case ISD::ANY_EXTEND:
18664 case ISD::ZERO_EXTEND: {
18665 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
18666 APInt Mask = APInt::getAllOnesValue(InBits);
18667 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
18668 return DAG.getNode(ISD::AND, DL, VT,
18669 Op, DAG.getConstant(Mask, VT));
18671 case ISD::SIGN_EXTEND:
18672 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
18673 Op, DAG.getValueType(NarrowVT));
18675 llvm_unreachable("Unexpected opcode");
18679 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
18680 TargetLowering::DAGCombinerInfo &DCI,
18681 const X86Subtarget *Subtarget) {
18682 EVT VT = N->getValueType(0);
18683 if (DCI.isBeforeLegalizeOps())
18686 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18690 // Create BEXTR instructions
18691 // BEXTR is ((X >> imm) & (2**size-1))
18692 if (VT == MVT::i32 || VT == MVT::i64) {
18693 SDValue N0 = N->getOperand(0);
18694 SDValue N1 = N->getOperand(1);
18697 // Check for BEXTR.
18698 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
18699 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
18700 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
18701 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
18702 if (MaskNode && ShiftNode) {
18703 uint64_t Mask = MaskNode->getZExtValue();
18704 uint64_t Shift = ShiftNode->getZExtValue();
18705 if (isMask_64(Mask)) {
18706 uint64_t MaskSize = CountPopulation_64(Mask);
18707 if (Shift + MaskSize <= VT.getSizeInBits())
18708 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
18709 DAG.getConstant(Shift | (MaskSize << 8), VT));
18717 // Want to form ANDNP nodes:
18718 // 1) In the hopes of then easily combining them with OR and AND nodes
18719 // to form PBLEND/PSIGN.
18720 // 2) To match ANDN packed intrinsics
18721 if (VT != MVT::v2i64 && VT != MVT::v4i64)
18724 SDValue N0 = N->getOperand(0);
18725 SDValue N1 = N->getOperand(1);
18728 // Check LHS for vnot
18729 if (N0.getOpcode() == ISD::XOR &&
18730 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
18731 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
18732 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
18734 // Check RHS for vnot
18735 if (N1.getOpcode() == ISD::XOR &&
18736 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
18737 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
18738 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
18743 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
18744 TargetLowering::DAGCombinerInfo &DCI,
18745 const X86Subtarget *Subtarget) {
18746 if (DCI.isBeforeLegalizeOps())
18749 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18753 SDValue N0 = N->getOperand(0);
18754 SDValue N1 = N->getOperand(1);
18755 EVT VT = N->getValueType(0);
18757 // look for psign/blend
18758 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
18759 if (!Subtarget->hasSSSE3() ||
18760 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
18763 // Canonicalize pandn to RHS
18764 if (N0.getOpcode() == X86ISD::ANDNP)
18766 // or (and (m, y), (pandn m, x))
18767 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
18768 SDValue Mask = N1.getOperand(0);
18769 SDValue X = N1.getOperand(1);
18771 if (N0.getOperand(0) == Mask)
18772 Y = N0.getOperand(1);
18773 if (N0.getOperand(1) == Mask)
18774 Y = N0.getOperand(0);
18776 // Check to see if the mask appeared in both the AND and ANDNP and
18780 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
18781 // Look through mask bitcast.
18782 if (Mask.getOpcode() == ISD::BITCAST)
18783 Mask = Mask.getOperand(0);
18784 if (X.getOpcode() == ISD::BITCAST)
18785 X = X.getOperand(0);
18786 if (Y.getOpcode() == ISD::BITCAST)
18787 Y = Y.getOperand(0);
18789 EVT MaskVT = Mask.getValueType();
18791 // Validate that the Mask operand is a vector sra node.
18792 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
18793 // there is no psrai.b
18794 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
18795 unsigned SraAmt = ~0;
18796 if (Mask.getOpcode() == ISD::SRA) {
18797 SDValue Amt = Mask.getOperand(1);
18798 if (isSplatVector(Amt.getNode())) {
18799 SDValue SclrAmt = Amt->getOperand(0);
18800 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
18801 SraAmt = C->getZExtValue();
18803 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
18804 SDValue SraC = Mask.getOperand(1);
18805 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
18807 if ((SraAmt + 1) != EltBits)
18812 // Now we know we at least have a plendvb with the mask val. See if
18813 // we can form a psignb/w/d.
18814 // psign = x.type == y.type == mask.type && y = sub(0, x);
18815 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
18816 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
18817 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
18818 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
18819 "Unsupported VT for PSIGN");
18820 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
18821 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18823 // PBLENDVB only available on SSE 4.1
18824 if (!Subtarget->hasSSE41())
18827 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
18829 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
18830 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
18831 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
18832 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
18833 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18837 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
18840 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
18841 MachineFunction &MF = DAG.getMachineFunction();
18842 bool OptForSize = MF.getFunction()->getAttributes().
18843 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
18845 // SHLD/SHRD instructions have lower register pressure, but on some
18846 // platforms they have higher latency than the equivalent
18847 // series of shifts/or that would otherwise be generated.
18848 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
18849 // have higher latencies and we are not optimizing for size.
18850 if (!OptForSize && Subtarget->isSHLDSlow())
18853 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
18855 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
18857 if (!N0.hasOneUse() || !N1.hasOneUse())
18860 SDValue ShAmt0 = N0.getOperand(1);
18861 if (ShAmt0.getValueType() != MVT::i8)
18863 SDValue ShAmt1 = N1.getOperand(1);
18864 if (ShAmt1.getValueType() != MVT::i8)
18866 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
18867 ShAmt0 = ShAmt0.getOperand(0);
18868 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
18869 ShAmt1 = ShAmt1.getOperand(0);
18872 unsigned Opc = X86ISD::SHLD;
18873 SDValue Op0 = N0.getOperand(0);
18874 SDValue Op1 = N1.getOperand(0);
18875 if (ShAmt0.getOpcode() == ISD::SUB) {
18876 Opc = X86ISD::SHRD;
18877 std::swap(Op0, Op1);
18878 std::swap(ShAmt0, ShAmt1);
18881 unsigned Bits = VT.getSizeInBits();
18882 if (ShAmt1.getOpcode() == ISD::SUB) {
18883 SDValue Sum = ShAmt1.getOperand(0);
18884 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
18885 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
18886 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
18887 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
18888 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
18889 return DAG.getNode(Opc, DL, VT,
18891 DAG.getNode(ISD::TRUNCATE, DL,
18894 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
18895 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
18897 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
18898 return DAG.getNode(Opc, DL, VT,
18899 N0.getOperand(0), N1.getOperand(0),
18900 DAG.getNode(ISD::TRUNCATE, DL,
18907 // Generate NEG and CMOV for integer abs.
18908 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
18909 EVT VT = N->getValueType(0);
18911 // Since X86 does not have CMOV for 8-bit integer, we don't convert
18912 // 8-bit integer abs to NEG and CMOV.
18913 if (VT.isInteger() && VT.getSizeInBits() == 8)
18916 SDValue N0 = N->getOperand(0);
18917 SDValue N1 = N->getOperand(1);
18920 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
18921 // and change it to SUB and CMOV.
18922 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
18923 N0.getOpcode() == ISD::ADD &&
18924 N0.getOperand(1) == N1 &&
18925 N1.getOpcode() == ISD::SRA &&
18926 N1.getOperand(0) == N0.getOperand(0))
18927 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
18928 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
18929 // Generate SUB & CMOV.
18930 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
18931 DAG.getConstant(0, VT), N0.getOperand(0));
18933 SDValue Ops[] = { N0.getOperand(0), Neg,
18934 DAG.getConstant(X86::COND_GE, MVT::i8),
18935 SDValue(Neg.getNode(), 1) };
18936 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
18937 Ops, array_lengthof(Ops));
18942 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
18943 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
18944 TargetLowering::DAGCombinerInfo &DCI,
18945 const X86Subtarget *Subtarget) {
18946 if (DCI.isBeforeLegalizeOps())
18949 if (Subtarget->hasCMov()) {
18950 SDValue RV = performIntegerAbsCombine(N, DAG);
18958 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
18959 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
18960 TargetLowering::DAGCombinerInfo &DCI,
18961 const X86Subtarget *Subtarget) {
18962 LoadSDNode *Ld = cast<LoadSDNode>(N);
18963 EVT RegVT = Ld->getValueType(0);
18964 EVT MemVT = Ld->getMemoryVT();
18966 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18967 unsigned RegSz = RegVT.getSizeInBits();
18969 // On Sandybridge unaligned 256bit loads are inefficient.
18970 ISD::LoadExtType Ext = Ld->getExtensionType();
18971 unsigned Alignment = Ld->getAlignment();
18972 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
18973 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
18974 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
18975 unsigned NumElems = RegVT.getVectorNumElements();
18979 SDValue Ptr = Ld->getBasePtr();
18980 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
18982 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18984 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18985 Ld->getPointerInfo(), Ld->isVolatile(),
18986 Ld->isNonTemporal(), Ld->isInvariant(),
18988 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18989 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18990 Ld->getPointerInfo(), Ld->isVolatile(),
18991 Ld->isNonTemporal(), Ld->isInvariant(),
18992 std::min(16U, Alignment));
18993 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18995 Load2.getValue(1));
18997 SDValue NewVec = DAG.getUNDEF(RegVT);
18998 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
18999 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
19000 return DCI.CombineTo(N, NewVec, TF, true);
19003 // If this is a vector EXT Load then attempt to optimize it using a
19004 // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
19005 // expansion is still better than scalar code.
19006 // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
19007 // emit a shuffle and a arithmetic shift.
19008 // TODO: It is possible to support ZExt by zeroing the undef values
19009 // during the shuffle phase or after the shuffle.
19010 if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
19011 (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
19012 assert(MemVT != RegVT && "Cannot extend to the same type");
19013 assert(MemVT.isVector() && "Must load a vector from memory");
19015 unsigned NumElems = RegVT.getVectorNumElements();
19016 unsigned MemSz = MemVT.getSizeInBits();
19017 assert(RegSz > MemSz && "Register size must be greater than the mem size");
19019 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
19022 // All sizes must be a power of two.
19023 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
19026 // Attempt to load the original value using scalar loads.
19027 // Find the largest scalar type that divides the total loaded size.
19028 MVT SclrLoadTy = MVT::i8;
19029 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19030 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19031 MVT Tp = (MVT::SimpleValueType)tp;
19032 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
19037 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19038 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
19040 SclrLoadTy = MVT::f64;
19042 // Calculate the number of scalar loads that we need to perform
19043 // in order to load our vector from memory.
19044 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
19045 if (Ext == ISD::SEXTLOAD && NumLoads > 1)
19048 unsigned loadRegZize = RegSz;
19049 if (Ext == ISD::SEXTLOAD && RegSz == 256)
19052 // Represent our vector as a sequence of elements which are the
19053 // largest scalar that we can load.
19054 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
19055 loadRegZize/SclrLoadTy.getSizeInBits());
19057 // Represent the data using the same element type that is stored in
19058 // memory. In practice, we ''widen'' MemVT.
19060 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19061 loadRegZize/MemVT.getScalarType().getSizeInBits());
19063 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
19064 "Invalid vector type");
19066 // We can't shuffle using an illegal type.
19067 if (!TLI.isTypeLegal(WideVecVT))
19070 SmallVector<SDValue, 8> Chains;
19071 SDValue Ptr = Ld->getBasePtr();
19072 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
19073 TLI.getPointerTy());
19074 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
19076 for (unsigned i = 0; i < NumLoads; ++i) {
19077 // Perform a single load.
19078 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
19079 Ptr, Ld->getPointerInfo(),
19080 Ld->isVolatile(), Ld->isNonTemporal(),
19081 Ld->isInvariant(), Ld->getAlignment());
19082 Chains.push_back(ScalarLoad.getValue(1));
19083 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
19084 // another round of DAGCombining.
19086 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
19088 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
19089 ScalarLoad, DAG.getIntPtrConstant(i));
19091 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19094 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
19097 // Bitcast the loaded value to a vector of the original element type, in
19098 // the size of the target vector type.
19099 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
19100 unsigned SizeRatio = RegSz/MemSz;
19102 if (Ext == ISD::SEXTLOAD) {
19103 // If we have SSE4.1 we can directly emit a VSEXT node.
19104 if (Subtarget->hasSSE41()) {
19105 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
19106 return DCI.CombineTo(N, Sext, TF, true);
19109 // Otherwise we'll shuffle the small elements in the high bits of the
19110 // larger type and perform an arithmetic shift. If the shift is not legal
19111 // it's better to scalarize.
19112 if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
19115 // Redistribute the loaded elements into the different locations.
19116 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19117 for (unsigned i = 0; i != NumElems; ++i)
19118 ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
19120 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19121 DAG.getUNDEF(WideVecVT),
19124 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19126 // Build the arithmetic shift.
19127 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
19128 MemVT.getVectorElementType().getSizeInBits();
19129 Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
19130 DAG.getConstant(Amt, RegVT));
19132 return DCI.CombineTo(N, Shuff, TF, true);
19135 // Redistribute the loaded elements into the different locations.
19136 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19137 for (unsigned i = 0; i != NumElems; ++i)
19138 ShuffleVec[i*SizeRatio] = i;
19140 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19141 DAG.getUNDEF(WideVecVT),
19144 // Bitcast to the requested type.
19145 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19146 // Replace the original load with the new sequence
19147 // and return the new chain.
19148 return DCI.CombineTo(N, Shuff, TF, true);
19154 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
19155 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
19156 const X86Subtarget *Subtarget) {
19157 StoreSDNode *St = cast<StoreSDNode>(N);
19158 EVT VT = St->getValue().getValueType();
19159 EVT StVT = St->getMemoryVT();
19161 SDValue StoredVal = St->getOperand(1);
19162 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19164 // If we are saving a concatenation of two XMM registers, perform two stores.
19165 // On Sandy Bridge, 256-bit memory operations are executed by two
19166 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
19167 // memory operation.
19168 unsigned Alignment = St->getAlignment();
19169 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
19170 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
19171 StVT == VT && !IsAligned) {
19172 unsigned NumElems = VT.getVectorNumElements();
19176 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
19177 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
19179 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
19180 SDValue Ptr0 = St->getBasePtr();
19181 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
19183 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
19184 St->getPointerInfo(), St->isVolatile(),
19185 St->isNonTemporal(), Alignment);
19186 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
19187 St->getPointerInfo(), St->isVolatile(),
19188 St->isNonTemporal(),
19189 std::min(16U, Alignment));
19190 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
19193 // Optimize trunc store (of multiple scalars) to shuffle and store.
19194 // First, pack all of the elements in one place. Next, store to memory
19195 // in fewer chunks.
19196 if (St->isTruncatingStore() && VT.isVector()) {
19197 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19198 unsigned NumElems = VT.getVectorNumElements();
19199 assert(StVT != VT && "Cannot truncate to the same type");
19200 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
19201 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
19203 // From, To sizes and ElemCount must be pow of two
19204 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
19205 // We are going to use the original vector elt for storing.
19206 // Accumulated smaller vector elements must be a multiple of the store size.
19207 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
19209 unsigned SizeRatio = FromSz / ToSz;
19211 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
19213 // Create a type on which we perform the shuffle
19214 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
19215 StVT.getScalarType(), NumElems*SizeRatio);
19217 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
19219 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
19220 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19221 for (unsigned i = 0; i != NumElems; ++i)
19222 ShuffleVec[i] = i * SizeRatio;
19224 // Can't shuffle using an illegal type.
19225 if (!TLI.isTypeLegal(WideVecVT))
19228 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
19229 DAG.getUNDEF(WideVecVT),
19231 // At this point all of the data is stored at the bottom of the
19232 // register. We now need to save it to mem.
19234 // Find the largest store unit
19235 MVT StoreType = MVT::i8;
19236 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19237 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19238 MVT Tp = (MVT::SimpleValueType)tp;
19239 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
19243 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19244 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
19245 (64 <= NumElems * ToSz))
19246 StoreType = MVT::f64;
19248 // Bitcast the original vector into a vector of store-size units
19249 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
19250 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
19251 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
19252 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
19253 SmallVector<SDValue, 8> Chains;
19254 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
19255 TLI.getPointerTy());
19256 SDValue Ptr = St->getBasePtr();
19258 // Perform one or more big stores into memory.
19259 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
19260 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
19261 StoreType, ShuffWide,
19262 DAG.getIntPtrConstant(i));
19263 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
19264 St->getPointerInfo(), St->isVolatile(),
19265 St->isNonTemporal(), St->getAlignment());
19266 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19267 Chains.push_back(Ch);
19270 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
19274 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
19275 // the FP state in cases where an emms may be missing.
19276 // A preferable solution to the general problem is to figure out the right
19277 // places to insert EMMS. This qualifies as a quick hack.
19279 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
19280 if (VT.getSizeInBits() != 64)
19283 const Function *F = DAG.getMachineFunction().getFunction();
19284 bool NoImplicitFloatOps = F->getAttributes().
19285 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
19286 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
19287 && Subtarget->hasSSE2();
19288 if ((VT.isVector() ||
19289 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
19290 isa<LoadSDNode>(St->getValue()) &&
19291 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
19292 St->getChain().hasOneUse() && !St->isVolatile()) {
19293 SDNode* LdVal = St->getValue().getNode();
19294 LoadSDNode *Ld = nullptr;
19295 int TokenFactorIndex = -1;
19296 SmallVector<SDValue, 8> Ops;
19297 SDNode* ChainVal = St->getChain().getNode();
19298 // Must be a store of a load. We currently handle two cases: the load
19299 // is a direct child, and it's under an intervening TokenFactor. It is
19300 // possible to dig deeper under nested TokenFactors.
19301 if (ChainVal == LdVal)
19302 Ld = cast<LoadSDNode>(St->getChain());
19303 else if (St->getValue().hasOneUse() &&
19304 ChainVal->getOpcode() == ISD::TokenFactor) {
19305 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
19306 if (ChainVal->getOperand(i).getNode() == LdVal) {
19307 TokenFactorIndex = i;
19308 Ld = cast<LoadSDNode>(St->getValue());
19310 Ops.push_back(ChainVal->getOperand(i));
19314 if (!Ld || !ISD::isNormalLoad(Ld))
19317 // If this is not the MMX case, i.e. we are just turning i64 load/store
19318 // into f64 load/store, avoid the transformation if there are multiple
19319 // uses of the loaded value.
19320 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
19325 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
19326 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
19328 if (Subtarget->is64Bit() || F64IsLegal) {
19329 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
19330 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
19331 Ld->getPointerInfo(), Ld->isVolatile(),
19332 Ld->isNonTemporal(), Ld->isInvariant(),
19333 Ld->getAlignment());
19334 SDValue NewChain = NewLd.getValue(1);
19335 if (TokenFactorIndex != -1) {
19336 Ops.push_back(NewChain);
19337 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
19340 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
19341 St->getPointerInfo(),
19342 St->isVolatile(), St->isNonTemporal(),
19343 St->getAlignment());
19346 // Otherwise, lower to two pairs of 32-bit loads / stores.
19347 SDValue LoAddr = Ld->getBasePtr();
19348 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
19349 DAG.getConstant(4, MVT::i32));
19351 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
19352 Ld->getPointerInfo(),
19353 Ld->isVolatile(), Ld->isNonTemporal(),
19354 Ld->isInvariant(), Ld->getAlignment());
19355 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
19356 Ld->getPointerInfo().getWithOffset(4),
19357 Ld->isVolatile(), Ld->isNonTemporal(),
19359 MinAlign(Ld->getAlignment(), 4));
19361 SDValue NewChain = LoLd.getValue(1);
19362 if (TokenFactorIndex != -1) {
19363 Ops.push_back(LoLd);
19364 Ops.push_back(HiLd);
19365 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
19369 LoAddr = St->getBasePtr();
19370 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
19371 DAG.getConstant(4, MVT::i32));
19373 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
19374 St->getPointerInfo(),
19375 St->isVolatile(), St->isNonTemporal(),
19376 St->getAlignment());
19377 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
19378 St->getPointerInfo().getWithOffset(4),
19380 St->isNonTemporal(),
19381 MinAlign(St->getAlignment(), 4));
19382 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
19387 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
19388 /// and return the operands for the horizontal operation in LHS and RHS. A
19389 /// horizontal operation performs the binary operation on successive elements
19390 /// of its first operand, then on successive elements of its second operand,
19391 /// returning the resulting values in a vector. For example, if
19392 /// A = < float a0, float a1, float a2, float a3 >
19394 /// B = < float b0, float b1, float b2, float b3 >
19395 /// then the result of doing a horizontal operation on A and B is
19396 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
19397 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
19398 /// A horizontal-op B, for some already available A and B, and if so then LHS is
19399 /// set to A, RHS to B, and the routine returns 'true'.
19400 /// Note that the binary operation should have the property that if one of the
19401 /// operands is UNDEF then the result is UNDEF.
19402 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
19403 // Look for the following pattern: if
19404 // A = < float a0, float a1, float a2, float a3 >
19405 // B = < float b0, float b1, float b2, float b3 >
19407 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
19408 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
19409 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
19410 // which is A horizontal-op B.
19412 // At least one of the operands should be a vector shuffle.
19413 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
19414 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
19417 MVT VT = LHS.getSimpleValueType();
19419 assert((VT.is128BitVector() || VT.is256BitVector()) &&
19420 "Unsupported vector type for horizontal add/sub");
19422 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
19423 // operate independently on 128-bit lanes.
19424 unsigned NumElts = VT.getVectorNumElements();
19425 unsigned NumLanes = VT.getSizeInBits()/128;
19426 unsigned NumLaneElts = NumElts / NumLanes;
19427 assert((NumLaneElts % 2 == 0) &&
19428 "Vector type should have an even number of elements in each lane");
19429 unsigned HalfLaneElts = NumLaneElts/2;
19431 // View LHS in the form
19432 // LHS = VECTOR_SHUFFLE A, B, LMask
19433 // If LHS is not a shuffle then pretend it is the shuffle
19434 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
19435 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
19438 SmallVector<int, 16> LMask(NumElts);
19439 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19440 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
19441 A = LHS.getOperand(0);
19442 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
19443 B = LHS.getOperand(1);
19444 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
19445 std::copy(Mask.begin(), Mask.end(), LMask.begin());
19447 if (LHS.getOpcode() != ISD::UNDEF)
19449 for (unsigned i = 0; i != NumElts; ++i)
19453 // Likewise, view RHS in the form
19454 // RHS = VECTOR_SHUFFLE C, D, RMask
19456 SmallVector<int, 16> RMask(NumElts);
19457 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19458 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
19459 C = RHS.getOperand(0);
19460 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
19461 D = RHS.getOperand(1);
19462 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
19463 std::copy(Mask.begin(), Mask.end(), RMask.begin());
19465 if (RHS.getOpcode() != ISD::UNDEF)
19467 for (unsigned i = 0; i != NumElts; ++i)
19471 // Check that the shuffles are both shuffling the same vectors.
19472 if (!(A == C && B == D) && !(A == D && B == C))
19475 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
19476 if (!A.getNode() && !B.getNode())
19479 // If A and B occur in reverse order in RHS, then "swap" them (which means
19480 // rewriting the mask).
19482 CommuteVectorShuffleMask(RMask, NumElts);
19484 // At this point LHS and RHS are equivalent to
19485 // LHS = VECTOR_SHUFFLE A, B, LMask
19486 // RHS = VECTOR_SHUFFLE A, B, RMask
19487 // Check that the masks correspond to performing a horizontal operation.
19488 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
19489 for (unsigned i = 0; i != NumLaneElts; ++i) {
19490 int LIdx = LMask[i+l], RIdx = RMask[i+l];
19492 // Ignore any UNDEF components.
19493 if (LIdx < 0 || RIdx < 0 ||
19494 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
19495 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
19498 // Check that successive elements are being operated on. If not, this is
19499 // not a horizontal operation.
19500 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
19501 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
19502 if (!(LIdx == Index && RIdx == Index + 1) &&
19503 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
19508 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
19509 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
19513 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
19514 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
19515 const X86Subtarget *Subtarget) {
19516 EVT VT = N->getValueType(0);
19517 SDValue LHS = N->getOperand(0);
19518 SDValue RHS = N->getOperand(1);
19520 // Try to synthesize horizontal adds from adds of shuffles.
19521 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19522 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19523 isHorizontalBinOp(LHS, RHS, true))
19524 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
19528 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
19529 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
19530 const X86Subtarget *Subtarget) {
19531 EVT VT = N->getValueType(0);
19532 SDValue LHS = N->getOperand(0);
19533 SDValue RHS = N->getOperand(1);
19535 // Try to synthesize horizontal subs from subs of shuffles.
19536 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19537 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19538 isHorizontalBinOp(LHS, RHS, false))
19539 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
19543 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
19544 /// X86ISD::FXOR nodes.
19545 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
19546 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
19547 // F[X]OR(0.0, x) -> x
19548 // F[X]OR(x, 0.0) -> x
19549 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19550 if (C->getValueAPF().isPosZero())
19551 return N->getOperand(1);
19552 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19553 if (C->getValueAPF().isPosZero())
19554 return N->getOperand(0);
19558 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
19559 /// X86ISD::FMAX nodes.
19560 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
19561 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
19563 // Only perform optimizations if UnsafeMath is used.
19564 if (!DAG.getTarget().Options.UnsafeFPMath)
19567 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
19568 // into FMINC and FMAXC, which are Commutative operations.
19569 unsigned NewOp = 0;
19570 switch (N->getOpcode()) {
19571 default: llvm_unreachable("unknown opcode");
19572 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
19573 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
19576 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
19577 N->getOperand(0), N->getOperand(1));
19580 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
19581 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
19582 // FAND(0.0, x) -> 0.0
19583 // FAND(x, 0.0) -> 0.0
19584 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19585 if (C->getValueAPF().isPosZero())
19586 return N->getOperand(0);
19587 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19588 if (C->getValueAPF().isPosZero())
19589 return N->getOperand(1);
19593 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
19594 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
19595 // FANDN(x, 0.0) -> 0.0
19596 // FANDN(0.0, x) -> x
19597 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19598 if (C->getValueAPF().isPosZero())
19599 return N->getOperand(1);
19600 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19601 if (C->getValueAPF().isPosZero())
19602 return N->getOperand(1);
19606 static SDValue PerformBTCombine(SDNode *N,
19608 TargetLowering::DAGCombinerInfo &DCI) {
19609 // BT ignores high bits in the bit index operand.
19610 SDValue Op1 = N->getOperand(1);
19611 if (Op1.hasOneUse()) {
19612 unsigned BitWidth = Op1.getValueSizeInBits();
19613 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
19614 APInt KnownZero, KnownOne;
19615 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
19616 !DCI.isBeforeLegalizeOps());
19617 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19618 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
19619 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
19620 DCI.CommitTargetLoweringOpt(TLO);
19625 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
19626 SDValue Op = N->getOperand(0);
19627 if (Op.getOpcode() == ISD::BITCAST)
19628 Op = Op.getOperand(0);
19629 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
19630 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
19631 VT.getVectorElementType().getSizeInBits() ==
19632 OpVT.getVectorElementType().getSizeInBits()) {
19633 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
19638 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
19639 const X86Subtarget *Subtarget) {
19640 EVT VT = N->getValueType(0);
19641 if (!VT.isVector())
19644 SDValue N0 = N->getOperand(0);
19645 SDValue N1 = N->getOperand(1);
19646 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
19649 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
19650 // both SSE and AVX2 since there is no sign-extended shift right
19651 // operation on a vector with 64-bit elements.
19652 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
19653 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
19654 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
19655 N0.getOpcode() == ISD::SIGN_EXTEND)) {
19656 SDValue N00 = N0.getOperand(0);
19658 // EXTLOAD has a better solution on AVX2,
19659 // it may be replaced with X86ISD::VSEXT node.
19660 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
19661 if (!ISD::isNormalLoad(N00.getNode()))
19664 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
19665 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
19667 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
19673 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
19674 TargetLowering::DAGCombinerInfo &DCI,
19675 const X86Subtarget *Subtarget) {
19676 if (!DCI.isBeforeLegalizeOps())
19679 if (!Subtarget->hasFp256())
19682 EVT VT = N->getValueType(0);
19683 if (VT.isVector() && VT.getSizeInBits() == 256) {
19684 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19692 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
19693 const X86Subtarget* Subtarget) {
19695 EVT VT = N->getValueType(0);
19697 // Let legalize expand this if it isn't a legal type yet.
19698 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19701 EVT ScalarVT = VT.getScalarType();
19702 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
19703 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
19706 SDValue A = N->getOperand(0);
19707 SDValue B = N->getOperand(1);
19708 SDValue C = N->getOperand(2);
19710 bool NegA = (A.getOpcode() == ISD::FNEG);
19711 bool NegB = (B.getOpcode() == ISD::FNEG);
19712 bool NegC = (C.getOpcode() == ISD::FNEG);
19714 // Negative multiplication when NegA xor NegB
19715 bool NegMul = (NegA != NegB);
19717 A = A.getOperand(0);
19719 B = B.getOperand(0);
19721 C = C.getOperand(0);
19725 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
19727 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
19729 return DAG.getNode(Opcode, dl, VT, A, B, C);
19732 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
19733 TargetLowering::DAGCombinerInfo &DCI,
19734 const X86Subtarget *Subtarget) {
19735 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
19736 // (and (i32 x86isd::setcc_carry), 1)
19737 // This eliminates the zext. This transformation is necessary because
19738 // ISD::SETCC is always legalized to i8.
19740 SDValue N0 = N->getOperand(0);
19741 EVT VT = N->getValueType(0);
19743 if (N0.getOpcode() == ISD::AND &&
19745 N0.getOperand(0).hasOneUse()) {
19746 SDValue N00 = N0.getOperand(0);
19747 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19748 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19749 if (!C || C->getZExtValue() != 1)
19751 return DAG.getNode(ISD::AND, dl, VT,
19752 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19753 N00.getOperand(0), N00.getOperand(1)),
19754 DAG.getConstant(1, VT));
19758 if (N0.getOpcode() == ISD::TRUNCATE &&
19760 N0.getOperand(0).hasOneUse()) {
19761 SDValue N00 = N0.getOperand(0);
19762 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19763 return DAG.getNode(ISD::AND, dl, VT,
19764 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19765 N00.getOperand(0), N00.getOperand(1)),
19766 DAG.getConstant(1, VT));
19769 if (VT.is256BitVector()) {
19770 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19778 // Optimize x == -y --> x+y == 0
19779 // x != -y --> x+y != 0
19780 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
19781 const X86Subtarget* Subtarget) {
19782 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
19783 SDValue LHS = N->getOperand(0);
19784 SDValue RHS = N->getOperand(1);
19785 EVT VT = N->getValueType(0);
19788 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
19789 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
19790 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
19791 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19792 LHS.getValueType(), RHS, LHS.getOperand(1));
19793 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19794 addV, DAG.getConstant(0, addV.getValueType()), CC);
19796 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
19797 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
19798 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
19799 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19800 RHS.getValueType(), LHS, RHS.getOperand(1));
19801 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19802 addV, DAG.getConstant(0, addV.getValueType()), CC);
19805 if (VT.getScalarType() == MVT::i1) {
19806 bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
19807 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
19808 bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
19809 if (!IsSEXT0 && !IsVZero0)
19811 bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
19812 (RHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
19813 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
19815 if (!IsSEXT1 && !IsVZero1)
19818 if (IsSEXT0 && IsVZero1) {
19819 assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
19820 if (CC == ISD::SETEQ)
19821 return DAG.getNOT(DL, LHS.getOperand(0), VT);
19822 return LHS.getOperand(0);
19824 if (IsSEXT1 && IsVZero0) {
19825 assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
19826 if (CC == ISD::SETEQ)
19827 return DAG.getNOT(DL, RHS.getOperand(0), VT);
19828 return RHS.getOperand(0);
19835 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
19836 // as "sbb reg,reg", since it can be extended without zext and produces
19837 // an all-ones bit which is more useful than 0/1 in some cases.
19838 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
19841 return DAG.getNode(ISD::AND, DL, VT,
19842 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19843 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
19844 DAG.getConstant(1, VT));
19845 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
19846 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
19847 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19848 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
19851 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
19852 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
19853 TargetLowering::DAGCombinerInfo &DCI,
19854 const X86Subtarget *Subtarget) {
19856 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
19857 SDValue EFLAGS = N->getOperand(1);
19859 if (CC == X86::COND_A) {
19860 // Try to convert COND_A into COND_B in an attempt to facilitate
19861 // materializing "setb reg".
19863 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
19864 // cannot take an immediate as its first operand.
19866 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
19867 EFLAGS.getValueType().isInteger() &&
19868 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
19869 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
19870 EFLAGS.getNode()->getVTList(),
19871 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
19872 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
19873 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
19877 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
19878 // a zext and produces an all-ones bit which is more useful than 0/1 in some
19880 if (CC == X86::COND_B)
19881 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
19885 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19886 if (Flags.getNode()) {
19887 SDValue Cond = DAG.getConstant(CC, MVT::i8);
19888 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
19894 // Optimize branch condition evaluation.
19896 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
19897 TargetLowering::DAGCombinerInfo &DCI,
19898 const X86Subtarget *Subtarget) {
19900 SDValue Chain = N->getOperand(0);
19901 SDValue Dest = N->getOperand(1);
19902 SDValue EFLAGS = N->getOperand(3);
19903 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
19907 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19908 if (Flags.getNode()) {
19909 SDValue Cond = DAG.getConstant(CC, MVT::i8);
19910 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
19917 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
19918 const X86TargetLowering *XTLI) {
19919 SDValue Op0 = N->getOperand(0);
19920 EVT InVT = Op0->getValueType(0);
19922 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
19923 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
19925 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
19926 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
19927 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
19930 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
19931 // a 32-bit target where SSE doesn't support i64->FP operations.
19932 if (Op0.getOpcode() == ISD::LOAD) {
19933 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
19934 EVT VT = Ld->getValueType(0);
19935 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
19936 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
19937 !XTLI->getSubtarget()->is64Bit() &&
19939 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
19940 Ld->getChain(), Op0, DAG);
19941 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
19948 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
19949 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
19950 X86TargetLowering::DAGCombinerInfo &DCI) {
19951 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
19952 // the result is either zero or one (depending on the input carry bit).
19953 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
19954 if (X86::isZeroNode(N->getOperand(0)) &&
19955 X86::isZeroNode(N->getOperand(1)) &&
19956 // We don't have a good way to replace an EFLAGS use, so only do this when
19958 SDValue(N, 1).use_empty()) {
19960 EVT VT = N->getValueType(0);
19961 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
19962 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
19963 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
19964 DAG.getConstant(X86::COND_B,MVT::i8),
19966 DAG.getConstant(1, VT));
19967 return DCI.CombineTo(N, Res1, CarryOut);
19973 // fold (add Y, (sete X, 0)) -> adc 0, Y
19974 // (add Y, (setne X, 0)) -> sbb -1, Y
19975 // (sub (sete X, 0), Y) -> sbb 0, Y
19976 // (sub (setne X, 0), Y) -> adc -1, Y
19977 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
19980 // Look through ZExts.
19981 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
19982 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
19985 SDValue SetCC = Ext.getOperand(0);
19986 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
19989 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
19990 if (CC != X86::COND_E && CC != X86::COND_NE)
19993 SDValue Cmp = SetCC.getOperand(1);
19994 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
19995 !X86::isZeroNode(Cmp.getOperand(1)) ||
19996 !Cmp.getOperand(0).getValueType().isInteger())
19999 SDValue CmpOp0 = Cmp.getOperand(0);
20000 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
20001 DAG.getConstant(1, CmpOp0.getValueType()));
20003 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
20004 if (CC == X86::COND_NE)
20005 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
20006 DL, OtherVal.getValueType(), OtherVal,
20007 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
20008 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
20009 DL, OtherVal.getValueType(), OtherVal,
20010 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
20013 /// PerformADDCombine - Do target-specific dag combines on integer adds.
20014 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
20015 const X86Subtarget *Subtarget) {
20016 EVT VT = N->getValueType(0);
20017 SDValue Op0 = N->getOperand(0);
20018 SDValue Op1 = N->getOperand(1);
20020 // Try to synthesize horizontal adds from adds of shuffles.
20021 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20022 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20023 isHorizontalBinOp(Op0, Op1, true))
20024 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
20026 return OptimizeConditionalInDecrement(N, DAG);
20029 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
20030 const X86Subtarget *Subtarget) {
20031 SDValue Op0 = N->getOperand(0);
20032 SDValue Op1 = N->getOperand(1);
20034 // X86 can't encode an immediate LHS of a sub. See if we can push the
20035 // negation into a preceding instruction.
20036 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
20037 // If the RHS of the sub is a XOR with one use and a constant, invert the
20038 // immediate. Then add one to the LHS of the sub so we can turn
20039 // X-Y -> X+~Y+1, saving one register.
20040 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
20041 isa<ConstantSDNode>(Op1.getOperand(1))) {
20042 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
20043 EVT VT = Op0.getValueType();
20044 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
20046 DAG.getConstant(~XorC, VT));
20047 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
20048 DAG.getConstant(C->getAPIntValue()+1, VT));
20052 // Try to synthesize horizontal adds from adds of shuffles.
20053 EVT VT = N->getValueType(0);
20054 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20055 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20056 isHorizontalBinOp(Op0, Op1, true))
20057 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
20059 return OptimizeConditionalInDecrement(N, DAG);
20062 /// performVZEXTCombine - Performs build vector combines
20063 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
20064 TargetLowering::DAGCombinerInfo &DCI,
20065 const X86Subtarget *Subtarget) {
20066 // (vzext (bitcast (vzext (x)) -> (vzext x)
20067 SDValue In = N->getOperand(0);
20068 while (In.getOpcode() == ISD::BITCAST)
20069 In = In.getOperand(0);
20071 if (In.getOpcode() != X86ISD::VZEXT)
20074 return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
20078 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
20079 DAGCombinerInfo &DCI) const {
20080 SelectionDAG &DAG = DCI.DAG;
20081 switch (N->getOpcode()) {
20083 case ISD::EXTRACT_VECTOR_ELT:
20084 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
20086 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
20087 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
20088 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
20089 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
20090 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
20091 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
20094 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
20095 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
20096 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
20097 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
20098 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
20099 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
20100 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
20101 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
20102 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
20104 case X86ISD::FOR: return PerformFORCombine(N, DAG);
20106 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
20107 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
20108 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
20109 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
20110 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
20111 case ISD::ANY_EXTEND:
20112 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
20113 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
20114 case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
20115 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
20116 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
20117 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
20118 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
20119 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
20120 case X86ISD::SHUFP: // Handle all target specific shuffles
20121 case X86ISD::PALIGNR:
20122 case X86ISD::UNPCKH:
20123 case X86ISD::UNPCKL:
20124 case X86ISD::MOVHLPS:
20125 case X86ISD::MOVLHPS:
20126 case X86ISD::PSHUFD:
20127 case X86ISD::PSHUFHW:
20128 case X86ISD::PSHUFLW:
20129 case X86ISD::MOVSS:
20130 case X86ISD::MOVSD:
20131 case X86ISD::VPERMILP:
20132 case X86ISD::VPERM2X128:
20133 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
20134 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
20140 /// isTypeDesirableForOp - Return true if the target has native support for
20141 /// the specified value type and it is 'desirable' to use the type for the
20142 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
20143 /// instruction encodings are longer and some i16 instructions are slow.
20144 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
20145 if (!isTypeLegal(VT))
20147 if (VT != MVT::i16)
20154 case ISD::SIGN_EXTEND:
20155 case ISD::ZERO_EXTEND:
20156 case ISD::ANY_EXTEND:
20169 /// IsDesirableToPromoteOp - This method query the target whether it is
20170 /// beneficial for dag combiner to promote the specified node. If true, it
20171 /// should return the desired promotion type by reference.
20172 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
20173 EVT VT = Op.getValueType();
20174 if (VT != MVT::i16)
20177 bool Promote = false;
20178 bool Commute = false;
20179 switch (Op.getOpcode()) {
20182 LoadSDNode *LD = cast<LoadSDNode>(Op);
20183 // If the non-extending load has a single use and it's not live out, then it
20184 // might be folded.
20185 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
20186 Op.hasOneUse()*/) {
20187 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
20188 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
20189 // The only case where we'd want to promote LOAD (rather then it being
20190 // promoted as an operand is when it's only use is liveout.
20191 if (UI->getOpcode() != ISD::CopyToReg)
20198 case ISD::SIGN_EXTEND:
20199 case ISD::ZERO_EXTEND:
20200 case ISD::ANY_EXTEND:
20205 SDValue N0 = Op.getOperand(0);
20206 // Look out for (store (shl (load), x)).
20207 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
20220 SDValue N0 = Op.getOperand(0);
20221 SDValue N1 = Op.getOperand(1);
20222 if (!Commute && MayFoldLoad(N1))
20224 // Avoid disabling potential load folding opportunities.
20225 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
20227 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
20237 //===----------------------------------------------------------------------===//
20238 // X86 Inline Assembly Support
20239 //===----------------------------------------------------------------------===//
20242 // Helper to match a string separated by whitespace.
20243 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
20244 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
20246 for (unsigned i = 0, e = args.size(); i != e; ++i) {
20247 StringRef piece(*args[i]);
20248 if (!s.startswith(piece)) // Check if the piece matches.
20251 s = s.substr(piece.size());
20252 StringRef::size_type pos = s.find_first_not_of(" \t");
20253 if (pos == 0) // We matched a prefix.
20261 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
20264 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
20266 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
20267 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
20268 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
20269 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
20271 if (AsmPieces.size() == 3)
20273 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
20280 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
20281 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
20283 std::string AsmStr = IA->getAsmString();
20285 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
20286 if (!Ty || Ty->getBitWidth() % 16 != 0)
20289 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
20290 SmallVector<StringRef, 4> AsmPieces;
20291 SplitString(AsmStr, AsmPieces, ";\n");
20293 switch (AsmPieces.size()) {
20294 default: return false;
20296 // FIXME: this should verify that we are targeting a 486 or better. If not,
20297 // we will turn this bswap into something that will be lowered to logical
20298 // ops instead of emitting the bswap asm. For now, we don't support 486 or
20299 // lower so don't worry about this.
20301 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
20302 matchAsm(AsmPieces[0], "bswapl", "$0") ||
20303 matchAsm(AsmPieces[0], "bswapq", "$0") ||
20304 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
20305 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
20306 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
20307 // No need to check constraints, nothing other than the equivalent of
20308 // "=r,0" would be valid here.
20309 return IntrinsicLowering::LowerToByteSwap(CI);
20312 // rorw $$8, ${0:w} --> llvm.bswap.i16
20313 if (CI->getType()->isIntegerTy(16) &&
20314 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20315 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
20316 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
20318 const std::string &ConstraintsStr = IA->getConstraintString();
20319 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20320 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20321 if (clobbersFlagRegisters(AsmPieces))
20322 return IntrinsicLowering::LowerToByteSwap(CI);
20326 if (CI->getType()->isIntegerTy(32) &&
20327 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20328 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
20329 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
20330 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
20332 const std::string &ConstraintsStr = IA->getConstraintString();
20333 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20334 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20335 if (clobbersFlagRegisters(AsmPieces))
20336 return IntrinsicLowering::LowerToByteSwap(CI);
20339 if (CI->getType()->isIntegerTy(64)) {
20340 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
20341 if (Constraints.size() >= 2 &&
20342 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
20343 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
20344 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
20345 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
20346 matchAsm(AsmPieces[1], "bswap", "%edx") &&
20347 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
20348 return IntrinsicLowering::LowerToByteSwap(CI);
20356 /// getConstraintType - Given a constraint letter, return the type of
20357 /// constraint it is for this target.
20358 X86TargetLowering::ConstraintType
20359 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
20360 if (Constraint.size() == 1) {
20361 switch (Constraint[0]) {
20372 return C_RegisterClass;
20396 return TargetLowering::getConstraintType(Constraint);
20399 /// Examine constraint type and operand type and determine a weight value.
20400 /// This object must already have been set up with the operand type
20401 /// and the current alternative constraint selected.
20402 TargetLowering::ConstraintWeight
20403 X86TargetLowering::getSingleConstraintMatchWeight(
20404 AsmOperandInfo &info, const char *constraint) const {
20405 ConstraintWeight weight = CW_Invalid;
20406 Value *CallOperandVal = info.CallOperandVal;
20407 // If we don't have a value, we can't do a match,
20408 // but allow it at the lowest weight.
20409 if (!CallOperandVal)
20411 Type *type = CallOperandVal->getType();
20412 // Look at the constraint type.
20413 switch (*constraint) {
20415 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
20426 if (CallOperandVal->getType()->isIntegerTy())
20427 weight = CW_SpecificReg;
20432 if (type->isFloatingPointTy())
20433 weight = CW_SpecificReg;
20436 if (type->isX86_MMXTy() && Subtarget->hasMMX())
20437 weight = CW_SpecificReg;
20441 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
20442 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
20443 weight = CW_Register;
20446 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
20447 if (C->getZExtValue() <= 31)
20448 weight = CW_Constant;
20452 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20453 if (C->getZExtValue() <= 63)
20454 weight = CW_Constant;
20458 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20459 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
20460 weight = CW_Constant;
20464 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20465 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
20466 weight = CW_Constant;
20470 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20471 if (C->getZExtValue() <= 3)
20472 weight = CW_Constant;
20476 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20477 if (C->getZExtValue() <= 0xff)
20478 weight = CW_Constant;
20483 if (dyn_cast<ConstantFP>(CallOperandVal)) {
20484 weight = CW_Constant;
20488 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20489 if ((C->getSExtValue() >= -0x80000000LL) &&
20490 (C->getSExtValue() <= 0x7fffffffLL))
20491 weight = CW_Constant;
20495 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20496 if (C->getZExtValue() <= 0xffffffff)
20497 weight = CW_Constant;
20504 /// LowerXConstraint - try to replace an X constraint, which matches anything,
20505 /// with another that has more specific requirements based on the type of the
20506 /// corresponding operand.
20507 const char *X86TargetLowering::
20508 LowerXConstraint(EVT ConstraintVT) const {
20509 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
20510 // 'f' like normal targets.
20511 if (ConstraintVT.isFloatingPoint()) {
20512 if (Subtarget->hasSSE2())
20514 if (Subtarget->hasSSE1())
20518 return TargetLowering::LowerXConstraint(ConstraintVT);
20521 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
20522 /// vector. If it is invalid, don't add anything to Ops.
20523 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
20524 std::string &Constraint,
20525 std::vector<SDValue>&Ops,
20526 SelectionDAG &DAG) const {
20529 // Only support length 1 constraints for now.
20530 if (Constraint.length() > 1) return;
20532 char ConstraintLetter = Constraint[0];
20533 switch (ConstraintLetter) {
20536 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20537 if (C->getZExtValue() <= 31) {
20538 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20544 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20545 if (C->getZExtValue() <= 63) {
20546 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20552 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20553 if (isInt<8>(C->getSExtValue())) {
20554 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20560 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20561 if (C->getZExtValue() <= 255) {
20562 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20568 // 32-bit signed value
20569 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20570 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20571 C->getSExtValue())) {
20572 // Widen to 64 bits here to get it sign extended.
20573 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
20576 // FIXME gcc accepts some relocatable values here too, but only in certain
20577 // memory models; it's complicated.
20582 // 32-bit unsigned value
20583 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20584 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20585 C->getZExtValue())) {
20586 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20590 // FIXME gcc accepts some relocatable values here too, but only in certain
20591 // memory models; it's complicated.
20595 // Literal immediates are always ok.
20596 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
20597 // Widen to 64 bits here to get it sign extended.
20598 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
20602 // In any sort of PIC mode addresses need to be computed at runtime by
20603 // adding in a register or some sort of table lookup. These can't
20604 // be used as immediates.
20605 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
20608 // If we are in non-pic codegen mode, we allow the address of a global (with
20609 // an optional displacement) to be used with 'i'.
20610 GlobalAddressSDNode *GA = nullptr;
20611 int64_t Offset = 0;
20613 // Match either (GA), (GA+C), (GA+C1+C2), etc.
20615 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
20616 Offset += GA->getOffset();
20618 } else if (Op.getOpcode() == ISD::ADD) {
20619 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20620 Offset += C->getZExtValue();
20621 Op = Op.getOperand(0);
20624 } else if (Op.getOpcode() == ISD::SUB) {
20625 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20626 Offset += -C->getZExtValue();
20627 Op = Op.getOperand(0);
20632 // Otherwise, this isn't something we can handle, reject it.
20636 const GlobalValue *GV = GA->getGlobal();
20637 // If we require an extra load to get this address, as in PIC mode, we
20638 // can't accept it.
20639 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
20640 getTargetMachine())))
20643 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
20644 GA->getValueType(0), Offset);
20649 if (Result.getNode()) {
20650 Ops.push_back(Result);
20653 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
20656 std::pair<unsigned, const TargetRegisterClass*>
20657 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
20659 // First, see if this is a constraint that directly corresponds to an LLVM
20661 if (Constraint.size() == 1) {
20662 // GCC Constraint Letters
20663 switch (Constraint[0]) {
20665 // TODO: Slight differences here in allocation order and leaving
20666 // RIP in the class. Do they matter any more here than they do
20667 // in the normal allocation?
20668 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
20669 if (Subtarget->is64Bit()) {
20670 if (VT == MVT::i32 || VT == MVT::f32)
20671 return std::make_pair(0U, &X86::GR32RegClass);
20672 if (VT == MVT::i16)
20673 return std::make_pair(0U, &X86::GR16RegClass);
20674 if (VT == MVT::i8 || VT == MVT::i1)
20675 return std::make_pair(0U, &X86::GR8RegClass);
20676 if (VT == MVT::i64 || VT == MVT::f64)
20677 return std::make_pair(0U, &X86::GR64RegClass);
20680 // 32-bit fallthrough
20681 case 'Q': // Q_REGS
20682 if (VT == MVT::i32 || VT == MVT::f32)
20683 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
20684 if (VT == MVT::i16)
20685 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
20686 if (VT == MVT::i8 || VT == MVT::i1)
20687 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
20688 if (VT == MVT::i64)
20689 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
20691 case 'r': // GENERAL_REGS
20692 case 'l': // INDEX_REGS
20693 if (VT == MVT::i8 || VT == MVT::i1)
20694 return std::make_pair(0U, &X86::GR8RegClass);
20695 if (VT == MVT::i16)
20696 return std::make_pair(0U, &X86::GR16RegClass);
20697 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
20698 return std::make_pair(0U, &X86::GR32RegClass);
20699 return std::make_pair(0U, &X86::GR64RegClass);
20700 case 'R': // LEGACY_REGS
20701 if (VT == MVT::i8 || VT == MVT::i1)
20702 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
20703 if (VT == MVT::i16)
20704 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
20705 if (VT == MVT::i32 || !Subtarget->is64Bit())
20706 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
20707 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
20708 case 'f': // FP Stack registers.
20709 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
20710 // value to the correct fpstack register class.
20711 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
20712 return std::make_pair(0U, &X86::RFP32RegClass);
20713 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
20714 return std::make_pair(0U, &X86::RFP64RegClass);
20715 return std::make_pair(0U, &X86::RFP80RegClass);
20716 case 'y': // MMX_REGS if MMX allowed.
20717 if (!Subtarget->hasMMX()) break;
20718 return std::make_pair(0U, &X86::VR64RegClass);
20719 case 'Y': // SSE_REGS if SSE2 allowed
20720 if (!Subtarget->hasSSE2()) break;
20722 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
20723 if (!Subtarget->hasSSE1()) break;
20725 switch (VT.SimpleTy) {
20727 // Scalar SSE types.
20730 return std::make_pair(0U, &X86::FR32RegClass);
20733 return std::make_pair(0U, &X86::FR64RegClass);
20741 return std::make_pair(0U, &X86::VR128RegClass);
20749 return std::make_pair(0U, &X86::VR256RegClass);
20754 return std::make_pair(0U, &X86::VR512RegClass);
20760 // Use the default implementation in TargetLowering to convert the register
20761 // constraint into a member of a register class.
20762 std::pair<unsigned, const TargetRegisterClass*> Res;
20763 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
20765 // Not found as a standard register?
20767 // Map st(0) -> st(7) -> ST0
20768 if (Constraint.size() == 7 && Constraint[0] == '{' &&
20769 tolower(Constraint[1]) == 's' &&
20770 tolower(Constraint[2]) == 't' &&
20771 Constraint[3] == '(' &&
20772 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
20773 Constraint[5] == ')' &&
20774 Constraint[6] == '}') {
20776 Res.first = X86::ST0+Constraint[4]-'0';
20777 Res.second = &X86::RFP80RegClass;
20781 // GCC allows "st(0)" to be called just plain "st".
20782 if (StringRef("{st}").equals_lower(Constraint)) {
20783 Res.first = X86::ST0;
20784 Res.second = &X86::RFP80RegClass;
20789 if (StringRef("{flags}").equals_lower(Constraint)) {
20790 Res.first = X86::EFLAGS;
20791 Res.second = &X86::CCRRegClass;
20795 // 'A' means EAX + EDX.
20796 if (Constraint == "A") {
20797 Res.first = X86::EAX;
20798 Res.second = &X86::GR32_ADRegClass;
20804 // Otherwise, check to see if this is a register class of the wrong value
20805 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
20806 // turn into {ax},{dx}.
20807 if (Res.second->hasType(VT))
20808 return Res; // Correct type already, nothing to do.
20810 // All of the single-register GCC register classes map their values onto
20811 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
20812 // really want an 8-bit or 32-bit register, map to the appropriate register
20813 // class and return the appropriate register.
20814 if (Res.second == &X86::GR16RegClass) {
20815 if (VT == MVT::i8 || VT == MVT::i1) {
20816 unsigned DestReg = 0;
20817 switch (Res.first) {
20819 case X86::AX: DestReg = X86::AL; break;
20820 case X86::DX: DestReg = X86::DL; break;
20821 case X86::CX: DestReg = X86::CL; break;
20822 case X86::BX: DestReg = X86::BL; break;
20825 Res.first = DestReg;
20826 Res.second = &X86::GR8RegClass;
20828 } else if (VT == MVT::i32 || VT == MVT::f32) {
20829 unsigned DestReg = 0;
20830 switch (Res.first) {
20832 case X86::AX: DestReg = X86::EAX; break;
20833 case X86::DX: DestReg = X86::EDX; break;
20834 case X86::CX: DestReg = X86::ECX; break;
20835 case X86::BX: DestReg = X86::EBX; break;
20836 case X86::SI: DestReg = X86::ESI; break;
20837 case X86::DI: DestReg = X86::EDI; break;
20838 case X86::BP: DestReg = X86::EBP; break;
20839 case X86::SP: DestReg = X86::ESP; break;
20842 Res.first = DestReg;
20843 Res.second = &X86::GR32RegClass;
20845 } else if (VT == MVT::i64 || VT == MVT::f64) {
20846 unsigned DestReg = 0;
20847 switch (Res.first) {
20849 case X86::AX: DestReg = X86::RAX; break;
20850 case X86::DX: DestReg = X86::RDX; break;
20851 case X86::CX: DestReg = X86::RCX; break;
20852 case X86::BX: DestReg = X86::RBX; break;
20853 case X86::SI: DestReg = X86::RSI; break;
20854 case X86::DI: DestReg = X86::RDI; break;
20855 case X86::BP: DestReg = X86::RBP; break;
20856 case X86::SP: DestReg = X86::RSP; break;
20859 Res.first = DestReg;
20860 Res.second = &X86::GR64RegClass;
20863 } else if (Res.second == &X86::FR32RegClass ||
20864 Res.second == &X86::FR64RegClass ||
20865 Res.second == &X86::VR128RegClass ||
20866 Res.second == &X86::VR256RegClass ||
20867 Res.second == &X86::FR32XRegClass ||
20868 Res.second == &X86::FR64XRegClass ||
20869 Res.second == &X86::VR128XRegClass ||
20870 Res.second == &X86::VR256XRegClass ||
20871 Res.second == &X86::VR512RegClass) {
20872 // Handle references to XMM physical registers that got mapped into the
20873 // wrong class. This can happen with constraints like {xmm0} where the
20874 // target independent register mapper will just pick the first match it can
20875 // find, ignoring the required type.
20877 if (VT == MVT::f32 || VT == MVT::i32)
20878 Res.second = &X86::FR32RegClass;
20879 else if (VT == MVT::f64 || VT == MVT::i64)
20880 Res.second = &X86::FR64RegClass;
20881 else if (X86::VR128RegClass.hasType(VT))
20882 Res.second = &X86::VR128RegClass;
20883 else if (X86::VR256RegClass.hasType(VT))
20884 Res.second = &X86::VR256RegClass;
20885 else if (X86::VR512RegClass.hasType(VT))
20886 Res.second = &X86::VR512RegClass;
20892 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
20894 // Scaling factors are not free at all.
20895 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
20896 // will take 2 allocations instead of 1 for plain addressing mode,
20897 // i.e. inst (reg1).
20898 if (isLegalAddressingMode(AM, Ty))
20899 // Scale represents reg2 * scale, thus account for 1
20900 // as soon as we use a second register.
20901 return AM.Scale != 0;