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 ArrayRef<SDUse>(Vec->op_begin()+NormalizedIdxVal,
91 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
92 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
98 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
99 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
100 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
101 /// instructions or a simple subregister reference. Idx is an index in the
102 /// 128 bits we want. It need not be aligned to a 128-bit bounday. That makes
103 /// lowering EXTRACT_VECTOR_ELT operations easier.
104 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
105 SelectionDAG &DAG, SDLoc dl) {
106 assert((Vec.getValueType().is256BitVector() ||
107 Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
108 return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
111 /// Generate a DAG to grab 256-bits from a 512-bit vector.
112 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
113 SelectionDAG &DAG, SDLoc dl) {
114 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
115 return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
118 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
119 unsigned IdxVal, SelectionDAG &DAG,
120 SDLoc dl, unsigned vectorWidth) {
121 assert((vectorWidth == 128 || vectorWidth == 256) &&
122 "Unsupported vector width");
123 // Inserting UNDEF is Result
124 if (Vec.getOpcode() == ISD::UNDEF)
126 EVT VT = Vec.getValueType();
127 EVT ElVT = VT.getVectorElementType();
128 EVT ResultVT = Result.getValueType();
130 // Insert the relevant vectorWidth bits.
131 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
133 // This is the index of the first element of the vectorWidth-bit chunk
135 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
138 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
139 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
142 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
143 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
144 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
145 /// simple superregister reference. Idx is an index in the 128 bits
146 /// we want. It need not be aligned to a 128-bit bounday. That makes
147 /// lowering INSERT_VECTOR_ELT operations easier.
148 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
149 unsigned IdxVal, SelectionDAG &DAG,
151 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
152 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
155 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
156 unsigned IdxVal, SelectionDAG &DAG,
158 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
159 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
162 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
163 /// instructions. This is used because creating CONCAT_VECTOR nodes of
164 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
165 /// large BUILD_VECTORS.
166 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
167 unsigned NumElems, SelectionDAG &DAG,
169 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
170 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
173 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
174 unsigned NumElems, SelectionDAG &DAG,
176 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
177 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
180 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
181 const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
182 bool is64Bit = Subtarget->is64Bit();
184 if (Subtarget->isTargetMacho()) {
186 return new X86_64MachoTargetObjectFile();
187 return new TargetLoweringObjectFileMachO();
190 if (Subtarget->isTargetLinux())
191 return new X86LinuxTargetObjectFile();
192 if (Subtarget->isTargetELF())
193 return new TargetLoweringObjectFileELF();
194 if (Subtarget->isTargetKnownWindowsMSVC())
195 return new X86WindowsTargetObjectFile();
196 if (Subtarget->isTargetCOFF())
197 return new TargetLoweringObjectFileCOFF();
198 llvm_unreachable("unknown subtarget type");
201 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
202 : TargetLowering(TM, createTLOF(TM)) {
203 Subtarget = &TM.getSubtarget<X86Subtarget>();
204 X86ScalarSSEf64 = Subtarget->hasSSE2();
205 X86ScalarSSEf32 = Subtarget->hasSSE1();
206 TD = getDataLayout();
208 resetOperationActions();
211 void X86TargetLowering::resetOperationActions() {
212 const TargetMachine &TM = getTargetMachine();
213 static bool FirstTimeThrough = true;
215 // If none of the target options have changed, then we don't need to reset the
216 // operation actions.
217 if (!FirstTimeThrough && TO == TM.Options) return;
219 if (!FirstTimeThrough) {
220 // Reinitialize the actions.
222 FirstTimeThrough = false;
227 // Set up the TargetLowering object.
228 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
230 // X86 is weird, it always uses i8 for shift amounts and setcc results.
231 setBooleanContents(ZeroOrOneBooleanContent);
232 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
233 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
235 // For 64-bit since we have so many registers use the ILP scheduler, for
236 // 32-bit code use the register pressure specific scheduling.
237 // For Atom, always use ILP scheduling.
238 if (Subtarget->isAtom())
239 setSchedulingPreference(Sched::ILP);
240 else if (Subtarget->is64Bit())
241 setSchedulingPreference(Sched::ILP);
243 setSchedulingPreference(Sched::RegPressure);
244 const X86RegisterInfo *RegInfo =
245 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
246 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
248 // Bypass expensive divides on Atom when compiling with O2
249 if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
250 addBypassSlowDiv(32, 8);
251 if (Subtarget->is64Bit())
252 addBypassSlowDiv(64, 16);
255 if (Subtarget->isTargetKnownWindowsMSVC()) {
256 // Setup Windows compiler runtime calls.
257 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
258 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
259 setLibcallName(RTLIB::SREM_I64, "_allrem");
260 setLibcallName(RTLIB::UREM_I64, "_aullrem");
261 setLibcallName(RTLIB::MUL_I64, "_allmul");
262 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
263 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
264 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
265 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
266 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
268 // The _ftol2 runtime function has an unusual calling conv, which
269 // is modeled by a special pseudo-instruction.
270 setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
271 setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
272 setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
273 setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
276 if (Subtarget->isTargetDarwin()) {
277 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
278 setUseUnderscoreSetJmp(false);
279 setUseUnderscoreLongJmp(false);
280 } else if (Subtarget->isTargetWindowsGNU()) {
281 // MS runtime is weird: it exports _setjmp, but longjmp!
282 setUseUnderscoreSetJmp(true);
283 setUseUnderscoreLongJmp(false);
285 setUseUnderscoreSetJmp(true);
286 setUseUnderscoreLongJmp(true);
289 // Set up the register classes.
290 addRegisterClass(MVT::i8, &X86::GR8RegClass);
291 addRegisterClass(MVT::i16, &X86::GR16RegClass);
292 addRegisterClass(MVT::i32, &X86::GR32RegClass);
293 if (Subtarget->is64Bit())
294 addRegisterClass(MVT::i64, &X86::GR64RegClass);
296 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
298 // We don't accept any truncstore of integer registers.
299 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
300 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
301 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
302 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
303 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
304 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
306 // SETOEQ and SETUNE require checking two conditions.
307 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
308 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
309 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
310 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
311 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
312 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
314 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
316 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
317 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
318 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
320 if (Subtarget->is64Bit()) {
321 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
322 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
323 } else if (!TM.Options.UseSoftFloat) {
324 // We have an algorithm for SSE2->double, and we turn this into a
325 // 64-bit FILD followed by conditional FADD for other targets.
326 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
327 // We have an algorithm for SSE2, and we turn this into a 64-bit
328 // FILD for other targets.
329 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
332 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
334 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
335 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
337 if (!TM.Options.UseSoftFloat) {
338 // SSE has no i16 to fp conversion, only i32
339 if (X86ScalarSSEf32) {
340 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
341 // f32 and f64 cases are Legal, f80 case is not
342 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
344 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
345 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
348 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
349 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
352 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
353 // are Legal, f80 is custom lowered.
354 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
355 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
357 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
359 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
360 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
362 if (X86ScalarSSEf32) {
363 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
364 // f32 and f64 cases are Legal, f80 case is not
365 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
367 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
368 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
371 // Handle FP_TO_UINT by promoting the destination to a larger signed
373 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
374 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
375 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
377 if (Subtarget->is64Bit()) {
378 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
379 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
380 } else if (!TM.Options.UseSoftFloat) {
381 // Since AVX is a superset of SSE3, only check for SSE here.
382 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
383 // Expand FP_TO_UINT into a select.
384 // FIXME: We would like to use a Custom expander here eventually to do
385 // the optimal thing for SSE vs. the default expansion in the legalizer.
386 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
388 // With SSE3 we can use fisttpll to convert to a signed i64; without
389 // SSE, we're stuck with a fistpll.
390 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
393 if (isTargetFTOL()) {
394 // Use the _ftol2 runtime function, which has a pseudo-instruction
395 // to handle its weird calling convention.
396 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
399 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
400 if (!X86ScalarSSEf64) {
401 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
402 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
403 if (Subtarget->is64Bit()) {
404 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
405 // Without SSE, i64->f64 goes through memory.
406 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
410 // Scalar integer divide and remainder are lowered to use operations that
411 // produce two results, to match the available instructions. This exposes
412 // the two-result form to trivial CSE, which is able to combine x/y and x%y
413 // into a single instruction.
415 // Scalar integer multiply-high is also lowered to use two-result
416 // operations, to match the available instructions. However, plain multiply
417 // (low) operations are left as Legal, as there are single-result
418 // instructions for this in x86. Using the two-result multiply instructions
419 // when both high and low results are needed must be arranged by dagcombine.
420 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
422 setOperationAction(ISD::MULHS, VT, Expand);
423 setOperationAction(ISD::MULHU, VT, Expand);
424 setOperationAction(ISD::SDIV, VT, Expand);
425 setOperationAction(ISD::UDIV, VT, Expand);
426 setOperationAction(ISD::SREM, VT, Expand);
427 setOperationAction(ISD::UREM, VT, Expand);
429 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
430 setOperationAction(ISD::ADDC, VT, Custom);
431 setOperationAction(ISD::ADDE, VT, Custom);
432 setOperationAction(ISD::SUBC, VT, Custom);
433 setOperationAction(ISD::SUBE, VT, Custom);
436 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
437 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
438 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
439 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
440 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
441 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
442 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
443 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
444 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
445 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
446 if (Subtarget->is64Bit())
447 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
448 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
449 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
450 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
451 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
452 setOperationAction(ISD::FREM , MVT::f32 , Expand);
453 setOperationAction(ISD::FREM , MVT::f64 , Expand);
454 setOperationAction(ISD::FREM , MVT::f80 , Expand);
455 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
457 // Promote the i8 variants and force them on up to i32 which has a shorter
459 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
460 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
461 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
462 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
463 if (Subtarget->hasBMI()) {
464 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
465 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
466 if (Subtarget->is64Bit())
467 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
469 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
470 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
471 if (Subtarget->is64Bit())
472 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
475 if (Subtarget->hasLZCNT()) {
476 // When promoting the i8 variants, force them to i32 for a shorter
478 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
479 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
480 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
481 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
482 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
483 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
484 if (Subtarget->is64Bit())
485 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
487 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
488 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
489 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
490 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
491 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
492 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
493 if (Subtarget->is64Bit()) {
494 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
495 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
499 if (Subtarget->hasPOPCNT()) {
500 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
502 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
503 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
504 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
505 if (Subtarget->is64Bit())
506 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
509 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
511 if (!Subtarget->hasMOVBE())
512 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
514 // These should be promoted to a larger select which is supported.
515 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
516 // X86 wants to expand cmov itself.
517 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
518 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
519 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
520 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
521 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
522 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
523 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
524 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
525 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
526 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
527 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
528 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
529 if (Subtarget->is64Bit()) {
530 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
531 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
533 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
534 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
535 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
536 // support continuation, user-level threading, and etc.. As a result, no
537 // other SjLj exception interfaces are implemented and please don't build
538 // your own exception handling based on them.
539 // LLVM/Clang supports zero-cost DWARF exception handling.
540 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
541 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
544 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
545 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
546 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
547 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
548 if (Subtarget->is64Bit())
549 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
550 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
551 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
552 if (Subtarget->is64Bit()) {
553 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
554 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
555 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
556 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
557 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
559 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
560 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
561 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
562 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
563 if (Subtarget->is64Bit()) {
564 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
565 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
566 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
569 if (Subtarget->hasSSE1())
570 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
572 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
574 // Expand certain atomics
575 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
577 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
578 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
579 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
582 if (!Subtarget->is64Bit()) {
583 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
584 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
585 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
586 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
587 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
588 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
589 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
590 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
591 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
592 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
593 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
594 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
597 if (Subtarget->hasCmpxchg16b()) {
598 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
601 // FIXME - use subtarget debug flags
602 if (!Subtarget->isTargetDarwin() &&
603 !Subtarget->isTargetELF() &&
604 !Subtarget->isTargetCygMing()) {
605 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
608 if (Subtarget->is64Bit()) {
609 setExceptionPointerRegister(X86::RAX);
610 setExceptionSelectorRegister(X86::RDX);
612 setExceptionPointerRegister(X86::EAX);
613 setExceptionSelectorRegister(X86::EDX);
615 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
616 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
618 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
619 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
621 setOperationAction(ISD::TRAP, MVT::Other, Legal);
622 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
624 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
625 setOperationAction(ISD::VASTART , MVT::Other, Custom);
626 setOperationAction(ISD::VAEND , MVT::Other, Expand);
627 if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
628 // TargetInfo::X86_64ABIBuiltinVaList
629 setOperationAction(ISD::VAARG , MVT::Other, Custom);
630 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
632 // TargetInfo::CharPtrBuiltinVaList
633 setOperationAction(ISD::VAARG , MVT::Other, Expand);
634 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
637 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
638 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
640 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
641 MVT::i64 : MVT::i32, Custom);
643 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
644 // f32 and f64 use SSE.
645 // Set up the FP register classes.
646 addRegisterClass(MVT::f32, &X86::FR32RegClass);
647 addRegisterClass(MVT::f64, &X86::FR64RegClass);
649 // Use ANDPD to simulate FABS.
650 setOperationAction(ISD::FABS , MVT::f64, Custom);
651 setOperationAction(ISD::FABS , MVT::f32, Custom);
653 // Use XORP to simulate FNEG.
654 setOperationAction(ISD::FNEG , MVT::f64, Custom);
655 setOperationAction(ISD::FNEG , MVT::f32, Custom);
657 // Use ANDPD and ORPD to simulate FCOPYSIGN.
658 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
659 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
661 // Lower this to FGETSIGNx86 plus an AND.
662 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
663 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
665 // We don't support sin/cos/fmod
666 setOperationAction(ISD::FSIN , MVT::f64, Expand);
667 setOperationAction(ISD::FCOS , MVT::f64, Expand);
668 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
669 setOperationAction(ISD::FSIN , MVT::f32, Expand);
670 setOperationAction(ISD::FCOS , MVT::f32, Expand);
671 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
673 // Expand FP immediates into loads from the stack, except for the special
675 addLegalFPImmediate(APFloat(+0.0)); // xorpd
676 addLegalFPImmediate(APFloat(+0.0f)); // xorps
677 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
678 // Use SSE for f32, x87 for f64.
679 // Set up the FP register classes.
680 addRegisterClass(MVT::f32, &X86::FR32RegClass);
681 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
683 // Use ANDPS to simulate FABS.
684 setOperationAction(ISD::FABS , MVT::f32, Custom);
686 // Use XORP to simulate FNEG.
687 setOperationAction(ISD::FNEG , MVT::f32, Custom);
689 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
691 // Use ANDPS and ORPS to simulate FCOPYSIGN.
692 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
693 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
695 // We don't support sin/cos/fmod
696 setOperationAction(ISD::FSIN , MVT::f32, Expand);
697 setOperationAction(ISD::FCOS , MVT::f32, Expand);
698 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
700 // Special cases we handle for FP constants.
701 addLegalFPImmediate(APFloat(+0.0f)); // xorps
702 addLegalFPImmediate(APFloat(+0.0)); // FLD0
703 addLegalFPImmediate(APFloat(+1.0)); // FLD1
704 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
705 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
707 if (!TM.Options.UnsafeFPMath) {
708 setOperationAction(ISD::FSIN , MVT::f64, Expand);
709 setOperationAction(ISD::FCOS , MVT::f64, Expand);
710 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
712 } else if (!TM.Options.UseSoftFloat) {
713 // f32 and f64 in x87.
714 // Set up the FP register classes.
715 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
716 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
718 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
719 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
720 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
721 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
723 if (!TM.Options.UnsafeFPMath) {
724 setOperationAction(ISD::FSIN , MVT::f64, Expand);
725 setOperationAction(ISD::FSIN , MVT::f32, Expand);
726 setOperationAction(ISD::FCOS , MVT::f64, Expand);
727 setOperationAction(ISD::FCOS , MVT::f32, Expand);
728 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
729 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
731 addLegalFPImmediate(APFloat(+0.0)); // FLD0
732 addLegalFPImmediate(APFloat(+1.0)); // FLD1
733 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
734 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
735 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
736 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
737 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
738 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
741 // We don't support FMA.
742 setOperationAction(ISD::FMA, MVT::f64, Expand);
743 setOperationAction(ISD::FMA, MVT::f32, Expand);
745 // Long double always uses X87.
746 if (!TM.Options.UseSoftFloat) {
747 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
748 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
749 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
751 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
752 addLegalFPImmediate(TmpFlt); // FLD0
754 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
757 APFloat TmpFlt2(+1.0);
758 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
760 addLegalFPImmediate(TmpFlt2); // FLD1
761 TmpFlt2.changeSign();
762 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
765 if (!TM.Options.UnsafeFPMath) {
766 setOperationAction(ISD::FSIN , MVT::f80, Expand);
767 setOperationAction(ISD::FCOS , MVT::f80, Expand);
768 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
771 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
772 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
773 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
774 setOperationAction(ISD::FRINT, MVT::f80, Expand);
775 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
776 setOperationAction(ISD::FMA, MVT::f80, Expand);
779 // Always use a library call for pow.
780 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
781 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
782 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
784 setOperationAction(ISD::FLOG, MVT::f80, Expand);
785 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
786 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
787 setOperationAction(ISD::FEXP, MVT::f80, Expand);
788 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
790 // First set operation action for all vector types to either promote
791 // (for widening) or expand (for scalarization). Then we will selectively
792 // turn on ones that can be effectively codegen'd.
793 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
794 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
795 MVT VT = (MVT::SimpleValueType)i;
796 setOperationAction(ISD::ADD , VT, Expand);
797 setOperationAction(ISD::SUB , VT, Expand);
798 setOperationAction(ISD::FADD, VT, Expand);
799 setOperationAction(ISD::FNEG, VT, Expand);
800 setOperationAction(ISD::FSUB, VT, Expand);
801 setOperationAction(ISD::MUL , VT, Expand);
802 setOperationAction(ISD::FMUL, VT, Expand);
803 setOperationAction(ISD::SDIV, VT, Expand);
804 setOperationAction(ISD::UDIV, VT, Expand);
805 setOperationAction(ISD::FDIV, VT, Expand);
806 setOperationAction(ISD::SREM, VT, Expand);
807 setOperationAction(ISD::UREM, VT, Expand);
808 setOperationAction(ISD::LOAD, VT, Expand);
809 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
810 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
811 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
812 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
813 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
814 setOperationAction(ISD::FABS, VT, Expand);
815 setOperationAction(ISD::FSIN, VT, Expand);
816 setOperationAction(ISD::FSINCOS, VT, Expand);
817 setOperationAction(ISD::FCOS, VT, Expand);
818 setOperationAction(ISD::FSINCOS, VT, Expand);
819 setOperationAction(ISD::FREM, VT, Expand);
820 setOperationAction(ISD::FMA, VT, Expand);
821 setOperationAction(ISD::FPOWI, VT, Expand);
822 setOperationAction(ISD::FSQRT, VT, Expand);
823 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
824 setOperationAction(ISD::FFLOOR, VT, Expand);
825 setOperationAction(ISD::FCEIL, VT, Expand);
826 setOperationAction(ISD::FTRUNC, VT, Expand);
827 setOperationAction(ISD::FRINT, VT, Expand);
828 setOperationAction(ISD::FNEARBYINT, VT, Expand);
829 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
830 setOperationAction(ISD::MULHS, VT, Expand);
831 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
832 setOperationAction(ISD::MULHU, VT, Expand);
833 setOperationAction(ISD::SDIVREM, VT, Expand);
834 setOperationAction(ISD::UDIVREM, VT, Expand);
835 setOperationAction(ISD::FPOW, VT, Expand);
836 setOperationAction(ISD::CTPOP, VT, Expand);
837 setOperationAction(ISD::CTTZ, VT, Expand);
838 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
839 setOperationAction(ISD::CTLZ, VT, Expand);
840 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
841 setOperationAction(ISD::SHL, VT, Expand);
842 setOperationAction(ISD::SRA, VT, Expand);
843 setOperationAction(ISD::SRL, VT, Expand);
844 setOperationAction(ISD::ROTL, VT, Expand);
845 setOperationAction(ISD::ROTR, VT, Expand);
846 setOperationAction(ISD::BSWAP, VT, Expand);
847 setOperationAction(ISD::SETCC, VT, Expand);
848 setOperationAction(ISD::FLOG, VT, Expand);
849 setOperationAction(ISD::FLOG2, VT, Expand);
850 setOperationAction(ISD::FLOG10, VT, Expand);
851 setOperationAction(ISD::FEXP, VT, Expand);
852 setOperationAction(ISD::FEXP2, VT, Expand);
853 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
854 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
855 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
856 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
857 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
858 setOperationAction(ISD::TRUNCATE, VT, Expand);
859 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
860 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
861 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
862 setOperationAction(ISD::VSELECT, VT, Expand);
863 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
864 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
865 setTruncStoreAction(VT,
866 (MVT::SimpleValueType)InnerVT, Expand);
867 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
868 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
869 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
872 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
873 // with -msoft-float, disable use of MMX as well.
874 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
875 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
876 // No operations on x86mmx supported, everything uses intrinsics.
879 // MMX-sized vectors (other than x86mmx) are expected to be expanded
880 // into smaller operations.
881 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
882 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
883 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
884 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
885 setOperationAction(ISD::AND, MVT::v8i8, Expand);
886 setOperationAction(ISD::AND, MVT::v4i16, Expand);
887 setOperationAction(ISD::AND, MVT::v2i32, Expand);
888 setOperationAction(ISD::AND, MVT::v1i64, Expand);
889 setOperationAction(ISD::OR, MVT::v8i8, Expand);
890 setOperationAction(ISD::OR, MVT::v4i16, Expand);
891 setOperationAction(ISD::OR, MVT::v2i32, Expand);
892 setOperationAction(ISD::OR, MVT::v1i64, Expand);
893 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
894 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
895 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
896 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
897 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
898 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
899 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
900 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
901 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
902 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
903 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
904 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
905 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
906 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
907 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
908 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
909 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
911 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
912 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
914 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
915 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
916 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
917 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
918 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
919 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
920 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
921 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
922 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
923 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
924 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
925 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
928 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
929 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
931 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
932 // registers cannot be used even for integer operations.
933 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
934 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
935 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
936 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
938 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
939 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
940 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
941 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
942 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
943 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
944 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
945 setOperationAction(ISD::SMUL_LOHI, MVT::v4i32, Custom);
946 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
947 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
948 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
949 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
950 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
951 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
952 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
953 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
954 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
955 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
956 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
957 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
958 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
959 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
961 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
962 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
963 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
964 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
966 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
967 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
968 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
969 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
970 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
972 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
973 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
974 MVT VT = (MVT::SimpleValueType)i;
975 // Do not attempt to custom lower non-power-of-2 vectors
976 if (!isPowerOf2_32(VT.getVectorNumElements()))
978 // Do not attempt to custom lower non-128-bit vectors
979 if (!VT.is128BitVector())
981 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
982 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
983 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
986 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
987 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
988 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
989 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
990 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
991 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
993 if (Subtarget->is64Bit()) {
994 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
995 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
998 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
999 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1000 MVT VT = (MVT::SimpleValueType)i;
1002 // Do not attempt to promote non-128-bit vectors
1003 if (!VT.is128BitVector())
1006 setOperationAction(ISD::AND, VT, Promote);
1007 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
1008 setOperationAction(ISD::OR, VT, Promote);
1009 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
1010 setOperationAction(ISD::XOR, VT, Promote);
1011 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
1012 setOperationAction(ISD::LOAD, VT, Promote);
1013 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
1014 setOperationAction(ISD::SELECT, VT, Promote);
1015 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1018 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1020 // Custom lower v2i64 and v2f64 selects.
1021 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
1022 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
1023 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
1024 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
1026 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1027 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1029 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1030 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1031 // As there is no 64-bit GPR available, we need build a special custom
1032 // sequence to convert from v2i32 to v2f32.
1033 if (!Subtarget->is64Bit())
1034 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
1036 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1037 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
1039 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
1042 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1043 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1044 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1045 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1046 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1047 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1048 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1049 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1050 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1051 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1052 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1054 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1055 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
1056 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1057 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
1058 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
1059 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
1060 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
1061 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
1062 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
1063 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
1065 // FIXME: Do we need to handle scalar-to-vector here?
1066 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1068 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
1069 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal);
1070 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
1071 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
1072 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
1074 // i8 and i16 vectors are custom , because the source register and source
1075 // source memory operand types are not the same width. f32 vectors are
1076 // custom since the immediate controlling the insert encodes additional
1078 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1079 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1080 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1081 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1083 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1084 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1085 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1086 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1088 // FIXME: these should be Legal but thats only for the case where
1089 // the index is constant. For now custom expand to deal with that.
1090 if (Subtarget->is64Bit()) {
1091 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1092 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1096 if (Subtarget->hasSSE2()) {
1097 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1098 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1100 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1101 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1103 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1104 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1106 // In the customized shift lowering, the legal cases in AVX2 will be
1108 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1109 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1111 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1112 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1114 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1117 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1118 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1119 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1120 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1121 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1122 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1123 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1125 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1126 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1127 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1129 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1130 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1131 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1132 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1133 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1134 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1135 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1136 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1137 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1138 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1139 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1140 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1142 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1143 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1144 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1145 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1146 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1147 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1148 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1149 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1150 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1151 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1152 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1153 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1155 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1156 // even though v8i16 is a legal type.
1157 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1158 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1159 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1161 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1162 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1163 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1165 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1166 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1168 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1170 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1171 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1173 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1174 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1176 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1177 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1179 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1180 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1181 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1182 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1184 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1185 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1186 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1188 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1189 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal);
1190 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal);
1191 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal);
1193 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1194 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1195 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1196 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1197 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1198 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1199 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1200 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1201 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1202 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1203 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1204 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1206 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1207 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1208 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1209 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1210 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1211 setOperationAction(ISD::FMA, MVT::f32, Legal);
1212 setOperationAction(ISD::FMA, MVT::f64, Legal);
1215 if (Subtarget->hasInt256()) {
1216 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1217 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1218 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1219 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1221 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1222 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1223 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1224 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1226 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1227 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1228 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1229 // Don't lower v32i8 because there is no 128-bit byte mul
1231 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1232 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1233 setOperationAction(ISD::MULHU, MVT::v16i16, Legal);
1234 setOperationAction(ISD::MULHS, MVT::v16i16, Legal);
1236 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
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);
1346 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1347 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1348 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1349 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1350 if (Subtarget->is64Bit()) {
1351 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1352 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1353 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1354 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1356 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1357 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1358 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1359 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1360 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1361 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1362 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1363 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1364 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1365 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1367 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1368 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1369 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1370 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1371 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1372 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1373 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1374 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1375 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1376 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1377 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1378 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1379 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1381 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1382 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1383 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1384 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1385 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1386 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1388 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1389 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1391 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1393 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1394 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1395 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1396 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1397 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1398 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1399 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1400 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1401 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1403 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1404 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1406 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1407 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1409 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1411 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1412 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1414 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1415 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1417 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1418 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1420 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1421 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1422 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1423 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1424 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1425 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1427 // Custom lower several nodes.
1428 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1429 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1430 MVT VT = (MVT::SimpleValueType)i;
1432 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1433 // Extract subvector is special because the value type
1434 // (result) is 256/128-bit but the source is 512-bit wide.
1435 if (VT.is128BitVector() || VT.is256BitVector())
1436 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1438 if (VT.getVectorElementType() == MVT::i1)
1439 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1441 // Do not attempt to custom lower other non-512-bit vectors
1442 if (!VT.is512BitVector())
1445 if ( EltSize >= 32) {
1446 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1447 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1448 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1449 setOperationAction(ISD::VSELECT, VT, Legal);
1450 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1451 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1452 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1455 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1456 MVT VT = (MVT::SimpleValueType)i;
1458 // Do not attempt to promote non-256-bit vectors
1459 if (!VT.is512BitVector())
1462 setOperationAction(ISD::SELECT, VT, Promote);
1463 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1467 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1468 // of this type with custom code.
1469 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1470 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1471 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1475 // We want to custom lower some of our intrinsics.
1476 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1477 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1478 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1479 if (!Subtarget->is64Bit())
1480 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1482 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1483 // handle type legalization for these operations here.
1485 // FIXME: We really should do custom legalization for addition and
1486 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1487 // than generic legalization for 64-bit multiplication-with-overflow, though.
1488 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1489 // Add/Sub/Mul with overflow operations are custom lowered.
1491 setOperationAction(ISD::SADDO, VT, Custom);
1492 setOperationAction(ISD::UADDO, VT, Custom);
1493 setOperationAction(ISD::SSUBO, VT, Custom);
1494 setOperationAction(ISD::USUBO, VT, Custom);
1495 setOperationAction(ISD::SMULO, VT, Custom);
1496 setOperationAction(ISD::UMULO, VT, Custom);
1499 // There are no 8-bit 3-address imul/mul instructions
1500 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1501 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1503 if (!Subtarget->is64Bit()) {
1504 // These libcalls are not available in 32-bit.
1505 setLibcallName(RTLIB::SHL_I128, nullptr);
1506 setLibcallName(RTLIB::SRL_I128, nullptr);
1507 setLibcallName(RTLIB::SRA_I128, nullptr);
1510 // Combine sin / cos into one node or libcall if possible.
1511 if (Subtarget->hasSinCos()) {
1512 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1513 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1514 if (Subtarget->isTargetDarwin()) {
1515 // For MacOSX, we don't want to the normal expansion of a libcall to
1516 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1518 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1519 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1523 // We have target-specific dag combine patterns for the following nodes:
1524 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1525 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1526 setTargetDAGCombine(ISD::VSELECT);
1527 setTargetDAGCombine(ISD::SELECT);
1528 setTargetDAGCombine(ISD::SHL);
1529 setTargetDAGCombine(ISD::SRA);
1530 setTargetDAGCombine(ISD::SRL);
1531 setTargetDAGCombine(ISD::OR);
1532 setTargetDAGCombine(ISD::AND);
1533 setTargetDAGCombine(ISD::ADD);
1534 setTargetDAGCombine(ISD::FADD);
1535 setTargetDAGCombine(ISD::FSUB);
1536 setTargetDAGCombine(ISD::FMA);
1537 setTargetDAGCombine(ISD::SUB);
1538 setTargetDAGCombine(ISD::LOAD);
1539 setTargetDAGCombine(ISD::STORE);
1540 setTargetDAGCombine(ISD::ZERO_EXTEND);
1541 setTargetDAGCombine(ISD::ANY_EXTEND);
1542 setTargetDAGCombine(ISD::SIGN_EXTEND);
1543 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1544 setTargetDAGCombine(ISD::TRUNCATE);
1545 setTargetDAGCombine(ISD::SINT_TO_FP);
1546 setTargetDAGCombine(ISD::SETCC);
1547 if (Subtarget->is64Bit())
1548 setTargetDAGCombine(ISD::MUL);
1549 setTargetDAGCombine(ISD::XOR);
1551 computeRegisterProperties();
1553 // On Darwin, -Os means optimize for size without hurting performance,
1554 // do not reduce the limit.
1555 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1556 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1557 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1558 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1559 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1560 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1561 setPrefLoopAlignment(4); // 2^4 bytes.
1563 // Predictable cmov don't hurt on atom because it's in-order.
1564 PredictableSelectIsExpensive = !Subtarget->isAtom();
1566 setPrefFunctionAlignment(4); // 2^4 bytes.
1569 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1571 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1573 if (Subtarget->hasAVX512())
1574 switch(VT.getVectorNumElements()) {
1575 case 8: return MVT::v8i1;
1576 case 16: return MVT::v16i1;
1579 return VT.changeVectorElementTypeToInteger();
1582 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1583 /// the desired ByVal argument alignment.
1584 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1587 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1588 if (VTy->getBitWidth() == 128)
1590 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1591 unsigned EltAlign = 0;
1592 getMaxByValAlign(ATy->getElementType(), EltAlign);
1593 if (EltAlign > MaxAlign)
1594 MaxAlign = EltAlign;
1595 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1596 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1597 unsigned EltAlign = 0;
1598 getMaxByValAlign(STy->getElementType(i), EltAlign);
1599 if (EltAlign > MaxAlign)
1600 MaxAlign = EltAlign;
1607 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1608 /// function arguments in the caller parameter area. For X86, aggregates
1609 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1610 /// are at 4-byte boundaries.
1611 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1612 if (Subtarget->is64Bit()) {
1613 // Max of 8 and alignment of type.
1614 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1621 if (Subtarget->hasSSE1())
1622 getMaxByValAlign(Ty, Align);
1626 /// getOptimalMemOpType - Returns the target specific optimal type for load
1627 /// and store operations as a result of memset, memcpy, and memmove
1628 /// lowering. If DstAlign is zero that means it's safe to destination
1629 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1630 /// means there isn't a need to check it against alignment requirement,
1631 /// probably because the source does not need to be loaded. If 'IsMemset' is
1632 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1633 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1634 /// source is constant so it does not need to be loaded.
1635 /// It returns EVT::Other if the type should be determined using generic
1636 /// target-independent logic.
1638 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1639 unsigned DstAlign, unsigned SrcAlign,
1640 bool IsMemset, bool ZeroMemset,
1642 MachineFunction &MF) const {
1643 const Function *F = MF.getFunction();
1644 if ((!IsMemset || ZeroMemset) &&
1645 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1646 Attribute::NoImplicitFloat)) {
1648 (Subtarget->isUnalignedMemAccessFast() ||
1649 ((DstAlign == 0 || DstAlign >= 16) &&
1650 (SrcAlign == 0 || SrcAlign >= 16)))) {
1652 if (Subtarget->hasInt256())
1654 if (Subtarget->hasFp256())
1657 if (Subtarget->hasSSE2())
1659 if (Subtarget->hasSSE1())
1661 } else if (!MemcpyStrSrc && Size >= 8 &&
1662 !Subtarget->is64Bit() &&
1663 Subtarget->hasSSE2()) {
1664 // Do not use f64 to lower memcpy if source is string constant. It's
1665 // better to use i32 to avoid the loads.
1669 if (Subtarget->is64Bit() && Size >= 8)
1674 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1676 return X86ScalarSSEf32;
1677 else if (VT == MVT::f64)
1678 return X86ScalarSSEf64;
1683 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1687 *Fast = Subtarget->isUnalignedMemAccessFast();
1691 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1692 /// current function. The returned value is a member of the
1693 /// MachineJumpTableInfo::JTEntryKind enum.
1694 unsigned X86TargetLowering::getJumpTableEncoding() const {
1695 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1697 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1698 Subtarget->isPICStyleGOT())
1699 return MachineJumpTableInfo::EK_Custom32;
1701 // Otherwise, use the normal jump table encoding heuristics.
1702 return TargetLowering::getJumpTableEncoding();
1706 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1707 const MachineBasicBlock *MBB,
1708 unsigned uid,MCContext &Ctx) const{
1709 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1710 Subtarget->isPICStyleGOT());
1711 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1713 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1714 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1717 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1719 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1720 SelectionDAG &DAG) const {
1721 if (!Subtarget->is64Bit())
1722 // This doesn't have SDLoc associated with it, but is not really the
1723 // same as a Register.
1724 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1728 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1729 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1731 const MCExpr *X86TargetLowering::
1732 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1733 MCContext &Ctx) const {
1734 // X86-64 uses RIP relative addressing based on the jump table label.
1735 if (Subtarget->isPICStyleRIPRel())
1736 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1738 // Otherwise, the reference is relative to the PIC base.
1739 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1742 // FIXME: Why this routine is here? Move to RegInfo!
1743 std::pair<const TargetRegisterClass*, uint8_t>
1744 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1745 const TargetRegisterClass *RRC = nullptr;
1747 switch (VT.SimpleTy) {
1749 return TargetLowering::findRepresentativeClass(VT);
1750 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1751 RRC = Subtarget->is64Bit() ?
1752 (const TargetRegisterClass*)&X86::GR64RegClass :
1753 (const TargetRegisterClass*)&X86::GR32RegClass;
1756 RRC = &X86::VR64RegClass;
1758 case MVT::f32: case MVT::f64:
1759 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1760 case MVT::v4f32: case MVT::v2f64:
1761 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1763 RRC = &X86::VR128RegClass;
1766 return std::make_pair(RRC, Cost);
1769 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1770 unsigned &Offset) const {
1771 if (!Subtarget->isTargetLinux())
1774 if (Subtarget->is64Bit()) {
1775 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1777 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1789 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1790 unsigned DestAS) const {
1791 assert(SrcAS != DestAS && "Expected different address spaces!");
1793 return SrcAS < 256 && DestAS < 256;
1796 //===----------------------------------------------------------------------===//
1797 // Return Value Calling Convention Implementation
1798 //===----------------------------------------------------------------------===//
1800 #include "X86GenCallingConv.inc"
1803 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1804 MachineFunction &MF, bool isVarArg,
1805 const SmallVectorImpl<ISD::OutputArg> &Outs,
1806 LLVMContext &Context) const {
1807 SmallVector<CCValAssign, 16> RVLocs;
1808 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1810 return CCInfo.CheckReturn(Outs, RetCC_X86);
1813 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1814 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1819 X86TargetLowering::LowerReturn(SDValue Chain,
1820 CallingConv::ID CallConv, bool isVarArg,
1821 const SmallVectorImpl<ISD::OutputArg> &Outs,
1822 const SmallVectorImpl<SDValue> &OutVals,
1823 SDLoc dl, SelectionDAG &DAG) const {
1824 MachineFunction &MF = DAG.getMachineFunction();
1825 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1827 SmallVector<CCValAssign, 16> RVLocs;
1828 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1829 RVLocs, *DAG.getContext());
1830 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1833 SmallVector<SDValue, 6> RetOps;
1834 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1835 // Operand #1 = Bytes To Pop
1836 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1839 // Copy the result values into the output registers.
1840 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1841 CCValAssign &VA = RVLocs[i];
1842 assert(VA.isRegLoc() && "Can only return in registers!");
1843 SDValue ValToCopy = OutVals[i];
1844 EVT ValVT = ValToCopy.getValueType();
1846 // Promote values to the appropriate types
1847 if (VA.getLocInfo() == CCValAssign::SExt)
1848 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1849 else if (VA.getLocInfo() == CCValAssign::ZExt)
1850 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1851 else if (VA.getLocInfo() == CCValAssign::AExt)
1852 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1853 else if (VA.getLocInfo() == CCValAssign::BCvt)
1854 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1856 assert(VA.getLocInfo() != CCValAssign::FPExt &&
1857 "Unexpected FP-extend for return value.");
1859 // If this is x86-64, and we disabled SSE, we can't return FP values,
1860 // or SSE or MMX vectors.
1861 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1862 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1863 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1864 report_fatal_error("SSE register return with SSE disabled");
1866 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1867 // llvm-gcc has never done it right and no one has noticed, so this
1868 // should be OK for now.
1869 if (ValVT == MVT::f64 &&
1870 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1871 report_fatal_error("SSE2 register return with SSE2 disabled");
1873 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1874 // the RET instruction and handled by the FP Stackifier.
1875 if (VA.getLocReg() == X86::ST0 ||
1876 VA.getLocReg() == X86::ST1) {
1877 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1878 // change the value to the FP stack register class.
1879 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1880 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1881 RetOps.push_back(ValToCopy);
1882 // Don't emit a copytoreg.
1886 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1887 // which is returned in RAX / RDX.
1888 if (Subtarget->is64Bit()) {
1889 if (ValVT == MVT::x86mmx) {
1890 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1891 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1892 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1894 // If we don't have SSE2 available, convert to v4f32 so the generated
1895 // register is legal.
1896 if (!Subtarget->hasSSE2())
1897 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1902 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1903 Flag = Chain.getValue(1);
1904 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1907 // The x86-64 ABIs require that for returning structs by value we copy
1908 // the sret argument into %rax/%eax (depending on ABI) for the return.
1909 // Win32 requires us to put the sret argument to %eax as well.
1910 // We saved the argument into a virtual register in the entry block,
1911 // so now we copy the value out and into %rax/%eax.
1912 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1913 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1914 MachineFunction &MF = DAG.getMachineFunction();
1915 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1916 unsigned Reg = FuncInfo->getSRetReturnReg();
1918 "SRetReturnReg should have been set in LowerFormalArguments().");
1919 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1922 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1923 X86::RAX : X86::EAX;
1924 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1925 Flag = Chain.getValue(1);
1927 // RAX/EAX now acts like a return value.
1928 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1931 RetOps[0] = Chain; // Update chain.
1933 // Add the flag if we have it.
1935 RetOps.push_back(Flag);
1937 return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
1940 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1941 if (N->getNumValues() != 1)
1943 if (!N->hasNUsesOfValue(1, 0))
1946 SDValue TCChain = Chain;
1947 SDNode *Copy = *N->use_begin();
1948 if (Copy->getOpcode() == ISD::CopyToReg) {
1949 // If the copy has a glue operand, we conservatively assume it isn't safe to
1950 // perform a tail call.
1951 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1953 TCChain = Copy->getOperand(0);
1954 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1957 bool HasRet = false;
1958 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1960 if (UI->getOpcode() != X86ISD::RET_FLAG)
1973 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1974 ISD::NodeType ExtendKind) const {
1976 // TODO: Is this also valid on 32-bit?
1977 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1978 ReturnMVT = MVT::i8;
1980 ReturnMVT = MVT::i32;
1982 MVT MinVT = getRegisterType(ReturnMVT);
1983 return VT.bitsLT(MinVT) ? MinVT : VT;
1986 /// LowerCallResult - Lower the result values of a call into the
1987 /// appropriate copies out of appropriate physical registers.
1990 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1991 CallingConv::ID CallConv, bool isVarArg,
1992 const SmallVectorImpl<ISD::InputArg> &Ins,
1993 SDLoc dl, SelectionDAG &DAG,
1994 SmallVectorImpl<SDValue> &InVals) const {
1996 // Assign locations to each value returned by this call.
1997 SmallVector<CCValAssign, 16> RVLocs;
1998 bool Is64Bit = Subtarget->is64Bit();
1999 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2000 getTargetMachine(), RVLocs, *DAG.getContext());
2001 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2003 // Copy all of the result registers out of their specified physreg.
2004 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2005 CCValAssign &VA = RVLocs[i];
2006 EVT CopyVT = VA.getValVT();
2008 // If this is x86-64, and we disabled SSE, we can't return FP values
2009 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2010 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2011 report_fatal_error("SSE register return with SSE disabled");
2016 // If this is a call to a function that returns an fp value on the floating
2017 // point stack, we must guarantee the value is popped from the stack, so
2018 // a CopyFromReg is not good enough - the copy instruction may be eliminated
2019 // if the return value is not used. We use the FpPOP_RETVAL instruction
2021 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2022 // If we prefer to use the value in xmm registers, copy it out as f80 and
2023 // use a truncate to move it from fp stack reg to xmm reg.
2024 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2025 SDValue Ops[] = { Chain, InFlag };
2026 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2027 MVT::Other, MVT::Glue, Ops), 1);
2028 Val = Chain.getValue(0);
2030 // Round the f80 to the right size, which also moves it to the appropriate
2032 if (CopyVT != VA.getValVT())
2033 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2034 // This truncation won't change the value.
2035 DAG.getIntPtrConstant(1));
2037 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2038 CopyVT, InFlag).getValue(1);
2039 Val = Chain.getValue(0);
2041 InFlag = Chain.getValue(2);
2042 InVals.push_back(Val);
2048 //===----------------------------------------------------------------------===//
2049 // C & StdCall & Fast Calling Convention implementation
2050 //===----------------------------------------------------------------------===//
2051 // StdCall calling convention seems to be standard for many Windows' API
2052 // routines and around. It differs from C calling convention just a little:
2053 // callee should clean up the stack, not caller. Symbols should be also
2054 // decorated in some fancy way :) It doesn't support any vector arguments.
2055 // For info on fast calling convention see Fast Calling Convention (tail call)
2056 // implementation LowerX86_32FastCCCallTo.
2058 /// CallIsStructReturn - Determines whether a call uses struct return
2060 enum StructReturnType {
2065 static StructReturnType
2066 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2068 return NotStructReturn;
2070 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2071 if (!Flags.isSRet())
2072 return NotStructReturn;
2073 if (Flags.isInReg())
2074 return RegStructReturn;
2075 return StackStructReturn;
2078 /// ArgsAreStructReturn - Determines whether a function uses struct
2079 /// return semantics.
2080 static StructReturnType
2081 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2083 return NotStructReturn;
2085 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2086 if (!Flags.isSRet())
2087 return NotStructReturn;
2088 if (Flags.isInReg())
2089 return RegStructReturn;
2090 return StackStructReturn;
2093 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2094 /// by "Src" to address "Dst" with size and alignment information specified by
2095 /// the specific parameter attribute. The copy will be passed as a byval
2096 /// function parameter.
2098 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2099 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2101 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2103 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2104 /*isVolatile*/false, /*AlwaysInline=*/true,
2105 MachinePointerInfo(), MachinePointerInfo());
2108 /// IsTailCallConvention - Return true if the calling convention is one that
2109 /// supports tail call optimization.
2110 static bool IsTailCallConvention(CallingConv::ID CC) {
2111 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2112 CC == CallingConv::HiPE);
2115 /// \brief Return true if the calling convention is a C calling convention.
2116 static bool IsCCallConvention(CallingConv::ID CC) {
2117 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2118 CC == CallingConv::X86_64_SysV);
2121 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2122 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2126 CallingConv::ID CalleeCC = CS.getCallingConv();
2127 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2133 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2134 /// a tailcall target by changing its ABI.
2135 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2136 bool GuaranteedTailCallOpt) {
2137 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2141 X86TargetLowering::LowerMemArgument(SDValue Chain,
2142 CallingConv::ID CallConv,
2143 const SmallVectorImpl<ISD::InputArg> &Ins,
2144 SDLoc dl, SelectionDAG &DAG,
2145 const CCValAssign &VA,
2146 MachineFrameInfo *MFI,
2148 // Create the nodes corresponding to a load from this parameter slot.
2149 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2150 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2151 getTargetMachine().Options.GuaranteedTailCallOpt);
2152 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2155 // If value is passed by pointer we have address passed instead of the value
2157 if (VA.getLocInfo() == CCValAssign::Indirect)
2158 ValVT = VA.getLocVT();
2160 ValVT = VA.getValVT();
2162 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2163 // changed with more analysis.
2164 // In case of tail call optimization mark all arguments mutable. Since they
2165 // could be overwritten by lowering of arguments in case of a tail call.
2166 if (Flags.isByVal()) {
2167 unsigned Bytes = Flags.getByValSize();
2168 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2169 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2170 return DAG.getFrameIndex(FI, getPointerTy());
2172 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2173 VA.getLocMemOffset(), isImmutable);
2174 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2175 return DAG.getLoad(ValVT, dl, Chain, FIN,
2176 MachinePointerInfo::getFixedStack(FI),
2177 false, false, false, 0);
2182 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2183 CallingConv::ID CallConv,
2185 const SmallVectorImpl<ISD::InputArg> &Ins,
2188 SmallVectorImpl<SDValue> &InVals)
2190 MachineFunction &MF = DAG.getMachineFunction();
2191 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2193 const Function* Fn = MF.getFunction();
2194 if (Fn->hasExternalLinkage() &&
2195 Subtarget->isTargetCygMing() &&
2196 Fn->getName() == "main")
2197 FuncInfo->setForceFramePointer(true);
2199 MachineFrameInfo *MFI = MF.getFrameInfo();
2200 bool Is64Bit = Subtarget->is64Bit();
2201 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2203 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2204 "Var args not supported with calling convention fastcc, ghc or hipe");
2206 // Assign locations to all of the incoming arguments.
2207 SmallVector<CCValAssign, 16> ArgLocs;
2208 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2209 ArgLocs, *DAG.getContext());
2211 // Allocate shadow area for Win64
2213 CCInfo.AllocateStack(32, 8);
2215 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2217 unsigned LastVal = ~0U;
2219 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2220 CCValAssign &VA = ArgLocs[i];
2221 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2223 assert(VA.getValNo() != LastVal &&
2224 "Don't support value assigned to multiple locs yet");
2226 LastVal = VA.getValNo();
2228 if (VA.isRegLoc()) {
2229 EVT RegVT = VA.getLocVT();
2230 const TargetRegisterClass *RC;
2231 if (RegVT == MVT::i32)
2232 RC = &X86::GR32RegClass;
2233 else if (Is64Bit && RegVT == MVT::i64)
2234 RC = &X86::GR64RegClass;
2235 else if (RegVT == MVT::f32)
2236 RC = &X86::FR32RegClass;
2237 else if (RegVT == MVT::f64)
2238 RC = &X86::FR64RegClass;
2239 else if (RegVT.is512BitVector())
2240 RC = &X86::VR512RegClass;
2241 else if (RegVT.is256BitVector())
2242 RC = &X86::VR256RegClass;
2243 else if (RegVT.is128BitVector())
2244 RC = &X86::VR128RegClass;
2245 else if (RegVT == MVT::x86mmx)
2246 RC = &X86::VR64RegClass;
2247 else if (RegVT == MVT::i1)
2248 RC = &X86::VK1RegClass;
2249 else if (RegVT == MVT::v8i1)
2250 RC = &X86::VK8RegClass;
2251 else if (RegVT == MVT::v16i1)
2252 RC = &X86::VK16RegClass;
2254 llvm_unreachable("Unknown argument type!");
2256 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2257 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2259 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2260 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2262 if (VA.getLocInfo() == CCValAssign::SExt)
2263 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2264 DAG.getValueType(VA.getValVT()));
2265 else if (VA.getLocInfo() == CCValAssign::ZExt)
2266 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2267 DAG.getValueType(VA.getValVT()));
2268 else if (VA.getLocInfo() == CCValAssign::BCvt)
2269 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2271 if (VA.isExtInLoc()) {
2272 // Handle MMX values passed in XMM regs.
2273 if (RegVT.isVector())
2274 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2276 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2279 assert(VA.isMemLoc());
2280 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2283 // If value is passed via pointer - do a load.
2284 if (VA.getLocInfo() == CCValAssign::Indirect)
2285 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2286 MachinePointerInfo(), false, false, false, 0);
2288 InVals.push_back(ArgValue);
2291 // The x86-64 ABIs require that for returning structs by value we copy
2292 // the sret argument into %rax/%eax (depending on ABI) for the return.
2293 // Win32 requires us to put the sret argument to %eax as well.
2294 // Save the argument into a virtual register so that we can access it
2295 // from the return points.
2296 if (MF.getFunction()->hasStructRetAttr() &&
2297 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2298 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2299 unsigned Reg = FuncInfo->getSRetReturnReg();
2301 MVT PtrTy = getPointerTy();
2302 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2303 FuncInfo->setSRetReturnReg(Reg);
2305 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2306 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2309 unsigned StackSize = CCInfo.getNextStackOffset();
2310 // Align stack specially for tail calls.
2311 if (FuncIsMadeTailCallSafe(CallConv,
2312 MF.getTarget().Options.GuaranteedTailCallOpt))
2313 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2315 // If the function takes variable number of arguments, make a frame index for
2316 // the start of the first vararg value... for expansion of llvm.va_start.
2318 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2319 CallConv != CallingConv::X86_ThisCall)) {
2320 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2323 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2325 // FIXME: We should really autogenerate these arrays
2326 static const MCPhysReg GPR64ArgRegsWin64[] = {
2327 X86::RCX, X86::RDX, X86::R8, X86::R9
2329 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2330 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2332 static const MCPhysReg XMMArgRegs64Bit[] = {
2333 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2334 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2336 const MCPhysReg *GPR64ArgRegs;
2337 unsigned NumXMMRegs = 0;
2340 // The XMM registers which might contain var arg parameters are shadowed
2341 // in their paired GPR. So we only need to save the GPR to their home
2343 TotalNumIntRegs = 4;
2344 GPR64ArgRegs = GPR64ArgRegsWin64;
2346 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2347 GPR64ArgRegs = GPR64ArgRegs64Bit;
2349 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2352 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2355 bool NoImplicitFloatOps = Fn->getAttributes().
2356 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2357 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2358 "SSE register cannot be used when SSE is disabled!");
2359 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2360 NoImplicitFloatOps) &&
2361 "SSE register cannot be used when SSE is disabled!");
2362 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2363 !Subtarget->hasSSE1())
2364 // Kernel mode asks for SSE to be disabled, so don't push them
2366 TotalNumXMMRegs = 0;
2369 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2370 // Get to the caller-allocated home save location. Add 8 to account
2371 // for the return address.
2372 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2373 FuncInfo->setRegSaveFrameIndex(
2374 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2375 // Fixup to set vararg frame on shadow area (4 x i64).
2377 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2379 // For X86-64, if there are vararg parameters that are passed via
2380 // registers, then we must store them to their spots on the stack so
2381 // they may be loaded by deferencing the result of va_next.
2382 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2383 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2384 FuncInfo->setRegSaveFrameIndex(
2385 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2389 // Store the integer parameter registers.
2390 SmallVector<SDValue, 8> MemOps;
2391 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2393 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2394 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2395 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2396 DAG.getIntPtrConstant(Offset));
2397 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2398 &X86::GR64RegClass);
2399 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2401 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2402 MachinePointerInfo::getFixedStack(
2403 FuncInfo->getRegSaveFrameIndex(), Offset),
2405 MemOps.push_back(Store);
2409 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2410 // Now store the XMM (fp + vector) parameter registers.
2411 SmallVector<SDValue, 11> SaveXMMOps;
2412 SaveXMMOps.push_back(Chain);
2414 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2415 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2416 SaveXMMOps.push_back(ALVal);
2418 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2419 FuncInfo->getRegSaveFrameIndex()));
2420 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2421 FuncInfo->getVarArgsFPOffset()));
2423 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2424 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2425 &X86::VR128RegClass);
2426 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2427 SaveXMMOps.push_back(Val);
2429 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2430 MVT::Other, SaveXMMOps));
2433 if (!MemOps.empty())
2434 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2438 // Some CCs need callee pop.
2439 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2440 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2441 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2443 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2444 // If this is an sret function, the return should pop the hidden pointer.
2445 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2446 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2447 argsAreStructReturn(Ins) == StackStructReturn)
2448 FuncInfo->setBytesToPopOnReturn(4);
2452 // RegSaveFrameIndex is X86-64 only.
2453 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2454 if (CallConv == CallingConv::X86_FastCall ||
2455 CallConv == CallingConv::X86_ThisCall)
2456 // fastcc functions can't have varargs.
2457 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2460 FuncInfo->setArgumentStackSize(StackSize);
2466 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2467 SDValue StackPtr, SDValue Arg,
2468 SDLoc dl, SelectionDAG &DAG,
2469 const CCValAssign &VA,
2470 ISD::ArgFlagsTy Flags) const {
2471 unsigned LocMemOffset = VA.getLocMemOffset();
2472 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2473 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2474 if (Flags.isByVal())
2475 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2477 return DAG.getStore(Chain, dl, Arg, PtrOff,
2478 MachinePointerInfo::getStack(LocMemOffset),
2482 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2483 /// optimization is performed and it is required.
2485 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2486 SDValue &OutRetAddr, SDValue Chain,
2487 bool IsTailCall, bool Is64Bit,
2488 int FPDiff, SDLoc dl) const {
2489 // Adjust the Return address stack slot.
2490 EVT VT = getPointerTy();
2491 OutRetAddr = getReturnAddressFrameIndex(DAG);
2493 // Load the "old" Return address.
2494 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2495 false, false, false, 0);
2496 return SDValue(OutRetAddr.getNode(), 1);
2499 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2500 /// optimization is performed and it is required (FPDiff!=0).
2502 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2503 SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2504 unsigned SlotSize, int FPDiff, SDLoc dl) {
2505 // Store the return address to the appropriate stack slot.
2506 if (!FPDiff) return Chain;
2507 // Calculate the new stack slot for the return address.
2508 int NewReturnAddrFI =
2509 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2511 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2512 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2513 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2519 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2520 SmallVectorImpl<SDValue> &InVals) const {
2521 SelectionDAG &DAG = CLI.DAG;
2523 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2524 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2525 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2526 SDValue Chain = CLI.Chain;
2527 SDValue Callee = CLI.Callee;
2528 CallingConv::ID CallConv = CLI.CallConv;
2529 bool &isTailCall = CLI.IsTailCall;
2530 bool isVarArg = CLI.IsVarArg;
2532 MachineFunction &MF = DAG.getMachineFunction();
2533 bool Is64Bit = Subtarget->is64Bit();
2534 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2535 StructReturnType SR = callIsStructReturn(Outs);
2536 bool IsSibcall = false;
2538 if (MF.getTarget().Options.DisableTailCalls)
2542 // Check if it's really possible to do a tail call.
2543 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2544 isVarArg, SR != NotStructReturn,
2545 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2546 Outs, OutVals, Ins, DAG);
2548 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
2549 report_fatal_error("failed to perform tail call elimination on a call "
2550 "site marked musttail");
2552 // Sibcalls are automatically detected tailcalls which do not require
2554 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2561 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2562 "Var args not supported with calling convention fastcc, ghc or hipe");
2564 // Analyze operands of the call, assigning locations to each operand.
2565 SmallVector<CCValAssign, 16> ArgLocs;
2566 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2567 ArgLocs, *DAG.getContext());
2569 // Allocate shadow area for Win64
2571 CCInfo.AllocateStack(32, 8);
2573 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2575 // Get a count of how many bytes are to be pushed on the stack.
2576 unsigned NumBytes = CCInfo.getNextStackOffset();
2578 // This is a sibcall. The memory operands are available in caller's
2579 // own caller's stack.
2581 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2582 IsTailCallConvention(CallConv))
2583 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2586 if (isTailCall && !IsSibcall) {
2587 // Lower arguments at fp - stackoffset + fpdiff.
2588 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2589 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2591 FPDiff = NumBytesCallerPushed - NumBytes;
2593 // Set the delta of movement of the returnaddr stackslot.
2594 // But only set if delta is greater than previous delta.
2595 if (FPDiff < X86Info->getTCReturnAddrDelta())
2596 X86Info->setTCReturnAddrDelta(FPDiff);
2599 unsigned NumBytesToPush = NumBytes;
2600 unsigned NumBytesToPop = NumBytes;
2602 // If we have an inalloca argument, all stack space has already been allocated
2603 // for us and be right at the top of the stack. We don't support multiple
2604 // arguments passed in memory when using inalloca.
2605 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2607 assert(ArgLocs.back().getLocMemOffset() == 0 &&
2608 "an inalloca argument must be the only memory argument");
2612 Chain = DAG.getCALLSEQ_START(
2613 Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2615 SDValue RetAddrFrIdx;
2616 // Load return address for tail calls.
2617 if (isTailCall && FPDiff)
2618 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2619 Is64Bit, FPDiff, dl);
2621 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2622 SmallVector<SDValue, 8> MemOpChains;
2625 // Walk the register/memloc assignments, inserting copies/loads. In the case
2626 // of tail call optimization arguments are handle later.
2627 const X86RegisterInfo *RegInfo =
2628 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2629 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2630 // Skip inalloca arguments, they have already been written.
2631 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2632 if (Flags.isInAlloca())
2635 CCValAssign &VA = ArgLocs[i];
2636 EVT RegVT = VA.getLocVT();
2637 SDValue Arg = OutVals[i];
2638 bool isByVal = Flags.isByVal();
2640 // Promote the value if needed.
2641 switch (VA.getLocInfo()) {
2642 default: llvm_unreachable("Unknown loc info!");
2643 case CCValAssign::Full: break;
2644 case CCValAssign::SExt:
2645 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2647 case CCValAssign::ZExt:
2648 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2650 case CCValAssign::AExt:
2651 if (RegVT.is128BitVector()) {
2652 // Special case: passing MMX values in XMM registers.
2653 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2654 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2655 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2657 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2659 case CCValAssign::BCvt:
2660 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2662 case CCValAssign::Indirect: {
2663 // Store the argument.
2664 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2665 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2666 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2667 MachinePointerInfo::getFixedStack(FI),
2674 if (VA.isRegLoc()) {
2675 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2676 if (isVarArg && IsWin64) {
2677 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2678 // shadow reg if callee is a varargs function.
2679 unsigned ShadowReg = 0;
2680 switch (VA.getLocReg()) {
2681 case X86::XMM0: ShadowReg = X86::RCX; break;
2682 case X86::XMM1: ShadowReg = X86::RDX; break;
2683 case X86::XMM2: ShadowReg = X86::R8; break;
2684 case X86::XMM3: ShadowReg = X86::R9; break;
2687 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2689 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2690 assert(VA.isMemLoc());
2691 if (!StackPtr.getNode())
2692 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2694 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2695 dl, DAG, VA, Flags));
2699 if (!MemOpChains.empty())
2700 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2702 if (Subtarget->isPICStyleGOT()) {
2703 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2706 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2707 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2709 // If we are tail calling and generating PIC/GOT style code load the
2710 // address of the callee into ECX. The value in ecx is used as target of
2711 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2712 // for tail calls on PIC/GOT architectures. Normally we would just put the
2713 // address of GOT into ebx and then call target@PLT. But for tail calls
2714 // ebx would be restored (since ebx is callee saved) before jumping to the
2717 // Note: The actual moving to ECX is done further down.
2718 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2719 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2720 !G->getGlobal()->hasProtectedVisibility())
2721 Callee = LowerGlobalAddress(Callee, DAG);
2722 else if (isa<ExternalSymbolSDNode>(Callee))
2723 Callee = LowerExternalSymbol(Callee, DAG);
2727 if (Is64Bit && isVarArg && !IsWin64) {
2728 // From AMD64 ABI document:
2729 // For calls that may call functions that use varargs or stdargs
2730 // (prototype-less calls or calls to functions containing ellipsis (...) in
2731 // the declaration) %al is used as hidden argument to specify the number
2732 // of SSE registers used. The contents of %al do not need to match exactly
2733 // the number of registers, but must be an ubound on the number of SSE
2734 // registers used and is in the range 0 - 8 inclusive.
2736 // Count the number of XMM registers allocated.
2737 static const MCPhysReg XMMArgRegs[] = {
2738 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2739 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2741 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2742 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2743 && "SSE registers cannot be used when SSE is disabled");
2745 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2746 DAG.getConstant(NumXMMRegs, MVT::i8)));
2749 // For tail calls lower the arguments to the 'real' stack slot.
2751 // Force all the incoming stack arguments to be loaded from the stack
2752 // before any new outgoing arguments are stored to the stack, because the
2753 // outgoing stack slots may alias the incoming argument stack slots, and
2754 // the alias isn't otherwise explicit. This is slightly more conservative
2755 // than necessary, because it means that each store effectively depends
2756 // on every argument instead of just those arguments it would clobber.
2757 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2759 SmallVector<SDValue, 8> MemOpChains2;
2762 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2763 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2764 CCValAssign &VA = ArgLocs[i];
2767 assert(VA.isMemLoc());
2768 SDValue Arg = OutVals[i];
2769 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2770 // Create frame index.
2771 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2772 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2773 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2774 FIN = DAG.getFrameIndex(FI, getPointerTy());
2776 if (Flags.isByVal()) {
2777 // Copy relative to framepointer.
2778 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2779 if (!StackPtr.getNode())
2780 StackPtr = DAG.getCopyFromReg(Chain, dl,
2781 RegInfo->getStackRegister(),
2783 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2785 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2789 // Store relative to framepointer.
2790 MemOpChains2.push_back(
2791 DAG.getStore(ArgChain, dl, Arg, FIN,
2792 MachinePointerInfo::getFixedStack(FI),
2798 if (!MemOpChains2.empty())
2799 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2801 // Store the return address to the appropriate stack slot.
2802 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2803 getPointerTy(), RegInfo->getSlotSize(),
2807 // Build a sequence of copy-to-reg nodes chained together with token chain
2808 // and flag operands which copy the outgoing args into registers.
2810 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2811 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2812 RegsToPass[i].second, InFlag);
2813 InFlag = Chain.getValue(1);
2816 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2817 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2818 // In the 64-bit large code model, we have to make all calls
2819 // through a register, since the call instruction's 32-bit
2820 // pc-relative offset may not be large enough to hold the whole
2822 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2823 // If the callee is a GlobalAddress node (quite common, every direct call
2824 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2827 // We should use extra load for direct calls to dllimported functions in
2829 const GlobalValue *GV = G->getGlobal();
2830 if (!GV->hasDLLImportStorageClass()) {
2831 unsigned char OpFlags = 0;
2832 bool ExtraLoad = false;
2833 unsigned WrapperKind = ISD::DELETED_NODE;
2835 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2836 // external symbols most go through the PLT in PIC mode. If the symbol
2837 // has hidden or protected visibility, or if it is static or local, then
2838 // we don't need to use the PLT - we can directly call it.
2839 if (Subtarget->isTargetELF() &&
2840 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2841 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2842 OpFlags = X86II::MO_PLT;
2843 } else if (Subtarget->isPICStyleStubAny() &&
2844 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2845 (!Subtarget->getTargetTriple().isMacOSX() ||
2846 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2847 // PC-relative references to external symbols should go through $stub,
2848 // unless we're building with the leopard linker or later, which
2849 // automatically synthesizes these stubs.
2850 OpFlags = X86II::MO_DARWIN_STUB;
2851 } else if (Subtarget->isPICStyleRIPRel() &&
2852 isa<Function>(GV) &&
2853 cast<Function>(GV)->getAttributes().
2854 hasAttribute(AttributeSet::FunctionIndex,
2855 Attribute::NonLazyBind)) {
2856 // If the function is marked as non-lazy, generate an indirect call
2857 // which loads from the GOT directly. This avoids runtime overhead
2858 // at the cost of eager binding (and one extra byte of encoding).
2859 OpFlags = X86II::MO_GOTPCREL;
2860 WrapperKind = X86ISD::WrapperRIP;
2864 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2865 G->getOffset(), OpFlags);
2867 // Add a wrapper if needed.
2868 if (WrapperKind != ISD::DELETED_NODE)
2869 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2870 // Add extra indirection if needed.
2872 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2873 MachinePointerInfo::getGOT(),
2874 false, false, false, 0);
2876 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2877 unsigned char OpFlags = 0;
2879 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2880 // external symbols should go through the PLT.
2881 if (Subtarget->isTargetELF() &&
2882 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2883 OpFlags = X86II::MO_PLT;
2884 } else if (Subtarget->isPICStyleStubAny() &&
2885 (!Subtarget->getTargetTriple().isMacOSX() ||
2886 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2887 // PC-relative references to external symbols should go through $stub,
2888 // unless we're building with the leopard linker or later, which
2889 // automatically synthesizes these stubs.
2890 OpFlags = X86II::MO_DARWIN_STUB;
2893 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2897 // Returns a chain & a flag for retval copy to use.
2898 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2899 SmallVector<SDValue, 8> Ops;
2901 if (!IsSibcall && isTailCall) {
2902 Chain = DAG.getCALLSEQ_END(Chain,
2903 DAG.getIntPtrConstant(NumBytesToPop, true),
2904 DAG.getIntPtrConstant(0, true), InFlag, dl);
2905 InFlag = Chain.getValue(1);
2908 Ops.push_back(Chain);
2909 Ops.push_back(Callee);
2912 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2914 // Add argument registers to the end of the list so that they are known live
2916 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2917 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2918 RegsToPass[i].second.getValueType()));
2920 // Add a register mask operand representing the call-preserved registers.
2921 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2922 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2923 assert(Mask && "Missing call preserved mask for calling convention");
2924 Ops.push_back(DAG.getRegisterMask(Mask));
2926 if (InFlag.getNode())
2927 Ops.push_back(InFlag);
2931 //// If this is the first return lowered for this function, add the regs
2932 //// to the liveout set for the function.
2933 // This isn't right, although it's probably harmless on x86; liveouts
2934 // should be computed from returns not tail calls. Consider a void
2935 // function making a tail call to a function returning int.
2936 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
2939 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
2940 InFlag = Chain.getValue(1);
2942 // Create the CALLSEQ_END node.
2943 unsigned NumBytesForCalleeToPop;
2944 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2945 getTargetMachine().Options.GuaranteedTailCallOpt))
2946 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
2947 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2948 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2949 SR == StackStructReturn)
2950 // If this is a call to a struct-return function, the callee
2951 // pops the hidden struct pointer, so we have to push it back.
2952 // This is common for Darwin/X86, Linux & Mingw32 targets.
2953 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2954 NumBytesForCalleeToPop = 4;
2956 NumBytesForCalleeToPop = 0; // Callee pops nothing.
2958 // Returns a flag for retval copy to use.
2960 Chain = DAG.getCALLSEQ_END(Chain,
2961 DAG.getIntPtrConstant(NumBytesToPop, true),
2962 DAG.getIntPtrConstant(NumBytesForCalleeToPop,
2965 InFlag = Chain.getValue(1);
2968 // Handle result values, copying them out of physregs into vregs that we
2970 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2971 Ins, dl, DAG, InVals);
2974 //===----------------------------------------------------------------------===//
2975 // Fast Calling Convention (tail call) implementation
2976 //===----------------------------------------------------------------------===//
2978 // Like std call, callee cleans arguments, convention except that ECX is
2979 // reserved for storing the tail called function address. Only 2 registers are
2980 // free for argument passing (inreg). Tail call optimization is performed
2982 // * tailcallopt is enabled
2983 // * caller/callee are fastcc
2984 // On X86_64 architecture with GOT-style position independent code only local
2985 // (within module) calls are supported at the moment.
2986 // To keep the stack aligned according to platform abi the function
2987 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2988 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2989 // If a tail called function callee has more arguments than the caller the
2990 // caller needs to make sure that there is room to move the RETADDR to. This is
2991 // achieved by reserving an area the size of the argument delta right after the
2992 // original REtADDR, but before the saved framepointer or the spilled registers
2993 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3005 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3006 /// for a 16 byte align requirement.
3008 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3009 SelectionDAG& DAG) const {
3010 MachineFunction &MF = DAG.getMachineFunction();
3011 const TargetMachine &TM = MF.getTarget();
3012 const X86RegisterInfo *RegInfo =
3013 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3014 const TargetFrameLowering &TFI = *TM.getFrameLowering();
3015 unsigned StackAlignment = TFI.getStackAlignment();
3016 uint64_t AlignMask = StackAlignment - 1;
3017 int64_t Offset = StackSize;
3018 unsigned SlotSize = RegInfo->getSlotSize();
3019 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3020 // Number smaller than 12 so just add the difference.
3021 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3023 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3024 Offset = ((~AlignMask) & Offset) + StackAlignment +
3025 (StackAlignment-SlotSize);
3030 /// MatchingStackOffset - Return true if the given stack call argument is
3031 /// already available in the same position (relatively) of the caller's
3032 /// incoming argument stack.
3034 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3035 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3036 const X86InstrInfo *TII) {
3037 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3039 if (Arg.getOpcode() == ISD::CopyFromReg) {
3040 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3041 if (!TargetRegisterInfo::isVirtualRegister(VR))
3043 MachineInstr *Def = MRI->getVRegDef(VR);
3046 if (!Flags.isByVal()) {
3047 if (!TII->isLoadFromStackSlot(Def, FI))
3050 unsigned Opcode = Def->getOpcode();
3051 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3052 Def->getOperand(1).isFI()) {
3053 FI = Def->getOperand(1).getIndex();
3054 Bytes = Flags.getByValSize();
3058 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3059 if (Flags.isByVal())
3060 // ByVal argument is passed in as a pointer but it's now being
3061 // dereferenced. e.g.
3062 // define @foo(%struct.X* %A) {
3063 // tail call @bar(%struct.X* byval %A)
3066 SDValue Ptr = Ld->getBasePtr();
3067 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3070 FI = FINode->getIndex();
3071 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3072 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3073 FI = FINode->getIndex();
3074 Bytes = Flags.getByValSize();
3078 assert(FI != INT_MAX);
3079 if (!MFI->isFixedObjectIndex(FI))
3081 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3084 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3085 /// for tail call optimization. Targets which want to do tail call
3086 /// optimization should implement this function.
3088 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3089 CallingConv::ID CalleeCC,
3091 bool isCalleeStructRet,
3092 bool isCallerStructRet,
3094 const SmallVectorImpl<ISD::OutputArg> &Outs,
3095 const SmallVectorImpl<SDValue> &OutVals,
3096 const SmallVectorImpl<ISD::InputArg> &Ins,
3097 SelectionDAG &DAG) const {
3098 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3101 // If -tailcallopt is specified, make fastcc functions tail-callable.
3102 const MachineFunction &MF = DAG.getMachineFunction();
3103 const Function *CallerF = MF.getFunction();
3105 // If the function return type is x86_fp80 and the callee return type is not,
3106 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3107 // perform a tailcall optimization here.
3108 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3111 CallingConv::ID CallerCC = CallerF->getCallingConv();
3112 bool CCMatch = CallerCC == CalleeCC;
3113 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3114 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3116 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3117 if (IsTailCallConvention(CalleeCC) && CCMatch)
3122 // Look for obvious safe cases to perform tail call optimization that do not
3123 // require ABI changes. This is what gcc calls sibcall.
3125 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3126 // emit a special epilogue.
3127 const X86RegisterInfo *RegInfo =
3128 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3129 if (RegInfo->needsStackRealignment(MF))
3132 // Also avoid sibcall optimization if either caller or callee uses struct
3133 // return semantics.
3134 if (isCalleeStructRet || isCallerStructRet)
3137 // An stdcall/thiscall caller is expected to clean up its arguments; the
3138 // callee isn't going to do that.
3139 // FIXME: this is more restrictive than needed. We could produce a tailcall
3140 // when the stack adjustment matches. For example, with a thiscall that takes
3141 // only one argument.
3142 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3143 CallerCC == CallingConv::X86_ThisCall))
3146 // Do not sibcall optimize vararg calls unless all arguments are passed via
3148 if (isVarArg && !Outs.empty()) {
3150 // Optimizing for varargs on Win64 is unlikely to be safe without
3151 // additional testing.
3152 if (IsCalleeWin64 || IsCallerWin64)
3155 SmallVector<CCValAssign, 16> ArgLocs;
3156 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3157 getTargetMachine(), ArgLocs, *DAG.getContext());
3159 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3160 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3161 if (!ArgLocs[i].isRegLoc())
3165 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3166 // stack. Therefore, if it's not used by the call it is not safe to optimize
3167 // this into a sibcall.
3168 bool Unused = false;
3169 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3176 SmallVector<CCValAssign, 16> RVLocs;
3177 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3178 getTargetMachine(), RVLocs, *DAG.getContext());
3179 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3180 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3181 CCValAssign &VA = RVLocs[i];
3182 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3187 // If the calling conventions do not match, then we'd better make sure the
3188 // results are returned in the same way as what the caller expects.
3190 SmallVector<CCValAssign, 16> RVLocs1;
3191 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3192 getTargetMachine(), RVLocs1, *DAG.getContext());
3193 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3195 SmallVector<CCValAssign, 16> RVLocs2;
3196 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3197 getTargetMachine(), RVLocs2, *DAG.getContext());
3198 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3200 if (RVLocs1.size() != RVLocs2.size())
3202 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3203 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3205 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3207 if (RVLocs1[i].isRegLoc()) {
3208 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3211 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3217 // If the callee takes no arguments then go on to check the results of the
3219 if (!Outs.empty()) {
3220 // Check if stack adjustment is needed. For now, do not do this if any
3221 // argument is passed on the stack.
3222 SmallVector<CCValAssign, 16> ArgLocs;
3223 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3224 getTargetMachine(), ArgLocs, *DAG.getContext());
3226 // Allocate shadow area for Win64
3228 CCInfo.AllocateStack(32, 8);
3230 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3231 if (CCInfo.getNextStackOffset()) {
3232 MachineFunction &MF = DAG.getMachineFunction();
3233 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3236 // Check if the arguments are already laid out in the right way as
3237 // the caller's fixed stack objects.
3238 MachineFrameInfo *MFI = MF.getFrameInfo();
3239 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3240 const X86InstrInfo *TII =
3241 ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3242 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3243 CCValAssign &VA = ArgLocs[i];
3244 SDValue Arg = OutVals[i];
3245 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3246 if (VA.getLocInfo() == CCValAssign::Indirect)
3248 if (!VA.isRegLoc()) {
3249 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3256 // If the tailcall address may be in a register, then make sure it's
3257 // possible to register allocate for it. In 32-bit, the call address can
3258 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3259 // callee-saved registers are restored. These happen to be the same
3260 // registers used to pass 'inreg' arguments so watch out for those.
3261 if (!Subtarget->is64Bit() &&
3262 ((!isa<GlobalAddressSDNode>(Callee) &&
3263 !isa<ExternalSymbolSDNode>(Callee)) ||
3264 getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3265 unsigned NumInRegs = 0;
3266 // In PIC we need an extra register to formulate the address computation
3268 unsigned MaxInRegs =
3269 (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3271 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3272 CCValAssign &VA = ArgLocs[i];
3275 unsigned Reg = VA.getLocReg();
3278 case X86::EAX: case X86::EDX: case X86::ECX:
3279 if (++NumInRegs == MaxInRegs)
3291 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3292 const TargetLibraryInfo *libInfo) const {
3293 return X86::createFastISel(funcInfo, libInfo);
3296 //===----------------------------------------------------------------------===//
3297 // Other Lowering Hooks
3298 //===----------------------------------------------------------------------===//
3300 static bool MayFoldLoad(SDValue Op) {
3301 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3304 static bool MayFoldIntoStore(SDValue Op) {
3305 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3308 static bool isTargetShuffle(unsigned Opcode) {
3310 default: return false;
3311 case X86ISD::PSHUFD:
3312 case X86ISD::PSHUFHW:
3313 case X86ISD::PSHUFLW:
3315 case X86ISD::PALIGNR:
3316 case X86ISD::MOVLHPS:
3317 case X86ISD::MOVLHPD:
3318 case X86ISD::MOVHLPS:
3319 case X86ISD::MOVLPS:
3320 case X86ISD::MOVLPD:
3321 case X86ISD::MOVSHDUP:
3322 case X86ISD::MOVSLDUP:
3323 case X86ISD::MOVDDUP:
3326 case X86ISD::UNPCKL:
3327 case X86ISD::UNPCKH:
3328 case X86ISD::VPERMILP:
3329 case X86ISD::VPERM2X128:
3330 case X86ISD::VPERMI:
3335 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3336 SDValue V1, SelectionDAG &DAG) {
3338 default: llvm_unreachable("Unknown x86 shuffle node");
3339 case X86ISD::MOVSHDUP:
3340 case X86ISD::MOVSLDUP:
3341 case X86ISD::MOVDDUP:
3342 return DAG.getNode(Opc, dl, VT, V1);
3346 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3347 SDValue V1, unsigned TargetMask,
3348 SelectionDAG &DAG) {
3350 default: llvm_unreachable("Unknown x86 shuffle node");
3351 case X86ISD::PSHUFD:
3352 case X86ISD::PSHUFHW:
3353 case X86ISD::PSHUFLW:
3354 case X86ISD::VPERMILP:
3355 case X86ISD::VPERMI:
3356 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3360 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3361 SDValue V1, SDValue V2, unsigned TargetMask,
3362 SelectionDAG &DAG) {
3364 default: llvm_unreachable("Unknown x86 shuffle node");
3365 case X86ISD::PALIGNR:
3367 case X86ISD::VPERM2X128:
3368 return DAG.getNode(Opc, dl, VT, V1, V2,
3369 DAG.getConstant(TargetMask, MVT::i8));
3373 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3374 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3376 default: llvm_unreachable("Unknown x86 shuffle node");
3377 case X86ISD::MOVLHPS:
3378 case X86ISD::MOVLHPD:
3379 case X86ISD::MOVHLPS:
3380 case X86ISD::MOVLPS:
3381 case X86ISD::MOVLPD:
3384 case X86ISD::UNPCKL:
3385 case X86ISD::UNPCKH:
3386 return DAG.getNode(Opc, dl, VT, V1, V2);
3390 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3391 MachineFunction &MF = DAG.getMachineFunction();
3392 const X86RegisterInfo *RegInfo =
3393 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3394 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3395 int ReturnAddrIndex = FuncInfo->getRAIndex();
3397 if (ReturnAddrIndex == 0) {
3398 // Set up a frame object for the return address.
3399 unsigned SlotSize = RegInfo->getSlotSize();
3400 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3403 FuncInfo->setRAIndex(ReturnAddrIndex);
3406 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3409 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3410 bool hasSymbolicDisplacement) {
3411 // Offset should fit into 32 bit immediate field.
3412 if (!isInt<32>(Offset))
3415 // If we don't have a symbolic displacement - we don't have any extra
3417 if (!hasSymbolicDisplacement)
3420 // FIXME: Some tweaks might be needed for medium code model.
3421 if (M != CodeModel::Small && M != CodeModel::Kernel)
3424 // For small code model we assume that latest object is 16MB before end of 31
3425 // bits boundary. We may also accept pretty large negative constants knowing
3426 // that all objects are in the positive half of address space.
3427 if (M == CodeModel::Small && Offset < 16*1024*1024)
3430 // For kernel code model we know that all object resist in the negative half
3431 // of 32bits address space. We may not accept negative offsets, since they may
3432 // be just off and we may accept pretty large positive ones.
3433 if (M == CodeModel::Kernel && Offset > 0)
3439 /// isCalleePop - Determines whether the callee is required to pop its
3440 /// own arguments. Callee pop is necessary to support tail calls.
3441 bool X86::isCalleePop(CallingConv::ID CallingConv,
3442 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3446 switch (CallingConv) {
3449 case CallingConv::X86_StdCall:
3451 case CallingConv::X86_FastCall:
3453 case CallingConv::X86_ThisCall:
3455 case CallingConv::Fast:
3457 case CallingConv::GHC:
3459 case CallingConv::HiPE:
3464 /// \brief Return true if the condition is an unsigned comparison operation.
3465 static bool isX86CCUnsigned(unsigned X86CC) {
3467 default: llvm_unreachable("Invalid integer condition!");
3468 case X86::COND_E: return true;
3469 case X86::COND_G: return false;
3470 case X86::COND_GE: return false;
3471 case X86::COND_L: return false;
3472 case X86::COND_LE: return false;
3473 case X86::COND_NE: return true;
3474 case X86::COND_B: return true;
3475 case X86::COND_A: return true;
3476 case X86::COND_BE: return true;
3477 case X86::COND_AE: return true;
3479 llvm_unreachable("covered switch fell through?!");
3482 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3483 /// specific condition code, returning the condition code and the LHS/RHS of the
3484 /// comparison to make.
3485 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3486 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3488 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3489 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3490 // X > -1 -> X == 0, jump !sign.
3491 RHS = DAG.getConstant(0, RHS.getValueType());
3492 return X86::COND_NS;
3494 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3495 // X < 0 -> X == 0, jump on sign.
3498 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3500 RHS = DAG.getConstant(0, RHS.getValueType());
3501 return X86::COND_LE;
3505 switch (SetCCOpcode) {
3506 default: llvm_unreachable("Invalid integer condition!");
3507 case ISD::SETEQ: return X86::COND_E;
3508 case ISD::SETGT: return X86::COND_G;
3509 case ISD::SETGE: return X86::COND_GE;
3510 case ISD::SETLT: return X86::COND_L;
3511 case ISD::SETLE: return X86::COND_LE;
3512 case ISD::SETNE: return X86::COND_NE;
3513 case ISD::SETULT: return X86::COND_B;
3514 case ISD::SETUGT: return X86::COND_A;
3515 case ISD::SETULE: return X86::COND_BE;
3516 case ISD::SETUGE: return X86::COND_AE;
3520 // First determine if it is required or is profitable to flip the operands.
3522 // If LHS is a foldable load, but RHS is not, flip the condition.
3523 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3524 !ISD::isNON_EXTLoad(RHS.getNode())) {
3525 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3526 std::swap(LHS, RHS);
3529 switch (SetCCOpcode) {
3535 std::swap(LHS, RHS);
3539 // On a floating point condition, the flags are set as follows:
3541 // 0 | 0 | 0 | X > Y
3542 // 0 | 0 | 1 | X < Y
3543 // 1 | 0 | 0 | X == Y
3544 // 1 | 1 | 1 | unordered
3545 switch (SetCCOpcode) {
3546 default: llvm_unreachable("Condcode should be pre-legalized away");
3548 case ISD::SETEQ: return X86::COND_E;
3549 case ISD::SETOLT: // flipped
3551 case ISD::SETGT: return X86::COND_A;
3552 case ISD::SETOLE: // flipped
3554 case ISD::SETGE: return X86::COND_AE;
3555 case ISD::SETUGT: // flipped
3557 case ISD::SETLT: return X86::COND_B;
3558 case ISD::SETUGE: // flipped
3560 case ISD::SETLE: return X86::COND_BE;
3562 case ISD::SETNE: return X86::COND_NE;
3563 case ISD::SETUO: return X86::COND_P;
3564 case ISD::SETO: return X86::COND_NP;
3566 case ISD::SETUNE: return X86::COND_INVALID;
3570 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3571 /// code. Current x86 isa includes the following FP cmov instructions:
3572 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3573 static bool hasFPCMov(unsigned X86CC) {
3589 /// isFPImmLegal - Returns true if the target can instruction select the
3590 /// specified FP immediate natively. If false, the legalizer will
3591 /// materialize the FP immediate as a load from a constant pool.
3592 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3593 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3594 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3600 /// \brief Returns true if it is beneficial to convert a load of a constant
3601 /// to just the constant itself.
3602 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3604 assert(Ty->isIntegerTy());
3606 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3607 if (BitSize == 0 || BitSize > 64)
3612 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3613 /// the specified range (L, H].
3614 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3615 return (Val < 0) || (Val >= Low && Val < Hi);
3618 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3619 /// specified value.
3620 static bool isUndefOrEqual(int Val, int CmpVal) {
3621 return (Val < 0 || Val == CmpVal);
3624 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3625 /// from position Pos and ending in Pos+Size, falls within the specified
3626 /// sequential range (L, L+Pos]. or is undef.
3627 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3628 unsigned Pos, unsigned Size, int Low) {
3629 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3630 if (!isUndefOrEqual(Mask[i], Low))
3635 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3636 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3637 /// the second operand.
3638 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3639 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3640 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3641 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3642 return (Mask[0] < 2 && Mask[1] < 2);
3646 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3647 /// is suitable for input to PSHUFHW.
3648 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3649 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3652 // Lower quadword copied in order or undef.
3653 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3656 // Upper quadword shuffled.
3657 for (unsigned i = 4; i != 8; ++i)
3658 if (!isUndefOrInRange(Mask[i], 4, 8))
3661 if (VT == MVT::v16i16) {
3662 // Lower quadword copied in order or undef.
3663 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3666 // Upper quadword shuffled.
3667 for (unsigned i = 12; i != 16; ++i)
3668 if (!isUndefOrInRange(Mask[i], 12, 16))
3675 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3676 /// is suitable for input to PSHUFLW.
3677 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3678 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3681 // Upper quadword copied in order.
3682 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3685 // Lower quadword shuffled.
3686 for (unsigned i = 0; i != 4; ++i)
3687 if (!isUndefOrInRange(Mask[i], 0, 4))
3690 if (VT == MVT::v16i16) {
3691 // Upper quadword copied in order.
3692 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3695 // Lower quadword shuffled.
3696 for (unsigned i = 8; i != 12; ++i)
3697 if (!isUndefOrInRange(Mask[i], 8, 12))
3704 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3705 /// is suitable for input to PALIGNR.
3706 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3707 const X86Subtarget *Subtarget) {
3708 if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3709 (VT.is256BitVector() && !Subtarget->hasInt256()))
3712 unsigned NumElts = VT.getVectorNumElements();
3713 unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3714 unsigned NumLaneElts = NumElts/NumLanes;
3716 // Do not handle 64-bit element shuffles with palignr.
3717 if (NumLaneElts == 2)
3720 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3722 for (i = 0; i != NumLaneElts; ++i) {
3727 // Lane is all undef, go to next lane
3728 if (i == NumLaneElts)
3731 int Start = Mask[i+l];
3733 // Make sure its in this lane in one of the sources
3734 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3735 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3738 // If not lane 0, then we must match lane 0
3739 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3742 // Correct second source to be contiguous with first source
3743 if (Start >= (int)NumElts)
3744 Start -= NumElts - NumLaneElts;
3746 // Make sure we're shifting in the right direction.
3747 if (Start <= (int)(i+l))
3752 // Check the rest of the elements to see if they are consecutive.
3753 for (++i; i != NumLaneElts; ++i) {
3754 int Idx = Mask[i+l];
3756 // Make sure its in this lane
3757 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3758 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3761 // If not lane 0, then we must match lane 0
3762 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3765 if (Idx >= (int)NumElts)
3766 Idx -= NumElts - NumLaneElts;
3768 if (!isUndefOrEqual(Idx, Start+i))
3777 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3778 /// the two vector operands have swapped position.
3779 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3780 unsigned NumElems) {
3781 for (unsigned i = 0; i != NumElems; ++i) {
3785 else if (idx < (int)NumElems)
3786 Mask[i] = idx + NumElems;
3788 Mask[i] = idx - NumElems;
3792 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3793 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3794 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3795 /// reverse of what x86 shuffles want.
3796 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3798 unsigned NumElems = VT.getVectorNumElements();
3799 unsigned NumLanes = VT.getSizeInBits()/128;
3800 unsigned NumLaneElems = NumElems/NumLanes;
3802 if (NumLaneElems != 2 && NumLaneElems != 4)
3805 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3806 bool symetricMaskRequired =
3807 (VT.getSizeInBits() >= 256) && (EltSize == 32);
3809 // VSHUFPSY divides the resulting vector into 4 chunks.
3810 // The sources are also splitted into 4 chunks, and each destination
3811 // chunk must come from a different source chunk.
3813 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3814 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3816 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3817 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3819 // VSHUFPDY divides the resulting vector into 4 chunks.
3820 // The sources are also splitted into 4 chunks, and each destination
3821 // chunk must come from a different source chunk.
3823 // SRC1 => X3 X2 X1 X0
3824 // SRC2 => Y3 Y2 Y1 Y0
3826 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3828 SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3829 unsigned HalfLaneElems = NumLaneElems/2;
3830 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3831 for (unsigned i = 0; i != NumLaneElems; ++i) {
3832 int Idx = Mask[i+l];
3833 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3834 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3836 // For VSHUFPSY, the mask of the second half must be the same as the
3837 // first but with the appropriate offsets. This works in the same way as
3838 // VPERMILPS works with masks.
3839 if (!symetricMaskRequired || Idx < 0)
3841 if (MaskVal[i] < 0) {
3842 MaskVal[i] = Idx - l;
3845 if ((signed)(Idx - l) != MaskVal[i])
3853 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3854 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3855 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3856 if (!VT.is128BitVector())
3859 unsigned NumElems = VT.getVectorNumElements();
3864 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3865 return isUndefOrEqual(Mask[0], 6) &&
3866 isUndefOrEqual(Mask[1], 7) &&
3867 isUndefOrEqual(Mask[2], 2) &&
3868 isUndefOrEqual(Mask[3], 3);
3871 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3872 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3874 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3875 if (!VT.is128BitVector())
3878 unsigned NumElems = VT.getVectorNumElements();
3883 return isUndefOrEqual(Mask[0], 2) &&
3884 isUndefOrEqual(Mask[1], 3) &&
3885 isUndefOrEqual(Mask[2], 2) &&
3886 isUndefOrEqual(Mask[3], 3);
3889 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3890 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3891 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3892 if (!VT.is128BitVector())
3895 unsigned NumElems = VT.getVectorNumElements();
3897 if (NumElems != 2 && NumElems != 4)
3900 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3901 if (!isUndefOrEqual(Mask[i], i + NumElems))
3904 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3905 if (!isUndefOrEqual(Mask[i], i))
3911 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3912 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3913 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3914 if (!VT.is128BitVector())
3917 unsigned NumElems = VT.getVectorNumElements();
3919 if (NumElems != 2 && NumElems != 4)
3922 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3923 if (!isUndefOrEqual(Mask[i], i))
3926 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3927 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3933 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
3934 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
3935 /// i. e: If all but one element come from the same vector.
3936 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
3937 // TODO: Deal with AVX's VINSERTPS
3938 if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
3941 unsigned CorrectPosV1 = 0;
3942 unsigned CorrectPosV2 = 0;
3943 for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i)
3946 else if (Mask[i] == i + 4)
3949 if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
3950 // We have 3 elements from one vector, and one from another.
3957 // Some special combinations that can be optimized.
3960 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3961 SelectionDAG &DAG) {
3962 MVT VT = SVOp->getSimpleValueType(0);
3965 if (VT != MVT::v8i32 && VT != MVT::v8f32)
3968 ArrayRef<int> Mask = SVOp->getMask();
3970 // These are the special masks that may be optimized.
3971 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3972 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
3973 bool MatchEvenMask = true;
3974 bool MatchOddMask = true;
3975 for (int i=0; i<8; ++i) {
3976 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3977 MatchEvenMask = false;
3978 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3979 MatchOddMask = false;
3982 if (!MatchEvenMask && !MatchOddMask)
3985 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3987 SDValue Op0 = SVOp->getOperand(0);
3988 SDValue Op1 = SVOp->getOperand(1);
3990 if (MatchEvenMask) {
3991 // Shift the second operand right to 32 bits.
3992 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3993 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3995 // Shift the first operand left to 32 bits.
3996 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3997 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3999 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4000 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4003 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4004 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4005 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4006 bool HasInt256, bool V2IsSplat = false) {
4008 assert(VT.getSizeInBits() >= 128 &&
4009 "Unsupported vector type for unpckl");
4011 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4013 unsigned NumOf256BitLanes;
4014 unsigned NumElts = VT.getVectorNumElements();
4015 if (VT.is256BitVector()) {
4016 if (NumElts != 4 && NumElts != 8 &&
4017 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4020 NumOf256BitLanes = 1;
4021 } else if (VT.is512BitVector()) {
4022 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4023 "Unsupported vector type for unpckh");
4025 NumOf256BitLanes = 2;
4028 NumOf256BitLanes = 1;
4031 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4032 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4034 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4035 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4036 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4037 int BitI = Mask[l256*NumEltsInStride+l+i];
4038 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4039 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4041 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4043 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4051 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4052 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4053 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4054 bool HasInt256, bool V2IsSplat = false) {
4055 assert(VT.getSizeInBits() >= 128 &&
4056 "Unsupported vector type for unpckh");
4058 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4060 unsigned NumOf256BitLanes;
4061 unsigned NumElts = VT.getVectorNumElements();
4062 if (VT.is256BitVector()) {
4063 if (NumElts != 4 && NumElts != 8 &&
4064 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4067 NumOf256BitLanes = 1;
4068 } else if (VT.is512BitVector()) {
4069 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4070 "Unsupported vector type for unpckh");
4072 NumOf256BitLanes = 2;
4075 NumOf256BitLanes = 1;
4078 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4079 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4081 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4082 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4083 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4084 int BitI = Mask[l256*NumEltsInStride+l+i];
4085 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4086 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4088 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4090 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4098 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4099 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4101 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4102 unsigned NumElts = VT.getVectorNumElements();
4103 bool Is256BitVec = VT.is256BitVector();
4105 if (VT.is512BitVector())
4107 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4108 "Unsupported vector type for unpckh");
4110 if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4111 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4114 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4115 // FIXME: Need a better way to get rid of this, there's no latency difference
4116 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4117 // the former later. We should also remove the "_undef" special mask.
4118 if (NumElts == 4 && Is256BitVec)
4121 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4122 // independently on 128-bit lanes.
4123 unsigned NumLanes = VT.getSizeInBits()/128;
4124 unsigned NumLaneElts = NumElts/NumLanes;
4126 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4127 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4128 int BitI = Mask[l+i];
4129 int BitI1 = Mask[l+i+1];
4131 if (!isUndefOrEqual(BitI, j))
4133 if (!isUndefOrEqual(BitI1, j))
4141 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4142 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4144 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4145 unsigned NumElts = VT.getVectorNumElements();
4147 if (VT.is512BitVector())
4150 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4151 "Unsupported vector type for unpckh");
4153 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4154 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4157 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4158 // independently on 128-bit lanes.
4159 unsigned NumLanes = VT.getSizeInBits()/128;
4160 unsigned NumLaneElts = NumElts/NumLanes;
4162 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4163 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4164 int BitI = Mask[l+i];
4165 int BitI1 = Mask[l+i+1];
4166 if (!isUndefOrEqual(BitI, j))
4168 if (!isUndefOrEqual(BitI1, j))
4175 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4176 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4177 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4178 if (!VT.is512BitVector())
4181 unsigned NumElts = VT.getVectorNumElements();
4182 unsigned HalfSize = NumElts/2;
4183 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4184 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4189 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4190 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4198 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4199 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4200 /// MOVSD, and MOVD, i.e. setting the lowest element.
4201 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4202 if (VT.getVectorElementType().getSizeInBits() < 32)
4204 if (!VT.is128BitVector())
4207 unsigned NumElts = VT.getVectorNumElements();
4209 if (!isUndefOrEqual(Mask[0], NumElts))
4212 for (unsigned i = 1; i != NumElts; ++i)
4213 if (!isUndefOrEqual(Mask[i], i))
4219 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4220 /// as permutations between 128-bit chunks or halves. As an example: this
4222 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4223 /// The first half comes from the second half of V1 and the second half from the
4224 /// the second half of V2.
4225 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4226 if (!HasFp256 || !VT.is256BitVector())
4229 // The shuffle result is divided into half A and half B. In total the two
4230 // sources have 4 halves, namely: C, D, E, F. The final values of A and
4231 // B must come from C, D, E or F.
4232 unsigned HalfSize = VT.getVectorNumElements()/2;
4233 bool MatchA = false, MatchB = false;
4235 // Check if A comes from one of C, D, E, F.
4236 for (unsigned Half = 0; Half != 4; ++Half) {
4237 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4243 // Check if B comes from one of C, D, E, F.
4244 for (unsigned Half = 0; Half != 4; ++Half) {
4245 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4251 return MatchA && MatchB;
4254 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4255 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4256 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4257 MVT VT = SVOp->getSimpleValueType(0);
4259 unsigned HalfSize = VT.getVectorNumElements()/2;
4261 unsigned FstHalf = 0, SndHalf = 0;
4262 for (unsigned i = 0; i < HalfSize; ++i) {
4263 if (SVOp->getMaskElt(i) > 0) {
4264 FstHalf = SVOp->getMaskElt(i)/HalfSize;
4268 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4269 if (SVOp->getMaskElt(i) > 0) {
4270 SndHalf = SVOp->getMaskElt(i)/HalfSize;
4275 return (FstHalf | (SndHalf << 4));
4278 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4279 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4280 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4284 unsigned NumElts = VT.getVectorNumElements();
4286 if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4287 for (unsigned i = 0; i != NumElts; ++i) {
4290 Imm8 |= Mask[i] << (i*2);
4295 unsigned LaneSize = 4;
4296 SmallVector<int, 4> MaskVal(LaneSize, -1);
4298 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4299 for (unsigned i = 0; i != LaneSize; ++i) {
4300 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4304 if (MaskVal[i] < 0) {
4305 MaskVal[i] = Mask[i+l] - l;
4306 Imm8 |= MaskVal[i] << (i*2);
4309 if (Mask[i+l] != (signed)(MaskVal[i]+l))
4316 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4317 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4318 /// Note that VPERMIL mask matching is different depending whether theunderlying
4319 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4320 /// to the same elements of the low, but to the higher half of the source.
4321 /// In VPERMILPD the two lanes could be shuffled independently of each other
4322 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4323 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4324 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4325 if (VT.getSizeInBits() < 256 || EltSize < 32)
4327 bool symetricMaskRequired = (EltSize == 32);
4328 unsigned NumElts = VT.getVectorNumElements();
4330 unsigned NumLanes = VT.getSizeInBits()/128;
4331 unsigned LaneSize = NumElts/NumLanes;
4332 // 2 or 4 elements in one lane
4334 SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4335 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4336 for (unsigned i = 0; i != LaneSize; ++i) {
4337 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4339 if (symetricMaskRequired) {
4340 if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4341 ExpectedMaskVal[i] = Mask[i+l] - l;
4344 if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4352 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4353 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
4354 /// element of vector 2 and the other elements to come from vector 1 in order.
4355 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4356 bool V2IsSplat = false, bool V2IsUndef = false) {
4357 if (!VT.is128BitVector())
4360 unsigned NumOps = VT.getVectorNumElements();
4361 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4364 if (!isUndefOrEqual(Mask[0], 0))
4367 for (unsigned i = 1; i != NumOps; ++i)
4368 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4369 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4370 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4376 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4377 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4378 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4379 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4380 const X86Subtarget *Subtarget) {
4381 if (!Subtarget->hasSSE3())
4384 unsigned NumElems = VT.getVectorNumElements();
4386 if ((VT.is128BitVector() && NumElems != 4) ||
4387 (VT.is256BitVector() && NumElems != 8) ||
4388 (VT.is512BitVector() && NumElems != 16))
4391 // "i+1" is the value the indexed mask element must have
4392 for (unsigned i = 0; i != NumElems; i += 2)
4393 if (!isUndefOrEqual(Mask[i], i+1) ||
4394 !isUndefOrEqual(Mask[i+1], i+1))
4400 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4401 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4402 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4403 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4404 const X86Subtarget *Subtarget) {
4405 if (!Subtarget->hasSSE3())
4408 unsigned NumElems = VT.getVectorNumElements();
4410 if ((VT.is128BitVector() && NumElems != 4) ||
4411 (VT.is256BitVector() && NumElems != 8) ||
4412 (VT.is512BitVector() && NumElems != 16))
4415 // "i" is the value the indexed mask element must have
4416 for (unsigned i = 0; i != NumElems; i += 2)
4417 if (!isUndefOrEqual(Mask[i], i) ||
4418 !isUndefOrEqual(Mask[i+1], i))
4424 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4425 /// specifies a shuffle of elements that is suitable for input to 256-bit
4426 /// version of MOVDDUP.
4427 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4428 if (!HasFp256 || !VT.is256BitVector())
4431 unsigned NumElts = VT.getVectorNumElements();
4435 for (unsigned i = 0; i != NumElts/2; ++i)
4436 if (!isUndefOrEqual(Mask[i], 0))
4438 for (unsigned i = NumElts/2; i != NumElts; ++i)
4439 if (!isUndefOrEqual(Mask[i], NumElts/2))
4444 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4445 /// specifies a shuffle of elements that is suitable for input to 128-bit
4446 /// version of MOVDDUP.
4447 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4448 if (!VT.is128BitVector())
4451 unsigned e = VT.getVectorNumElements() / 2;
4452 for (unsigned i = 0; i != e; ++i)
4453 if (!isUndefOrEqual(Mask[i], i))
4455 for (unsigned i = 0; i != e; ++i)
4456 if (!isUndefOrEqual(Mask[e+i], i))
4461 /// isVEXTRACTIndex - Return true if the specified
4462 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4463 /// suitable for instruction that extract 128 or 256 bit vectors
4464 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4465 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4466 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4469 // The index should be aligned on a vecWidth-bit boundary.
4471 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4473 MVT VT = N->getSimpleValueType(0);
4474 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4475 bool Result = (Index * ElSize) % vecWidth == 0;
4480 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4481 /// operand specifies a subvector insert that is suitable for input to
4482 /// insertion of 128 or 256-bit subvectors
4483 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4484 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4485 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4487 // The index should be aligned on a vecWidth-bit boundary.
4489 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4491 MVT VT = N->getSimpleValueType(0);
4492 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4493 bool Result = (Index * ElSize) % vecWidth == 0;
4498 bool X86::isVINSERT128Index(SDNode *N) {
4499 return isVINSERTIndex(N, 128);
4502 bool X86::isVINSERT256Index(SDNode *N) {
4503 return isVINSERTIndex(N, 256);
4506 bool X86::isVEXTRACT128Index(SDNode *N) {
4507 return isVEXTRACTIndex(N, 128);
4510 bool X86::isVEXTRACT256Index(SDNode *N) {
4511 return isVEXTRACTIndex(N, 256);
4514 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4515 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4516 /// Handles 128-bit and 256-bit.
4517 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4518 MVT VT = N->getSimpleValueType(0);
4520 assert((VT.getSizeInBits() >= 128) &&
4521 "Unsupported vector type for PSHUF/SHUFP");
4523 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4524 // independently on 128-bit lanes.
4525 unsigned NumElts = VT.getVectorNumElements();
4526 unsigned NumLanes = VT.getSizeInBits()/128;
4527 unsigned NumLaneElts = NumElts/NumLanes;
4529 assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4530 "Only supports 2, 4 or 8 elements per lane");
4532 unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4534 for (unsigned i = 0; i != NumElts; ++i) {
4535 int Elt = N->getMaskElt(i);
4536 if (Elt < 0) continue;
4537 Elt &= NumLaneElts - 1;
4538 unsigned ShAmt = (i << Shift) % 8;
4539 Mask |= Elt << ShAmt;
4545 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4546 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4547 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4548 MVT VT = N->getSimpleValueType(0);
4550 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4551 "Unsupported vector type for PSHUFHW");
4553 unsigned NumElts = VT.getVectorNumElements();
4556 for (unsigned l = 0; l != NumElts; l += 8) {
4557 // 8 nodes per lane, but we only care about the last 4.
4558 for (unsigned i = 0; i < 4; ++i) {
4559 int Elt = N->getMaskElt(l+i+4);
4560 if (Elt < 0) continue;
4561 Elt &= 0x3; // only 2-bits.
4562 Mask |= Elt << (i * 2);
4569 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4570 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4571 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4572 MVT VT = N->getSimpleValueType(0);
4574 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4575 "Unsupported vector type for PSHUFHW");
4577 unsigned NumElts = VT.getVectorNumElements();
4580 for (unsigned l = 0; l != NumElts; l += 8) {
4581 // 8 nodes per lane, but we only care about the first 4.
4582 for (unsigned i = 0; i < 4; ++i) {
4583 int Elt = N->getMaskElt(l+i);
4584 if (Elt < 0) continue;
4585 Elt &= 0x3; // only 2-bits
4586 Mask |= Elt << (i * 2);
4593 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4594 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4595 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4596 MVT VT = SVOp->getSimpleValueType(0);
4597 unsigned EltSize = VT.is512BitVector() ? 1 :
4598 VT.getVectorElementType().getSizeInBits() >> 3;
4600 unsigned NumElts = VT.getVectorNumElements();
4601 unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4602 unsigned NumLaneElts = NumElts/NumLanes;
4606 for (i = 0; i != NumElts; ++i) {
4607 Val = SVOp->getMaskElt(i);
4611 if (Val >= (int)NumElts)
4612 Val -= NumElts - NumLaneElts;
4614 assert(Val - i > 0 && "PALIGNR imm should be positive");
4615 return (Val - i) * EltSize;
4618 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4619 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4620 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4621 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4624 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4626 MVT VecVT = N->getOperand(0).getSimpleValueType();
4627 MVT ElVT = VecVT.getVectorElementType();
4629 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4630 return Index / NumElemsPerChunk;
4633 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4634 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4635 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4636 llvm_unreachable("Illegal insert subvector for VINSERT");
4639 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4641 MVT VecVT = N->getSimpleValueType(0);
4642 MVT ElVT = VecVT.getVectorElementType();
4644 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4645 return Index / NumElemsPerChunk;
4648 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4649 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4650 /// and VINSERTI128 instructions.
4651 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4652 return getExtractVEXTRACTImmediate(N, 128);
4655 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4656 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4657 /// and VINSERTI64x4 instructions.
4658 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4659 return getExtractVEXTRACTImmediate(N, 256);
4662 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4663 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4664 /// and VINSERTI128 instructions.
4665 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4666 return getInsertVINSERTImmediate(N, 128);
4669 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4670 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4671 /// and VINSERTI64x4 instructions.
4672 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4673 return getInsertVINSERTImmediate(N, 256);
4676 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4678 bool X86::isZeroNode(SDValue Elt) {
4679 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4680 return CN->isNullValue();
4681 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4682 return CFP->getValueAPF().isPosZero();
4686 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4687 /// their permute mask.
4688 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4689 SelectionDAG &DAG) {
4690 MVT VT = SVOp->getSimpleValueType(0);
4691 unsigned NumElems = VT.getVectorNumElements();
4692 SmallVector<int, 8> MaskVec;
4694 for (unsigned i = 0; i != NumElems; ++i) {
4695 int Idx = SVOp->getMaskElt(i);
4697 if (Idx < (int)NumElems)
4702 MaskVec.push_back(Idx);
4704 return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4705 SVOp->getOperand(0), &MaskVec[0]);
4708 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4709 /// match movhlps. The lower half elements should come from upper half of
4710 /// V1 (and in order), and the upper half elements should come from the upper
4711 /// half of V2 (and in order).
4712 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4713 if (!VT.is128BitVector())
4715 if (VT.getVectorNumElements() != 4)
4717 for (unsigned i = 0, e = 2; i != e; ++i)
4718 if (!isUndefOrEqual(Mask[i], i+2))
4720 for (unsigned i = 2; i != 4; ++i)
4721 if (!isUndefOrEqual(Mask[i], i+4))
4726 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4727 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4729 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4730 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4732 N = N->getOperand(0).getNode();
4733 if (!ISD::isNON_EXTLoad(N))
4736 *LD = cast<LoadSDNode>(N);
4740 // Test whether the given value is a vector value which will be legalized
4742 static bool WillBeConstantPoolLoad(SDNode *N) {
4743 if (N->getOpcode() != ISD::BUILD_VECTOR)
4746 // Check for any non-constant elements.
4747 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4748 switch (N->getOperand(i).getNode()->getOpcode()) {
4750 case ISD::ConstantFP:
4757 // Vectors of all-zeros and all-ones are materialized with special
4758 // instructions rather than being loaded.
4759 return !ISD::isBuildVectorAllZeros(N) &&
4760 !ISD::isBuildVectorAllOnes(N);
4763 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4764 /// match movlp{s|d}. The lower half elements should come from lower half of
4765 /// V1 (and in order), and the upper half elements should come from the upper
4766 /// half of V2 (and in order). And since V1 will become the source of the
4767 /// MOVLP, it must be either a vector load or a scalar load to vector.
4768 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4769 ArrayRef<int> Mask, MVT VT) {
4770 if (!VT.is128BitVector())
4773 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4775 // Is V2 is a vector load, don't do this transformation. We will try to use
4776 // load folding shufps op.
4777 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4780 unsigned NumElems = VT.getVectorNumElements();
4782 if (NumElems != 2 && NumElems != 4)
4784 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4785 if (!isUndefOrEqual(Mask[i], i))
4787 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4788 if (!isUndefOrEqual(Mask[i], i+NumElems))
4793 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4795 static bool isSplatVector(SDNode *N) {
4796 if (N->getOpcode() != ISD::BUILD_VECTOR)
4799 SDValue SplatValue = N->getOperand(0);
4800 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4801 if (N->getOperand(i) != SplatValue)
4806 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4807 /// to an zero vector.
4808 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4809 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4810 SDValue V1 = N->getOperand(0);
4811 SDValue V2 = N->getOperand(1);
4812 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4813 for (unsigned i = 0; i != NumElems; ++i) {
4814 int Idx = N->getMaskElt(i);
4815 if (Idx >= (int)NumElems) {
4816 unsigned Opc = V2.getOpcode();
4817 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4819 if (Opc != ISD::BUILD_VECTOR ||
4820 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4822 } else if (Idx >= 0) {
4823 unsigned Opc = V1.getOpcode();
4824 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4826 if (Opc != ISD::BUILD_VECTOR ||
4827 !X86::isZeroNode(V1.getOperand(Idx)))
4834 /// getZeroVector - Returns a vector of specified type with all zero elements.
4836 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4837 SelectionDAG &DAG, SDLoc dl) {
4838 assert(VT.isVector() && "Expected a vector type");
4840 // Always build SSE zero vectors as <4 x i32> bitcasted
4841 // to their dest type. This ensures they get CSE'd.
4843 if (VT.is128BitVector()) { // SSE
4844 if (Subtarget->hasSSE2()) { // SSE2
4845 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4846 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4848 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4849 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4851 } else if (VT.is256BitVector()) { // AVX
4852 if (Subtarget->hasInt256()) { // AVX2
4853 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4854 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4855 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4857 // 256-bit logic and arithmetic instructions in AVX are all
4858 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4859 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4860 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4861 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4863 } else if (VT.is512BitVector()) { // AVX-512
4864 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4865 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4866 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4867 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4868 } else if (VT.getScalarType() == MVT::i1) {
4869 assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4870 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4871 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4872 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4874 llvm_unreachable("Unexpected vector type");
4876 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4879 /// getOnesVector - Returns a vector of specified type with all bits set.
4880 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4881 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4882 /// Then bitcast to their original type, ensuring they get CSE'd.
4883 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4885 assert(VT.isVector() && "Expected a vector type");
4887 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4889 if (VT.is256BitVector()) {
4890 if (HasInt256) { // AVX2
4891 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4892 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4894 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4895 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4897 } else if (VT.is128BitVector()) {
4898 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4900 llvm_unreachable("Unexpected vector type");
4902 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4905 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4906 /// that point to V2 points to its first element.
4907 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4908 for (unsigned i = 0; i != NumElems; ++i) {
4909 if (Mask[i] > (int)NumElems) {
4915 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4916 /// operation of specified width.
4917 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4919 unsigned NumElems = VT.getVectorNumElements();
4920 SmallVector<int, 8> Mask;
4921 Mask.push_back(NumElems);
4922 for (unsigned i = 1; i != NumElems; ++i)
4924 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4927 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4928 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4930 unsigned NumElems = VT.getVectorNumElements();
4931 SmallVector<int, 8> Mask;
4932 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4934 Mask.push_back(i + NumElems);
4936 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4939 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4940 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4942 unsigned NumElems = VT.getVectorNumElements();
4943 SmallVector<int, 8> Mask;
4944 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4945 Mask.push_back(i + Half);
4946 Mask.push_back(i + NumElems + Half);
4948 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4951 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4952 // a generic shuffle instruction because the target has no such instructions.
4953 // Generate shuffles which repeat i16 and i8 several times until they can be
4954 // represented by v4f32 and then be manipulated by target suported shuffles.
4955 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4956 MVT VT = V.getSimpleValueType();
4957 int NumElems = VT.getVectorNumElements();
4960 while (NumElems > 4) {
4961 if (EltNo < NumElems/2) {
4962 V = getUnpackl(DAG, dl, VT, V, V);
4964 V = getUnpackh(DAG, dl, VT, V, V);
4965 EltNo -= NumElems/2;
4972 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4973 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4974 MVT VT = V.getSimpleValueType();
4977 if (VT.is128BitVector()) {
4978 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4979 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4980 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4982 } else if (VT.is256BitVector()) {
4983 // To use VPERMILPS to splat scalars, the second half of indicies must
4984 // refer to the higher part, which is a duplication of the lower one,
4985 // because VPERMILPS can only handle in-lane permutations.
4986 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4987 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4989 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4990 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4993 llvm_unreachable("Vector size not supported");
4995 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4998 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4999 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5000 MVT SrcVT = SV->getSimpleValueType(0);
5001 SDValue V1 = SV->getOperand(0);
5004 int EltNo = SV->getSplatIndex();
5005 int NumElems = SrcVT.getVectorNumElements();
5006 bool Is256BitVec = SrcVT.is256BitVector();
5008 assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5009 "Unknown how to promote splat for type");
5011 // Extract the 128-bit part containing the splat element and update
5012 // the splat element index when it refers to the higher register.
5014 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5015 if (EltNo >= NumElems/2)
5016 EltNo -= NumElems/2;
5019 // All i16 and i8 vector types can't be used directly by a generic shuffle
5020 // instruction because the target has no such instruction. Generate shuffles
5021 // which repeat i16 and i8 several times until they fit in i32, and then can
5022 // be manipulated by target suported shuffles.
5023 MVT EltVT = SrcVT.getVectorElementType();
5024 if (EltVT == MVT::i8 || EltVT == MVT::i16)
5025 V1 = PromoteSplati8i16(V1, DAG, EltNo);
5027 // Recreate the 256-bit vector and place the same 128-bit vector
5028 // into the low and high part. This is necessary because we want
5029 // to use VPERM* to shuffle the vectors
5031 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5034 return getLegalSplat(DAG, V1, EltNo);
5037 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5038 /// vector of zero or undef vector. This produces a shuffle where the low
5039 /// element of V2 is swizzled into the zero/undef vector, landing at element
5040 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
5041 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5043 const X86Subtarget *Subtarget,
5044 SelectionDAG &DAG) {
5045 MVT VT = V2.getSimpleValueType();
5047 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5048 unsigned NumElems = VT.getVectorNumElements();
5049 SmallVector<int, 16> MaskVec;
5050 for (unsigned i = 0; i != NumElems; ++i)
5051 // If this is the insertion idx, put the low elt of V2 here.
5052 MaskVec.push_back(i == Idx ? NumElems : i);
5053 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5056 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5057 /// target specific opcode. Returns true if the Mask could be calculated.
5058 /// Sets IsUnary to true if only uses one source.
5059 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5060 SmallVectorImpl<int> &Mask, bool &IsUnary) {
5061 unsigned NumElems = VT.getVectorNumElements();
5065 switch(N->getOpcode()) {
5067 ImmN = N->getOperand(N->getNumOperands()-1);
5068 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5070 case X86ISD::UNPCKH:
5071 DecodeUNPCKHMask(VT, Mask);
5073 case X86ISD::UNPCKL:
5074 DecodeUNPCKLMask(VT, Mask);
5076 case X86ISD::MOVHLPS:
5077 DecodeMOVHLPSMask(NumElems, Mask);
5079 case X86ISD::MOVLHPS:
5080 DecodeMOVLHPSMask(NumElems, Mask);
5082 case X86ISD::PALIGNR:
5083 ImmN = N->getOperand(N->getNumOperands()-1);
5084 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5086 case X86ISD::PSHUFD:
5087 case X86ISD::VPERMILP:
5088 ImmN = N->getOperand(N->getNumOperands()-1);
5089 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5092 case X86ISD::PSHUFHW:
5093 ImmN = N->getOperand(N->getNumOperands()-1);
5094 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5097 case X86ISD::PSHUFLW:
5098 ImmN = N->getOperand(N->getNumOperands()-1);
5099 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5102 case X86ISD::VPERMI:
5103 ImmN = N->getOperand(N->getNumOperands()-1);
5104 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5108 case X86ISD::MOVSD: {
5109 // The index 0 always comes from the first element of the second source,
5110 // this is why MOVSS and MOVSD are used in the first place. The other
5111 // elements come from the other positions of the first source vector
5112 Mask.push_back(NumElems);
5113 for (unsigned i = 1; i != NumElems; ++i) {
5118 case X86ISD::VPERM2X128:
5119 ImmN = N->getOperand(N->getNumOperands()-1);
5120 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5121 if (Mask.empty()) return false;
5123 case X86ISD::MOVDDUP:
5124 case X86ISD::MOVLHPD:
5125 case X86ISD::MOVLPD:
5126 case X86ISD::MOVLPS:
5127 case X86ISD::MOVSHDUP:
5128 case X86ISD::MOVSLDUP:
5129 // Not yet implemented
5131 default: llvm_unreachable("unknown target shuffle node");
5137 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5138 /// element of the result of the vector shuffle.
5139 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5142 return SDValue(); // Limit search depth.
5144 SDValue V = SDValue(N, 0);
5145 EVT VT = V.getValueType();
5146 unsigned Opcode = V.getOpcode();
5148 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5149 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5150 int Elt = SV->getMaskElt(Index);
5153 return DAG.getUNDEF(VT.getVectorElementType());
5155 unsigned NumElems = VT.getVectorNumElements();
5156 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5157 : SV->getOperand(1);
5158 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5161 // Recurse into target specific vector shuffles to find scalars.
5162 if (isTargetShuffle(Opcode)) {
5163 MVT ShufVT = V.getSimpleValueType();
5164 unsigned NumElems = ShufVT.getVectorNumElements();
5165 SmallVector<int, 16> ShuffleMask;
5168 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5171 int Elt = ShuffleMask[Index];
5173 return DAG.getUNDEF(ShufVT.getVectorElementType());
5175 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5177 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5181 // Actual nodes that may contain scalar elements
5182 if (Opcode == ISD::BITCAST) {
5183 V = V.getOperand(0);
5184 EVT SrcVT = V.getValueType();
5185 unsigned NumElems = VT.getVectorNumElements();
5187 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5191 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5192 return (Index == 0) ? V.getOperand(0)
5193 : DAG.getUNDEF(VT.getVectorElementType());
5195 if (V.getOpcode() == ISD::BUILD_VECTOR)
5196 return V.getOperand(Index);
5201 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5202 /// shuffle operation which come from a consecutively from a zero. The
5203 /// search can start in two different directions, from left or right.
5204 /// We count undefs as zeros until PreferredNum is reached.
5205 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5206 unsigned NumElems, bool ZerosFromLeft,
5208 unsigned PreferredNum = -1U) {
5209 unsigned NumZeros = 0;
5210 for (unsigned i = 0; i != NumElems; ++i) {
5211 unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5212 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5216 if (X86::isZeroNode(Elt))
5218 else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5219 NumZeros = std::min(NumZeros + 1, PreferredNum);
5227 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5228 /// correspond consecutively to elements from one of the vector operands,
5229 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5231 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5232 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5233 unsigned NumElems, unsigned &OpNum) {
5234 bool SeenV1 = false;
5235 bool SeenV2 = false;
5237 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5238 int Idx = SVOp->getMaskElt(i);
5239 // Ignore undef indicies
5243 if (Idx < (int)NumElems)
5248 // Only accept consecutive elements from the same vector
5249 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5253 OpNum = SeenV1 ? 0 : 1;
5257 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5258 /// logical left shift of a vector.
5259 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5260 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5262 SVOp->getSimpleValueType(0).getVectorNumElements();
5263 unsigned NumZeros = getNumOfConsecutiveZeros(
5264 SVOp, NumElems, false /* check zeros from right */, DAG,
5265 SVOp->getMaskElt(0));
5271 // Considering the elements in the mask that are not consecutive zeros,
5272 // check if they consecutively come from only one of the source vectors.
5274 // V1 = {X, A, B, C} 0
5276 // vector_shuffle V1, V2 <1, 2, 3, X>
5278 if (!isShuffleMaskConsecutive(SVOp,
5279 0, // Mask Start Index
5280 NumElems-NumZeros, // Mask End Index(exclusive)
5281 NumZeros, // Where to start looking in the src vector
5282 NumElems, // Number of elements in vector
5283 OpSrc)) // Which source operand ?
5288 ShVal = SVOp->getOperand(OpSrc);
5292 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5293 /// logical left shift of a vector.
5294 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5295 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5297 SVOp->getSimpleValueType(0).getVectorNumElements();
5298 unsigned NumZeros = getNumOfConsecutiveZeros(
5299 SVOp, NumElems, true /* check zeros from left */, DAG,
5300 NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5306 // Considering the elements in the mask that are not consecutive zeros,
5307 // check if they consecutively come from only one of the source vectors.
5309 // 0 { A, B, X, X } = V2
5311 // vector_shuffle V1, V2 <X, X, 4, 5>
5313 if (!isShuffleMaskConsecutive(SVOp,
5314 NumZeros, // Mask Start Index
5315 NumElems, // Mask End Index(exclusive)
5316 0, // Where to start looking in the src vector
5317 NumElems, // Number of elements in vector
5318 OpSrc)) // Which source operand ?
5323 ShVal = SVOp->getOperand(OpSrc);
5327 /// isVectorShift - Returns true if the shuffle can be implemented as a
5328 /// logical left or right shift of a vector.
5329 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5330 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5331 // Although the logic below support any bitwidth size, there are no
5332 // shift instructions which handle more than 128-bit vectors.
5333 if (!SVOp->getSimpleValueType(0).is128BitVector())
5336 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5337 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5343 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5345 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5346 unsigned NumNonZero, unsigned NumZero,
5348 const X86Subtarget* Subtarget,
5349 const TargetLowering &TLI) {
5356 for (unsigned i = 0; i < 16; ++i) {
5357 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5358 if (ThisIsNonZero && First) {
5360 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5362 V = DAG.getUNDEF(MVT::v8i16);
5367 SDValue ThisElt, LastElt;
5368 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5369 if (LastIsNonZero) {
5370 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5371 MVT::i16, Op.getOperand(i-1));
5373 if (ThisIsNonZero) {
5374 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5375 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5376 ThisElt, DAG.getConstant(8, MVT::i8));
5378 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5382 if (ThisElt.getNode())
5383 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5384 DAG.getIntPtrConstant(i/2));
5388 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5391 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5393 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5394 unsigned NumNonZero, unsigned NumZero,
5396 const X86Subtarget* Subtarget,
5397 const TargetLowering &TLI) {
5404 for (unsigned i = 0; i < 8; ++i) {
5405 bool isNonZero = (NonZeros & (1 << i)) != 0;
5409 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5411 V = DAG.getUNDEF(MVT::v8i16);
5414 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5415 MVT::v8i16, V, Op.getOperand(i),
5416 DAG.getIntPtrConstant(i));
5423 /// getVShift - Return a vector logical shift node.
5425 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5426 unsigned NumBits, SelectionDAG &DAG,
5427 const TargetLowering &TLI, SDLoc dl) {
5428 assert(VT.is128BitVector() && "Unknown type for VShift");
5429 EVT ShVT = MVT::v2i64;
5430 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5431 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5432 return DAG.getNode(ISD::BITCAST, dl, VT,
5433 DAG.getNode(Opc, dl, ShVT, SrcOp,
5434 DAG.getConstant(NumBits,
5435 TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5439 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5441 // Check if the scalar load can be widened into a vector load. And if
5442 // the address is "base + cst" see if the cst can be "absorbed" into
5443 // the shuffle mask.
5444 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5445 SDValue Ptr = LD->getBasePtr();
5446 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5448 EVT PVT = LD->getValueType(0);
5449 if (PVT != MVT::i32 && PVT != MVT::f32)
5454 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5455 FI = FINode->getIndex();
5457 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5458 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5459 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5460 Offset = Ptr.getConstantOperandVal(1);
5461 Ptr = Ptr.getOperand(0);
5466 // FIXME: 256-bit vector instructions don't require a strict alignment,
5467 // improve this code to support it better.
5468 unsigned RequiredAlign = VT.getSizeInBits()/8;
5469 SDValue Chain = LD->getChain();
5470 // Make sure the stack object alignment is at least 16 or 32.
5471 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5472 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5473 if (MFI->isFixedObjectIndex(FI)) {
5474 // Can't change the alignment. FIXME: It's possible to compute
5475 // the exact stack offset and reference FI + adjust offset instead.
5476 // If someone *really* cares about this. That's the way to implement it.
5479 MFI->setObjectAlignment(FI, RequiredAlign);
5483 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5484 // Ptr + (Offset & ~15).
5487 if ((Offset % RequiredAlign) & 3)
5489 int64_t StartOffset = Offset & ~(RequiredAlign-1);
5491 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5492 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5494 int EltNo = (Offset - StartOffset) >> 2;
5495 unsigned NumElems = VT.getVectorNumElements();
5497 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5498 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5499 LD->getPointerInfo().getWithOffset(StartOffset),
5500 false, false, false, 0);
5502 SmallVector<int, 8> Mask;
5503 for (unsigned i = 0; i != NumElems; ++i)
5504 Mask.push_back(EltNo);
5506 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5512 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5513 /// vector of type 'VT', see if the elements can be replaced by a single large
5514 /// load which has the same value as a build_vector whose operands are 'elts'.
5516 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5518 /// FIXME: we'd also like to handle the case where the last elements are zero
5519 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5520 /// There's even a handy isZeroNode for that purpose.
5521 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5522 SDLoc &DL, SelectionDAG &DAG,
5523 bool isAfterLegalize) {
5524 EVT EltVT = VT.getVectorElementType();
5525 unsigned NumElems = Elts.size();
5527 LoadSDNode *LDBase = nullptr;
5528 unsigned LastLoadedElt = -1U;
5530 // For each element in the initializer, see if we've found a load or an undef.
5531 // If we don't find an initial load element, or later load elements are
5532 // non-consecutive, bail out.
5533 for (unsigned i = 0; i < NumElems; ++i) {
5534 SDValue Elt = Elts[i];
5536 if (!Elt.getNode() ||
5537 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5540 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5542 LDBase = cast<LoadSDNode>(Elt.getNode());
5546 if (Elt.getOpcode() == ISD::UNDEF)
5549 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5550 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5555 // If we have found an entire vector of loads and undefs, then return a large
5556 // load of the entire vector width starting at the base pointer. If we found
5557 // consecutive loads for the low half, generate a vzext_load node.
5558 if (LastLoadedElt == NumElems - 1) {
5560 if (isAfterLegalize &&
5561 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5564 SDValue NewLd = SDValue();
5566 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5567 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5568 LDBase->getPointerInfo(),
5569 LDBase->isVolatile(), LDBase->isNonTemporal(),
5570 LDBase->isInvariant(), 0);
5571 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5572 LDBase->getPointerInfo(),
5573 LDBase->isVolatile(), LDBase->isNonTemporal(),
5574 LDBase->isInvariant(), LDBase->getAlignment());
5576 if (LDBase->hasAnyUseOfValue(1)) {
5577 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5579 SDValue(NewLd.getNode(), 1));
5580 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5581 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5582 SDValue(NewLd.getNode(), 1));
5587 if (NumElems == 4 && LastLoadedElt == 1 &&
5588 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5589 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5590 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5592 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5593 LDBase->getPointerInfo(),
5594 LDBase->getAlignment(),
5595 false/*isVolatile*/, true/*ReadMem*/,
5598 // Make sure the newly-created LOAD is in the same position as LDBase in
5599 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5600 // update uses of LDBase's output chain to use the TokenFactor.
5601 if (LDBase->hasAnyUseOfValue(1)) {
5602 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5603 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5604 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5605 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5606 SDValue(ResNode.getNode(), 1));
5609 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5614 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5615 /// to generate a splat value for the following cases:
5616 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5617 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5618 /// a scalar load, or a constant.
5619 /// The VBROADCAST node is returned when a pattern is found,
5620 /// or SDValue() otherwise.
5621 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5622 SelectionDAG &DAG) {
5623 if (!Subtarget->hasFp256())
5626 MVT VT = Op.getSimpleValueType();
5629 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5630 "Unsupported vector type for broadcast.");
5635 switch (Op.getOpcode()) {
5637 // Unknown pattern found.
5640 case ISD::BUILD_VECTOR: {
5641 // The BUILD_VECTOR node must be a splat.
5642 if (!isSplatVector(Op.getNode()))
5645 Ld = Op.getOperand(0);
5646 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5647 Ld.getOpcode() == ISD::ConstantFP);
5649 // The suspected load node has several users. Make sure that all
5650 // of its users are from the BUILD_VECTOR node.
5651 // Constants may have multiple users.
5652 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5657 case ISD::VECTOR_SHUFFLE: {
5658 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5660 // Shuffles must have a splat mask where the first element is
5662 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5665 SDValue Sc = Op.getOperand(0);
5666 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5667 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5669 if (!Subtarget->hasInt256())
5672 // Use the register form of the broadcast instruction available on AVX2.
5673 if (VT.getSizeInBits() >= 256)
5674 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5675 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5678 Ld = Sc.getOperand(0);
5679 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5680 Ld.getOpcode() == ISD::ConstantFP);
5682 // The scalar_to_vector node and the suspected
5683 // load node must have exactly one user.
5684 // Constants may have multiple users.
5686 // AVX-512 has register version of the broadcast
5687 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5688 Ld.getValueType().getSizeInBits() >= 32;
5689 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5696 bool IsGE256 = (VT.getSizeInBits() >= 256);
5698 // Handle the broadcasting a single constant scalar from the constant pool
5699 // into a vector. On Sandybridge it is still better to load a constant vector
5700 // from the constant pool and not to broadcast it from a scalar.
5701 if (ConstSplatVal && Subtarget->hasInt256()) {
5702 EVT CVT = Ld.getValueType();
5703 assert(!CVT.isVector() && "Must not broadcast a vector type");
5704 unsigned ScalarSize = CVT.getSizeInBits();
5706 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5707 const Constant *C = nullptr;
5708 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5709 C = CI->getConstantIntValue();
5710 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5711 C = CF->getConstantFPValue();
5713 assert(C && "Invalid constant type");
5715 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5716 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5717 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5718 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5719 MachinePointerInfo::getConstantPool(),
5720 false, false, false, Alignment);
5722 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5726 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5727 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5729 // Handle AVX2 in-register broadcasts.
5730 if (!IsLoad && Subtarget->hasInt256() &&
5731 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5732 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5734 // The scalar source must be a normal load.
5738 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5739 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5741 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5742 // double since there is no vbroadcastsd xmm
5743 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5744 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5745 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5748 // Unsupported broadcast.
5752 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5753 /// underlying vector and index.
5755 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5757 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5759 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5760 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5763 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5765 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5767 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5768 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5771 // In this case the vector is the extract_subvector expression and the index
5772 // is 2, as specified by the shuffle.
5773 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5774 SDValue ShuffleVec = SVOp->getOperand(0);
5775 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5776 assert(ShuffleVecVT.getVectorElementType() ==
5777 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5779 int ShuffleIdx = SVOp->getMaskElt(Idx);
5780 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5781 ExtractedFromVec = ShuffleVec;
5787 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5788 MVT VT = Op.getSimpleValueType();
5790 // Skip if insert_vec_elt is not supported.
5791 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5792 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5796 unsigned NumElems = Op.getNumOperands();
5800 SmallVector<unsigned, 4> InsertIndices;
5801 SmallVector<int, 8> Mask(NumElems, -1);
5803 for (unsigned i = 0; i != NumElems; ++i) {
5804 unsigned Opc = Op.getOperand(i).getOpcode();
5806 if (Opc == ISD::UNDEF)
5809 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5810 // Quit if more than 1 elements need inserting.
5811 if (InsertIndices.size() > 1)
5814 InsertIndices.push_back(i);
5818 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5819 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5820 // Quit if non-constant index.
5821 if (!isa<ConstantSDNode>(ExtIdx))
5823 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5825 // Quit if extracted from vector of different type.
5826 if (ExtractedFromVec.getValueType() != VT)
5829 if (!VecIn1.getNode())
5830 VecIn1 = ExtractedFromVec;
5831 else if (VecIn1 != ExtractedFromVec) {
5832 if (!VecIn2.getNode())
5833 VecIn2 = ExtractedFromVec;
5834 else if (VecIn2 != ExtractedFromVec)
5835 // Quit if more than 2 vectors to shuffle
5839 if (ExtractedFromVec == VecIn1)
5841 else if (ExtractedFromVec == VecIn2)
5842 Mask[i] = Idx + NumElems;
5845 if (!VecIn1.getNode())
5848 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5849 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5850 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5851 unsigned Idx = InsertIndices[i];
5852 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5853 DAG.getIntPtrConstant(Idx));
5859 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5861 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5863 MVT VT = Op.getSimpleValueType();
5864 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5865 "Unexpected type in LowerBUILD_VECTORvXi1!");
5868 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5869 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5870 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5871 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5874 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5875 SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5876 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5877 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5880 bool AllContants = true;
5881 uint64_t Immediate = 0;
5882 int NonConstIdx = -1;
5883 bool IsSplat = true;
5884 unsigned NumNonConsts = 0;
5885 unsigned NumConsts = 0;
5886 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5887 SDValue In = Op.getOperand(idx);
5888 if (In.getOpcode() == ISD::UNDEF)
5890 if (!isa<ConstantSDNode>(In)) {
5891 AllContants = false;
5897 if (cast<ConstantSDNode>(In)->getZExtValue())
5898 Immediate |= (1ULL << idx);
5900 if (In != Op.getOperand(0))
5905 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5906 DAG.getConstant(Immediate, MVT::i16));
5907 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5908 DAG.getIntPtrConstant(0));
5911 if (NumNonConsts == 1 && NonConstIdx != 0) {
5914 SDValue VecAsImm = DAG.getConstant(Immediate,
5915 MVT::getIntegerVT(VT.getSizeInBits()));
5916 DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
5919 DstVec = DAG.getUNDEF(VT);
5920 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5921 Op.getOperand(NonConstIdx),
5922 DAG.getIntPtrConstant(NonConstIdx));
5924 if (!IsSplat && (NonConstIdx != 0))
5925 llvm_unreachable("Unsupported BUILD_VECTOR operation");
5926 MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
5929 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5930 DAG.getConstant(-1, SelectVT),
5931 DAG.getConstant(0, SelectVT));
5933 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5934 DAG.getConstant((Immediate | 1), SelectVT),
5935 DAG.getConstant(Immediate, SelectVT));
5936 return DAG.getNode(ISD::BITCAST, dl, VT, Select);
5940 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5943 MVT VT = Op.getSimpleValueType();
5944 MVT ExtVT = VT.getVectorElementType();
5945 unsigned NumElems = Op.getNumOperands();
5947 // Generate vectors for predicate vectors.
5948 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5949 return LowerBUILD_VECTORvXi1(Op, DAG);
5951 // Vectors containing all zeros can be matched by pxor and xorps later
5952 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5953 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5954 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5955 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5958 return getZeroVector(VT, Subtarget, DAG, dl);
5961 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5962 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5963 // vpcmpeqd on 256-bit vectors.
5964 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5965 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5968 if (!VT.is512BitVector())
5969 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5972 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
5973 if (Broadcast.getNode())
5976 unsigned EVTBits = ExtVT.getSizeInBits();
5978 unsigned NumZero = 0;
5979 unsigned NumNonZero = 0;
5980 unsigned NonZeros = 0;
5981 bool IsAllConstants = true;
5982 SmallSet<SDValue, 8> Values;
5983 for (unsigned i = 0; i < NumElems; ++i) {
5984 SDValue Elt = Op.getOperand(i);
5985 if (Elt.getOpcode() == ISD::UNDEF)
5988 if (Elt.getOpcode() != ISD::Constant &&
5989 Elt.getOpcode() != ISD::ConstantFP)
5990 IsAllConstants = false;
5991 if (X86::isZeroNode(Elt))
5994 NonZeros |= (1 << i);
5999 // All undef vector. Return an UNDEF. All zero vectors were handled above.
6000 if (NumNonZero == 0)
6001 return DAG.getUNDEF(VT);
6003 // Special case for single non-zero, non-undef, element.
6004 if (NumNonZero == 1) {
6005 unsigned Idx = countTrailingZeros(NonZeros);
6006 SDValue Item = Op.getOperand(Idx);
6008 // If this is an insertion of an i64 value on x86-32, and if the top bits of
6009 // the value are obviously zero, truncate the value to i32 and do the
6010 // insertion that way. Only do this if the value is non-constant or if the
6011 // value is a constant being inserted into element 0. It is cheaper to do
6012 // a constant pool load than it is to do a movd + shuffle.
6013 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6014 (!IsAllConstants || Idx == 0)) {
6015 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6017 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6018 EVT VecVT = MVT::v4i32;
6019 unsigned VecElts = 4;
6021 // Truncate the value (which may itself be a constant) to i32, and
6022 // convert it to a vector with movd (S2V+shuffle to zero extend).
6023 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6024 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6025 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6027 // Now we have our 32-bit value zero extended in the low element of
6028 // a vector. If Idx != 0, swizzle it into place.
6030 SmallVector<int, 4> Mask;
6031 Mask.push_back(Idx);
6032 for (unsigned i = 1; i != VecElts; ++i)
6034 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6037 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6041 // If we have a constant or non-constant insertion into the low element of
6042 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6043 // the rest of the elements. This will be matched as movd/movq/movss/movsd
6044 // depending on what the source datatype is.
6047 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6049 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6050 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6051 if (VT.is256BitVector() || VT.is512BitVector()) {
6052 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6053 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6054 Item, DAG.getIntPtrConstant(0));
6056 assert(VT.is128BitVector() && "Expected an SSE value type!");
6057 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6058 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6059 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6062 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6063 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6064 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6065 if (VT.is256BitVector()) {
6066 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6067 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6069 assert(VT.is128BitVector() && "Expected an SSE value type!");
6070 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6072 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6076 // Is it a vector logical left shift?
6077 if (NumElems == 2 && Idx == 1 &&
6078 X86::isZeroNode(Op.getOperand(0)) &&
6079 !X86::isZeroNode(Op.getOperand(1))) {
6080 unsigned NumBits = VT.getSizeInBits();
6081 return getVShift(true, VT,
6082 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6083 VT, Op.getOperand(1)),
6084 NumBits/2, DAG, *this, dl);
6087 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6090 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6091 // is a non-constant being inserted into an element other than the low one,
6092 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6093 // movd/movss) to move this into the low element, then shuffle it into
6095 if (EVTBits == 32) {
6096 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6098 // Turn it into a shuffle of zero and zero-extended scalar to vector.
6099 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6100 SmallVector<int, 8> MaskVec;
6101 for (unsigned i = 0; i != NumElems; ++i)
6102 MaskVec.push_back(i == Idx ? 0 : 1);
6103 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6107 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6108 if (Values.size() == 1) {
6109 if (EVTBits == 32) {
6110 // Instead of a shuffle like this:
6111 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6112 // Check if it's possible to issue this instead.
6113 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6114 unsigned Idx = countTrailingZeros(NonZeros);
6115 SDValue Item = Op.getOperand(Idx);
6116 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6117 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6122 // A vector full of immediates; various special cases are already
6123 // handled, so this is best done with a single constant-pool load.
6127 // For AVX-length vectors, build the individual 128-bit pieces and use
6128 // shuffles to put them in place.
6129 if (VT.is256BitVector() || VT.is512BitVector()) {
6130 SmallVector<SDValue, 64> V;
6131 for (unsigned i = 0; i != NumElems; ++i)
6132 V.push_back(Op.getOperand(i));
6134 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6136 // Build both the lower and upper subvector.
6137 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6138 ArrayRef<SDValue>(&V[0], NumElems/2));
6139 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6140 ArrayRef<SDValue>(&V[NumElems / 2],
6143 // Recreate the wider vector with the lower and upper part.
6144 if (VT.is256BitVector())
6145 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6146 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6149 // Let legalizer expand 2-wide build_vectors.
6150 if (EVTBits == 64) {
6151 if (NumNonZero == 1) {
6152 // One half is zero or undef.
6153 unsigned Idx = countTrailingZeros(NonZeros);
6154 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6155 Op.getOperand(Idx));
6156 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6161 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6162 if (EVTBits == 8 && NumElems == 16) {
6163 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6165 if (V.getNode()) return V;
6168 if (EVTBits == 16 && NumElems == 8) {
6169 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6171 if (V.getNode()) return V;
6174 // If element VT is == 32 bits, turn it into a number of shuffles.
6175 SmallVector<SDValue, 8> V(NumElems);
6176 if (NumElems == 4 && NumZero > 0) {
6177 for (unsigned i = 0; i < 4; ++i) {
6178 bool isZero = !(NonZeros & (1 << i));
6180 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6182 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6185 for (unsigned i = 0; i < 2; ++i) {
6186 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6189 V[i] = V[i*2]; // Must be a zero vector.
6192 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6195 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6198 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6203 bool Reverse1 = (NonZeros & 0x3) == 2;
6204 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6208 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6209 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6211 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6214 if (Values.size() > 1 && VT.is128BitVector()) {
6215 // Check for a build vector of consecutive loads.
6216 for (unsigned i = 0; i < NumElems; ++i)
6217 V[i] = Op.getOperand(i);
6219 // Check for elements which are consecutive loads.
6220 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6224 // Check for a build vector from mostly shuffle plus few inserting.
6225 SDValue Sh = buildFromShuffleMostly(Op, DAG);
6229 // For SSE 4.1, use insertps to put the high elements into the low element.
6230 if (getSubtarget()->hasSSE41()) {
6232 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6233 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6235 Result = DAG.getUNDEF(VT);
6237 for (unsigned i = 1; i < NumElems; ++i) {
6238 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6239 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6240 Op.getOperand(i), DAG.getIntPtrConstant(i));
6245 // Otherwise, expand into a number of unpckl*, start by extending each of
6246 // our (non-undef) elements to the full vector width with the element in the
6247 // bottom slot of the vector (which generates no code for SSE).
6248 for (unsigned i = 0; i < NumElems; ++i) {
6249 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6250 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6252 V[i] = DAG.getUNDEF(VT);
6255 // Next, we iteratively mix elements, e.g. for v4f32:
6256 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6257 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6258 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6259 unsigned EltStride = NumElems >> 1;
6260 while (EltStride != 0) {
6261 for (unsigned i = 0; i < EltStride; ++i) {
6262 // If V[i+EltStride] is undef and this is the first round of mixing,
6263 // then it is safe to just drop this shuffle: V[i] is already in the
6264 // right place, the one element (since it's the first round) being
6265 // inserted as undef can be dropped. This isn't safe for successive
6266 // rounds because they will permute elements within both vectors.
6267 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6268 EltStride == NumElems/2)
6271 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6280 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6281 // to create 256-bit vectors from two other 128-bit ones.
6282 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6284 MVT ResVT = Op.getSimpleValueType();
6286 assert((ResVT.is256BitVector() ||
6287 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6289 SDValue V1 = Op.getOperand(0);
6290 SDValue V2 = Op.getOperand(1);
6291 unsigned NumElems = ResVT.getVectorNumElements();
6292 if(ResVT.is256BitVector())
6293 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6295 if (Op.getNumOperands() == 4) {
6296 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6297 ResVT.getVectorNumElements()/2);
6298 SDValue V3 = Op.getOperand(2);
6299 SDValue V4 = Op.getOperand(3);
6300 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6301 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6303 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6306 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6307 MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6308 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6309 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6310 Op.getNumOperands() == 4)));
6312 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6313 // from two other 128-bit ones.
6315 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6316 return LowerAVXCONCAT_VECTORS(Op, DAG);
6319 // Try to lower a shuffle node into a simple blend instruction.
6321 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6322 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6323 SDValue V1 = SVOp->getOperand(0);
6324 SDValue V2 = SVOp->getOperand(1);
6326 MVT VT = SVOp->getSimpleValueType(0);
6327 MVT EltVT = VT.getVectorElementType();
6328 unsigned NumElems = VT.getVectorNumElements();
6330 // There is no blend with immediate in AVX-512.
6331 if (VT.is512BitVector())
6334 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
6336 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
6339 // Check the mask for BLEND and build the value.
6340 unsigned MaskValue = 0;
6341 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6342 unsigned NumLanes = (NumElems-1)/8 + 1;
6343 unsigned NumElemsInLane = NumElems / NumLanes;
6345 // Blend for v16i16 should be symetric for the both lanes.
6346 for (unsigned i = 0; i < NumElemsInLane; ++i) {
6348 int SndLaneEltIdx = (NumLanes == 2) ?
6349 SVOp->getMaskElt(i + NumElemsInLane) : -1;
6350 int EltIdx = SVOp->getMaskElt(i);
6352 if ((EltIdx < 0 || EltIdx == (int)i) &&
6353 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6356 if (((unsigned)EltIdx == (i + NumElems)) &&
6357 (SndLaneEltIdx < 0 ||
6358 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6359 MaskValue |= (1<<i);
6364 // Convert i32 vectors to floating point if it is not AVX2.
6365 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6367 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6368 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6370 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6371 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6374 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6375 DAG.getConstant(MaskValue, MVT::i32));
6376 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6379 /// In vector type \p VT, return true if the element at index \p InputIdx
6380 /// falls on a different 128-bit lane than \p OutputIdx.
6381 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
6382 unsigned OutputIdx) {
6383 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6384 return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
6387 /// Generate a PSHUFB if possible. Selects elements from \p V1 according to
6388 /// \p MaskVals. MaskVals[OutputIdx] = InputIdx specifies that we want to
6389 /// shuffle the element at InputIdx in V1 to OutputIdx in the result. If \p
6390 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
6392 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
6393 SelectionDAG &DAG) {
6394 MVT VT = V1.getSimpleValueType();
6395 assert(VT.is128BitVector() || VT.is256BitVector());
6397 MVT EltVT = VT.getVectorElementType();
6398 unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
6399 unsigned NumElts = VT.getVectorNumElements();
6401 SmallVector<SDValue, 32> PshufbMask;
6402 for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
6403 int InputIdx = MaskVals[OutputIdx];
6404 unsigned InputByteIdx;
6406 if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
6407 InputByteIdx = 0x80;
6409 // Cross lane is not allowed.
6410 if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
6412 InputByteIdx = InputIdx * EltSizeInBytes;
6413 // Index is an byte offset within the 128-bit lane.
6414 InputByteIdx &= 0xf;
6417 for (unsigned j = 0; j < EltSizeInBytes; ++j) {
6418 PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
6419 if (InputByteIdx != 0x80)
6424 MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
6426 V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
6427 return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
6428 DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
6431 // v8i16 shuffles - Prefer shuffles in the following order:
6432 // 1. [all] pshuflw, pshufhw, optional move
6433 // 2. [ssse3] 1 x pshufb
6434 // 3. [ssse3] 2 x pshufb + 1 x por
6435 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6437 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6438 SelectionDAG &DAG) {
6439 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6440 SDValue V1 = SVOp->getOperand(0);
6441 SDValue V2 = SVOp->getOperand(1);
6443 SmallVector<int, 8> MaskVals;
6445 // Determine if more than 1 of the words in each of the low and high quadwords
6446 // of the result come from the same quadword of one of the two inputs. Undef
6447 // mask values count as coming from any quadword, for better codegen.
6449 // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
6450 // feeds this quad. For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
6451 unsigned LoQuad[] = { 0, 0, 0, 0 };
6452 unsigned HiQuad[] = { 0, 0, 0, 0 };
6453 // Indices of quads used.
6454 std::bitset<4> InputQuads;
6455 for (unsigned i = 0; i < 8; ++i) {
6456 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6457 int EltIdx = SVOp->getMaskElt(i);
6458 MaskVals.push_back(EltIdx);
6467 InputQuads.set(EltIdx / 4);
6470 int BestLoQuad = -1;
6471 unsigned MaxQuad = 1;
6472 for (unsigned i = 0; i < 4; ++i) {
6473 if (LoQuad[i] > MaxQuad) {
6475 MaxQuad = LoQuad[i];
6479 int BestHiQuad = -1;
6481 for (unsigned i = 0; i < 4; ++i) {
6482 if (HiQuad[i] > MaxQuad) {
6484 MaxQuad = HiQuad[i];
6488 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6489 // of the two input vectors, shuffle them into one input vector so only a
6490 // single pshufb instruction is necessary. If there are more than 2 input
6491 // quads, disable the next transformation since it does not help SSSE3.
6492 bool V1Used = InputQuads[0] || InputQuads[1];
6493 bool V2Used = InputQuads[2] || InputQuads[3];
6494 if (Subtarget->hasSSSE3()) {
6495 if (InputQuads.count() == 2 && V1Used && V2Used) {
6496 BestLoQuad = InputQuads[0] ? 0 : 1;
6497 BestHiQuad = InputQuads[2] ? 2 : 3;
6499 if (InputQuads.count() > 2) {
6505 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6506 // the shuffle mask. If a quad is scored as -1, that means that it contains
6507 // words from all 4 input quadwords.
6509 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6511 BestLoQuad < 0 ? 0 : BestLoQuad,
6512 BestHiQuad < 0 ? 1 : BestHiQuad
6514 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6515 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6516 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6517 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6519 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6520 // source words for the shuffle, to aid later transformations.
6521 bool AllWordsInNewV = true;
6522 bool InOrder[2] = { true, true };
6523 for (unsigned i = 0; i != 8; ++i) {
6524 int idx = MaskVals[i];
6526 InOrder[i/4] = false;
6527 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6529 AllWordsInNewV = false;
6533 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6534 if (AllWordsInNewV) {
6535 for (int i = 0; i != 8; ++i) {
6536 int idx = MaskVals[i];
6539 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6540 if ((idx != i) && idx < 4)
6542 if ((idx != i) && idx > 3)
6551 // If we've eliminated the use of V2, and the new mask is a pshuflw or
6552 // pshufhw, that's as cheap as it gets. Return the new shuffle.
6553 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6554 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6555 unsigned TargetMask = 0;
6556 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6557 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6558 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6559 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6560 getShufflePSHUFLWImmediate(SVOp);
6561 V1 = NewV.getOperand(0);
6562 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6566 // Promote splats to a larger type which usually leads to more efficient code.
6567 // FIXME: Is this true if pshufb is available?
6568 if (SVOp->isSplat())
6569 return PromoteSplat(SVOp, DAG);
6571 // If we have SSSE3, and all words of the result are from 1 input vector,
6572 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
6573 // is present, fall back to case 4.
6574 if (Subtarget->hasSSSE3()) {
6575 SmallVector<SDValue,16> pshufbMask;
6577 // If we have elements from both input vectors, set the high bit of the
6578 // shuffle mask element to zero out elements that come from V2 in the V1
6579 // mask, and elements that come from V1 in the V2 mask, so that the two
6580 // results can be OR'd together.
6581 bool TwoInputs = V1Used && V2Used;
6582 V1 = getPSHUFB(MaskVals, V1, dl, DAG);
6584 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6586 // Calculate the shuffle mask for the second input, shuffle it, and
6587 // OR it with the first shuffled input.
6588 CommuteVectorShuffleMask(MaskVals, 8);
6589 V2 = getPSHUFB(MaskVals, V2, dl, DAG);
6590 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6591 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6594 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6595 // and update MaskVals with new element order.
6596 std::bitset<8> InOrder;
6597 if (BestLoQuad >= 0) {
6598 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6599 for (int i = 0; i != 4; ++i) {
6600 int idx = MaskVals[i];
6603 } else if ((idx / 4) == BestLoQuad) {
6608 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6611 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6612 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6613 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6615 getShufflePSHUFLWImmediate(SVOp), DAG);
6619 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6620 // and update MaskVals with the new element order.
6621 if (BestHiQuad >= 0) {
6622 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6623 for (unsigned i = 4; i != 8; ++i) {
6624 int idx = MaskVals[i];
6627 } else if ((idx / 4) == BestHiQuad) {
6628 MaskV[i] = (idx & 3) + 4;
6632 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6635 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6636 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6637 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6639 getShufflePSHUFHWImmediate(SVOp), DAG);
6643 // In case BestHi & BestLo were both -1, which means each quadword has a word
6644 // from each of the four input quadwords, calculate the InOrder bitvector now
6645 // before falling through to the insert/extract cleanup.
6646 if (BestLoQuad == -1 && BestHiQuad == -1) {
6648 for (int i = 0; i != 8; ++i)
6649 if (MaskVals[i] < 0 || MaskVals[i] == i)
6653 // The other elements are put in the right place using pextrw and pinsrw.
6654 for (unsigned i = 0; i != 8; ++i) {
6657 int EltIdx = MaskVals[i];
6660 SDValue ExtOp = (EltIdx < 8) ?
6661 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6662 DAG.getIntPtrConstant(EltIdx)) :
6663 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6664 DAG.getIntPtrConstant(EltIdx - 8));
6665 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6666 DAG.getIntPtrConstant(i));
6671 /// \brief v16i16 shuffles
6673 /// FIXME: We only support generation of a single pshufb currently. We can
6674 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
6675 /// well (e.g 2 x pshufb + 1 x por).
6677 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
6678 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6679 SDValue V1 = SVOp->getOperand(0);
6680 SDValue V2 = SVOp->getOperand(1);
6683 if (V2.getOpcode() != ISD::UNDEF)
6686 SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6687 return getPSHUFB(MaskVals, V1, dl, DAG);
6690 // v16i8 shuffles - Prefer shuffles in the following order:
6691 // 1. [ssse3] 1 x pshufb
6692 // 2. [ssse3] 2 x pshufb + 1 x por
6693 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
6694 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6695 const X86Subtarget* Subtarget,
6696 SelectionDAG &DAG) {
6697 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6698 SDValue V1 = SVOp->getOperand(0);
6699 SDValue V2 = SVOp->getOperand(1);
6701 ArrayRef<int> MaskVals = SVOp->getMask();
6703 // Promote splats to a larger type which usually leads to more efficient code.
6704 // FIXME: Is this true if pshufb is available?
6705 if (SVOp->isSplat())
6706 return PromoteSplat(SVOp, DAG);
6708 // If we have SSSE3, case 1 is generated when all result bytes come from
6709 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
6710 // present, fall back to case 3.
6712 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6713 if (Subtarget->hasSSSE3()) {
6714 SmallVector<SDValue,16> pshufbMask;
6716 // If all result elements are from one input vector, then only translate
6717 // undef mask values to 0x80 (zero out result) in the pshufb mask.
6719 // Otherwise, we have elements from both input vectors, and must zero out
6720 // elements that come from V2 in the first mask, and V1 in the second mask
6721 // so that we can OR them together.
6722 for (unsigned i = 0; i != 16; ++i) {
6723 int EltIdx = MaskVals[i];
6724 if (EltIdx < 0 || EltIdx >= 16)
6726 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6728 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6729 DAG.getNode(ISD::BUILD_VECTOR, dl,
6730 MVT::v16i8, pshufbMask));
6732 // As PSHUFB will zero elements with negative indices, it's safe to ignore
6733 // the 2nd operand if it's undefined or zero.
6734 if (V2.getOpcode() == ISD::UNDEF ||
6735 ISD::isBuildVectorAllZeros(V2.getNode()))
6738 // Calculate the shuffle mask for the second input, shuffle it, and
6739 // OR it with the first shuffled input.
6741 for (unsigned i = 0; i != 16; ++i) {
6742 int EltIdx = MaskVals[i];
6743 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6744 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6746 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6747 DAG.getNode(ISD::BUILD_VECTOR, dl,
6748 MVT::v16i8, pshufbMask));
6749 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6752 // No SSSE3 - Calculate in place words and then fix all out of place words
6753 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
6754 // the 16 different words that comprise the two doublequadword input vectors.
6755 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6756 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6758 for (int i = 0; i != 8; ++i) {
6759 int Elt0 = MaskVals[i*2];
6760 int Elt1 = MaskVals[i*2+1];
6762 // This word of the result is all undef, skip it.
6763 if (Elt0 < 0 && Elt1 < 0)
6766 // This word of the result is already in the correct place, skip it.
6767 if ((Elt0 == i*2) && (Elt1 == i*2+1))
6770 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6771 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6774 // If Elt0 and Elt1 are defined, are consecutive, and can be load
6775 // using a single extract together, load it and store it.
6776 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6777 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6778 DAG.getIntPtrConstant(Elt1 / 2));
6779 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6780 DAG.getIntPtrConstant(i));
6784 // If Elt1 is defined, extract it from the appropriate source. If the
6785 // source byte is not also odd, shift the extracted word left 8 bits
6786 // otherwise clear the bottom 8 bits if we need to do an or.
6788 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6789 DAG.getIntPtrConstant(Elt1 / 2));
6790 if ((Elt1 & 1) == 0)
6791 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6793 TLI.getShiftAmountTy(InsElt.getValueType())));
6795 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6796 DAG.getConstant(0xFF00, MVT::i16));
6798 // If Elt0 is defined, extract it from the appropriate source. If the
6799 // source byte is not also even, shift the extracted word right 8 bits. If
6800 // Elt1 was also defined, OR the extracted values together before
6801 // inserting them in the result.
6803 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6804 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6805 if ((Elt0 & 1) != 0)
6806 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6808 TLI.getShiftAmountTy(InsElt0.getValueType())));
6810 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6811 DAG.getConstant(0x00FF, MVT::i16));
6812 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6815 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6816 DAG.getIntPtrConstant(i));
6818 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6821 // v32i8 shuffles - Translate to VPSHUFB if possible.
6823 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6824 const X86Subtarget *Subtarget,
6825 SelectionDAG &DAG) {
6826 MVT VT = SVOp->getSimpleValueType(0);
6827 SDValue V1 = SVOp->getOperand(0);
6828 SDValue V2 = SVOp->getOperand(1);
6830 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6832 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6833 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6834 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6836 // VPSHUFB may be generated if
6837 // (1) one of input vector is undefined or zeroinitializer.
6838 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6839 // And (2) the mask indexes don't cross the 128-bit lane.
6840 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6841 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6844 if (V1IsAllZero && !V2IsAllZero) {
6845 CommuteVectorShuffleMask(MaskVals, 32);
6848 return getPSHUFB(MaskVals, V1, dl, DAG);
6851 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6852 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6853 /// done when every pair / quad of shuffle mask elements point to elements in
6854 /// the right sequence. e.g.
6855 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6857 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6858 SelectionDAG &DAG) {
6859 MVT VT = SVOp->getSimpleValueType(0);
6861 unsigned NumElems = VT.getVectorNumElements();
6864 switch (VT.SimpleTy) {
6865 default: llvm_unreachable("Unexpected!");
6866 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
6867 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
6868 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
6869 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
6870 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6871 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
6874 SmallVector<int, 8> MaskVec;
6875 for (unsigned i = 0; i != NumElems; i += Scale) {
6877 for (unsigned j = 0; j != Scale; ++j) {
6878 int EltIdx = SVOp->getMaskElt(i+j);
6882 StartIdx = (EltIdx / Scale);
6883 if (EltIdx != (int)(StartIdx*Scale + j))
6886 MaskVec.push_back(StartIdx);
6889 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6890 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6891 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6894 /// getVZextMovL - Return a zero-extending vector move low node.
6896 static SDValue getVZextMovL(MVT VT, MVT OpVT,
6897 SDValue SrcOp, SelectionDAG &DAG,
6898 const X86Subtarget *Subtarget, SDLoc dl) {
6899 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6900 LoadSDNode *LD = nullptr;
6901 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6902 LD = dyn_cast<LoadSDNode>(SrcOp);
6904 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6906 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6907 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6908 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6909 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6910 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6912 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6913 return DAG.getNode(ISD::BITCAST, dl, VT,
6914 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6915 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6923 return DAG.getNode(ISD::BITCAST, dl, VT,
6924 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6925 DAG.getNode(ISD::BITCAST, dl,
6929 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6930 /// which could not be matched by any known target speficic shuffle
6932 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6934 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6935 if (NewOp.getNode())
6938 MVT VT = SVOp->getSimpleValueType(0);
6940 unsigned NumElems = VT.getVectorNumElements();
6941 unsigned NumLaneElems = NumElems / 2;
6944 MVT EltVT = VT.getVectorElementType();
6945 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6948 SmallVector<int, 16> Mask;
6949 for (unsigned l = 0; l < 2; ++l) {
6950 // Build a shuffle mask for the output, discovering on the fly which
6951 // input vectors to use as shuffle operands (recorded in InputUsed).
6952 // If building a suitable shuffle vector proves too hard, then bail
6953 // out with UseBuildVector set.
6954 bool UseBuildVector = false;
6955 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6956 unsigned LaneStart = l * NumLaneElems;
6957 for (unsigned i = 0; i != NumLaneElems; ++i) {
6958 // The mask element. This indexes into the input.
6959 int Idx = SVOp->getMaskElt(i+LaneStart);
6961 // the mask element does not index into any input vector.
6966 // The input vector this mask element indexes into.
6967 int Input = Idx / NumLaneElems;
6969 // Turn the index into an offset from the start of the input vector.
6970 Idx -= Input * NumLaneElems;
6972 // Find or create a shuffle vector operand to hold this input.
6974 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6975 if (InputUsed[OpNo] == Input)
6976 // This input vector is already an operand.
6978 if (InputUsed[OpNo] < 0) {
6979 // Create a new operand for this input vector.
6980 InputUsed[OpNo] = Input;
6985 if (OpNo >= array_lengthof(InputUsed)) {
6986 // More than two input vectors used! Give up on trying to create a
6987 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
6988 UseBuildVector = true;
6992 // Add the mask index for the new shuffle vector.
6993 Mask.push_back(Idx + OpNo * NumLaneElems);
6996 if (UseBuildVector) {
6997 SmallVector<SDValue, 16> SVOps;
6998 for (unsigned i = 0; i != NumLaneElems; ++i) {
6999 // The mask element. This indexes into the input.
7000 int Idx = SVOp->getMaskElt(i+LaneStart);
7002 SVOps.push_back(DAG.getUNDEF(EltVT));
7006 // The input vector this mask element indexes into.
7007 int Input = Idx / NumElems;
7009 // Turn the index into an offset from the start of the input vector.
7010 Idx -= Input * NumElems;
7012 // Extract the vector element by hand.
7013 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
7014 SVOp->getOperand(Input),
7015 DAG.getIntPtrConstant(Idx)));
7018 // Construct the output using a BUILD_VECTOR.
7019 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
7020 } else if (InputUsed[0] < 0) {
7021 // No input vectors were used! The result is undefined.
7022 Output[l] = DAG.getUNDEF(NVT);
7024 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
7025 (InputUsed[0] % 2) * NumLaneElems,
7027 // If only one input was used, use an undefined vector for the other.
7028 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
7029 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
7030 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
7031 // At least one input vector was used. Create a new shuffle vector.
7032 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
7038 // Concatenate the result back
7039 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
7042 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
7043 /// 4 elements, and match them with several different shuffle types.
7045 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7046 SDValue V1 = SVOp->getOperand(0);
7047 SDValue V2 = SVOp->getOperand(1);
7049 MVT VT = SVOp->getSimpleValueType(0);
7051 assert(VT.is128BitVector() && "Unsupported vector size");
7053 std::pair<int, int> Locs[4];
7054 int Mask1[] = { -1, -1, -1, -1 };
7055 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
7059 for (unsigned i = 0; i != 4; ++i) {
7060 int Idx = PermMask[i];
7062 Locs[i] = std::make_pair(-1, -1);
7064 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
7066 Locs[i] = std::make_pair(0, NumLo);
7070 Locs[i] = std::make_pair(1, NumHi);
7072 Mask1[2+NumHi] = Idx;
7078 if (NumLo <= 2 && NumHi <= 2) {
7079 // If no more than two elements come from either vector. This can be
7080 // implemented with two shuffles. First shuffle gather the elements.
7081 // The second shuffle, which takes the first shuffle as both of its
7082 // vector operands, put the elements into the right order.
7083 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7085 int Mask2[] = { -1, -1, -1, -1 };
7087 for (unsigned i = 0; i != 4; ++i)
7088 if (Locs[i].first != -1) {
7089 unsigned Idx = (i < 2) ? 0 : 4;
7090 Idx += Locs[i].first * 2 + Locs[i].second;
7094 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
7097 if (NumLo == 3 || NumHi == 3) {
7098 // Otherwise, we must have three elements from one vector, call it X, and
7099 // one element from the other, call it Y. First, use a shufps to build an
7100 // intermediate vector with the one element from Y and the element from X
7101 // that will be in the same half in the final destination (the indexes don't
7102 // matter). Then, use a shufps to build the final vector, taking the half
7103 // containing the element from Y from the intermediate, and the other half
7106 // Normalize it so the 3 elements come from V1.
7107 CommuteVectorShuffleMask(PermMask, 4);
7111 // Find the element from V2.
7113 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
7114 int Val = PermMask[HiIndex];
7121 Mask1[0] = PermMask[HiIndex];
7123 Mask1[2] = PermMask[HiIndex^1];
7125 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7128 Mask1[0] = PermMask[0];
7129 Mask1[1] = PermMask[1];
7130 Mask1[2] = HiIndex & 1 ? 6 : 4;
7131 Mask1[3] = HiIndex & 1 ? 4 : 6;
7132 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7135 Mask1[0] = HiIndex & 1 ? 2 : 0;
7136 Mask1[1] = HiIndex & 1 ? 0 : 2;
7137 Mask1[2] = PermMask[2];
7138 Mask1[3] = PermMask[3];
7143 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7146 // Break it into (shuffle shuffle_hi, shuffle_lo).
7147 int LoMask[] = { -1, -1, -1, -1 };
7148 int HiMask[] = { -1, -1, -1, -1 };
7150 int *MaskPtr = LoMask;
7151 unsigned MaskIdx = 0;
7154 for (unsigned i = 0; i != 4; ++i) {
7161 int Idx = PermMask[i];
7163 Locs[i] = std::make_pair(-1, -1);
7164 } else if (Idx < 4) {
7165 Locs[i] = std::make_pair(MaskIdx, LoIdx);
7166 MaskPtr[LoIdx] = Idx;
7169 Locs[i] = std::make_pair(MaskIdx, HiIdx);
7170 MaskPtr[HiIdx] = Idx;
7175 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7176 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7177 int MaskOps[] = { -1, -1, -1, -1 };
7178 for (unsigned i = 0; i != 4; ++i)
7179 if (Locs[i].first != -1)
7180 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7181 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7184 static bool MayFoldVectorLoad(SDValue V) {
7185 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7186 V = V.getOperand(0);
7188 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7189 V = V.getOperand(0);
7190 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7191 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7192 // BUILD_VECTOR (load), undef
7193 V = V.getOperand(0);
7195 return MayFoldLoad(V);
7199 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7200 MVT VT = Op.getSimpleValueType();
7202 // Canonizalize to v2f64.
7203 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7204 return DAG.getNode(ISD::BITCAST, dl, VT,
7205 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7210 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7212 SDValue V1 = Op.getOperand(0);
7213 SDValue V2 = Op.getOperand(1);
7214 MVT VT = Op.getSimpleValueType();
7216 assert(VT != MVT::v2i64 && "unsupported shuffle type");
7218 if (HasSSE2 && VT == MVT::v2f64)
7219 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7221 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7222 return DAG.getNode(ISD::BITCAST, dl, VT,
7223 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7224 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7225 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7229 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7230 SDValue V1 = Op.getOperand(0);
7231 SDValue V2 = Op.getOperand(1);
7232 MVT VT = Op.getSimpleValueType();
7234 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7235 "unsupported shuffle type");
7237 if (V2.getOpcode() == ISD::UNDEF)
7241 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7245 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7246 SDValue V1 = Op.getOperand(0);
7247 SDValue V2 = Op.getOperand(1);
7248 MVT VT = Op.getSimpleValueType();
7249 unsigned NumElems = VT.getVectorNumElements();
7251 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7252 // operand of these instructions is only memory, so check if there's a
7253 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7255 bool CanFoldLoad = false;
7257 // Trivial case, when V2 comes from a load.
7258 if (MayFoldVectorLoad(V2))
7261 // When V1 is a load, it can be folded later into a store in isel, example:
7262 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7264 // (MOVLPSmr addr:$src1, VR128:$src2)
7265 // So, recognize this potential and also use MOVLPS or MOVLPD
7266 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7269 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7271 if (HasSSE2 && NumElems == 2)
7272 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7275 // If we don't care about the second element, proceed to use movss.
7276 if (SVOp->getMaskElt(1) != -1)
7277 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7280 // movl and movlp will both match v2i64, but v2i64 is never matched by
7281 // movl earlier because we make it strict to avoid messing with the movlp load
7282 // folding logic (see the code above getMOVLP call). Match it here then,
7283 // this is horrible, but will stay like this until we move all shuffle
7284 // matching to x86 specific nodes. Note that for the 1st condition all
7285 // types are matched with movsd.
7287 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7288 // as to remove this logic from here, as much as possible
7289 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7290 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7291 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7294 assert(VT != MVT::v4i32 && "unsupported shuffle type");
7296 // Invert the operand order and use SHUFPS to match it.
7297 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7298 getShuffleSHUFImmediate(SVOp), DAG);
7301 // It is only safe to call this function if isINSERTPSMask is true for
7302 // this shufflevector mask.
7303 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
7304 SelectionDAG &DAG) {
7305 // Generate an insertps instruction when inserting an f32 from memory onto a
7306 // v4f32 or when copying a member from one v4f32 to another.
7307 // We also use it for transferring i32 from one register to another,
7308 // since it simply copies the same bits.
7309 // If we're transfering an i32 from memory to a specific element in a
7310 // register, we output a generic DAG that will match the PINSRD
7312 // TODO: Optimize for AVX cases too (VINSERTPS)
7313 MVT VT = SVOp->getSimpleValueType(0);
7314 MVT EVT = VT.getVectorElementType();
7315 SDValue V1 = SVOp->getOperand(0);
7316 SDValue V2 = SVOp->getOperand(1);
7317 auto Mask = SVOp->getMask();
7318 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
7319 "unsupported vector type for insertps/pinsrd");
7321 int FromV1 = std::count_if(Mask.begin(), Mask.end(),
7322 [](const int &i) { return i < 4; });
7330 DestIndex = std::find_if(Mask.begin(), Mask.end(),
7331 [](const int &i) { return i < 4; }) -
7336 DestIndex = std::find_if(Mask.begin(), Mask.end(),
7337 [](const int &i) { return i >= 4; }) -
7341 if (MayFoldLoad(From)) {
7342 // Trivial case, when From comes from a load and is only used by the
7343 // shuffle. Make it use insertps from the vector that we need from that
7345 SDValue Addr = From.getOperand(1);
7347 DAG.getNode(ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
7348 DAG.getConstant(DestIndex * EVT.getStoreSize(),
7349 Addr.getSimpleValueType()));
7351 LoadSDNode *Load = cast<LoadSDNode>(From);
7353 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
7354 DAG.getMachineFunction().getMachineMemOperand(
7355 Load->getMemOperand(), 0, EVT.getStoreSize()));
7357 if (EVT == MVT::f32) {
7358 // Create this as a scalar to vector to match the instruction pattern.
7359 SDValue LoadScalarToVector =
7360 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
7361 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
7362 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
7364 } else { // EVT == MVT::i32
7365 // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
7366 // instruction, to match the PINSRD instruction, which loads an i32 to a
7367 // certain vector element.
7368 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
7369 DAG.getConstant(DestIndex, MVT::i32));
7373 // Vector-element-to-vector
7374 unsigned SrcIndex = Mask[DestIndex] % 4;
7375 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
7376 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
7379 // Reduce a vector shuffle to zext.
7380 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7381 SelectionDAG &DAG) {
7382 // PMOVZX is only available from SSE41.
7383 if (!Subtarget->hasSSE41())
7386 MVT VT = Op.getSimpleValueType();
7388 // Only AVX2 support 256-bit vector integer extending.
7389 if (!Subtarget->hasInt256() && VT.is256BitVector())
7392 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7394 SDValue V1 = Op.getOperand(0);
7395 SDValue V2 = Op.getOperand(1);
7396 unsigned NumElems = VT.getVectorNumElements();
7398 // Extending is an unary operation and the element type of the source vector
7399 // won't be equal to or larger than i64.
7400 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7401 VT.getVectorElementType() == MVT::i64)
7404 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7405 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7406 while ((1U << Shift) < NumElems) {
7407 if (SVOp->getMaskElt(1U << Shift) == 1)
7410 // The maximal ratio is 8, i.e. from i8 to i64.
7415 // Check the shuffle mask.
7416 unsigned Mask = (1U << Shift) - 1;
7417 for (unsigned i = 0; i != NumElems; ++i) {
7418 int EltIdx = SVOp->getMaskElt(i);
7419 if ((i & Mask) != 0 && EltIdx != -1)
7421 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7425 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7426 MVT NeVT = MVT::getIntegerVT(NBits);
7427 MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7429 if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7432 // Simplify the operand as it's prepared to be fed into shuffle.
7433 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7434 if (V1.getOpcode() == ISD::BITCAST &&
7435 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7436 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7437 V1.getOperand(0).getOperand(0)
7438 .getSimpleValueType().getSizeInBits() == SignificantBits) {
7439 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7440 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7441 ConstantSDNode *CIdx =
7442 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7443 // If it's foldable, i.e. normal load with single use, we will let code
7444 // selection to fold it. Otherwise, we will short the conversion sequence.
7445 if (CIdx && CIdx->getZExtValue() == 0 &&
7446 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7447 MVT FullVT = V.getSimpleValueType();
7448 MVT V1VT = V1.getSimpleValueType();
7449 if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7450 // The "ext_vec_elt" node is wider than the result node.
7451 // In this case we should extract subvector from V.
7452 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7453 unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7454 MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7455 FullVT.getVectorNumElements()/Ratio);
7456 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7457 DAG.getIntPtrConstant(0));
7459 V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7463 return DAG.getNode(ISD::BITCAST, DL, VT,
7464 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7468 NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7469 SelectionDAG &DAG) {
7470 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7471 MVT VT = Op.getSimpleValueType();
7473 SDValue V1 = Op.getOperand(0);
7474 SDValue V2 = Op.getOperand(1);
7476 if (isZeroShuffle(SVOp))
7477 return getZeroVector(VT, Subtarget, DAG, dl);
7479 // Handle splat operations
7480 if (SVOp->isSplat()) {
7481 // Use vbroadcast whenever the splat comes from a foldable load
7482 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7483 if (Broadcast.getNode())
7487 // Check integer expanding shuffles.
7488 SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7489 if (NewOp.getNode())
7492 // If the shuffle can be profitably rewritten as a narrower shuffle, then
7494 if (VT == MVT::v8i16 || VT == MVT::v16i8 ||
7495 VT == MVT::v16i16 || VT == MVT::v32i8) {
7496 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7497 if (NewOp.getNode())
7498 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7499 } else if ((VT == MVT::v4i32 ||
7500 (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
7501 // FIXME: Figure out a cleaner way to do this.
7502 // Try to make use of movq to zero out the top part.
7503 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7504 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7505 if (NewOp.getNode()) {
7506 MVT NewVT = NewOp.getSimpleValueType();
7507 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7508 NewVT, true, false))
7509 return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
7510 DAG, Subtarget, dl);
7512 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7513 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7514 if (NewOp.getNode()) {
7515 MVT NewVT = NewOp.getSimpleValueType();
7516 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7517 return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
7518 DAG, Subtarget, dl);
7526 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7527 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7528 SDValue V1 = Op.getOperand(0);
7529 SDValue V2 = Op.getOperand(1);
7530 MVT VT = Op.getSimpleValueType();
7532 unsigned NumElems = VT.getVectorNumElements();
7533 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7534 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7535 bool V1IsSplat = false;
7536 bool V2IsSplat = false;
7537 bool HasSSE2 = Subtarget->hasSSE2();
7538 bool HasFp256 = Subtarget->hasFp256();
7539 bool HasInt256 = Subtarget->hasInt256();
7540 MachineFunction &MF = DAG.getMachineFunction();
7541 bool OptForSize = MF.getFunction()->getAttributes().
7542 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7544 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7546 if (V1IsUndef && V2IsUndef)
7547 return DAG.getUNDEF(VT);
7549 // When we create a shuffle node we put the UNDEF node to second operand,
7550 // but in some cases the first operand may be transformed to UNDEF.
7551 // In this case we should just commute the node.
7553 return CommuteVectorShuffle(SVOp, DAG);
7555 // Vector shuffle lowering takes 3 steps:
7557 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7558 // narrowing and commutation of operands should be handled.
7559 // 2) Matching of shuffles with known shuffle masks to x86 target specific
7561 // 3) Rewriting of unmatched masks into new generic shuffle operations,
7562 // so the shuffle can be broken into other shuffles and the legalizer can
7563 // try the lowering again.
7565 // The general idea is that no vector_shuffle operation should be left to
7566 // be matched during isel, all of them must be converted to a target specific
7569 // Normalize the input vectors. Here splats, zeroed vectors, profitable
7570 // narrowing and commutation of operands should be handled. The actual code
7571 // doesn't include all of those, work in progress...
7572 SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7573 if (NewOp.getNode())
7576 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7578 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7579 // unpckh_undef). Only use pshufd if speed is more important than size.
7580 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7581 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7582 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7583 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7585 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7586 V2IsUndef && MayFoldVectorLoad(V1))
7587 return getMOVDDup(Op, dl, V1, DAG);
7589 if (isMOVHLPS_v_undef_Mask(M, VT))
7590 return getMOVHighToLow(Op, dl, DAG);
7592 // Use to match splats
7593 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7594 (VT == MVT::v2f64 || VT == MVT::v2i64))
7595 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7597 if (isPSHUFDMask(M, VT)) {
7598 // The actual implementation will match the mask in the if above and then
7599 // during isel it can match several different instructions, not only pshufd
7600 // as its name says, sad but true, emulate the behavior for now...
7601 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7602 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7604 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7606 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7607 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7609 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7610 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7613 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7617 if (isPALIGNRMask(M, VT, Subtarget))
7618 return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7619 getShufflePALIGNRImmediate(SVOp),
7622 // Check if this can be converted into a logical shift.
7623 bool isLeft = false;
7626 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7627 if (isShift && ShVal.hasOneUse()) {
7628 // If the shifted value has multiple uses, it may be cheaper to use
7629 // v_set0 + movlhps or movhlps, etc.
7630 MVT EltVT = VT.getVectorElementType();
7631 ShAmt *= EltVT.getSizeInBits();
7632 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7635 if (isMOVLMask(M, VT)) {
7636 if (ISD::isBuildVectorAllZeros(V1.getNode()))
7637 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7638 if (!isMOVLPMask(M, VT)) {
7639 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7640 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7642 if (VT == MVT::v4i32 || VT == MVT::v4f32)
7643 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7647 // FIXME: fold these into legal mask.
7648 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7649 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7651 if (isMOVHLPSMask(M, VT))
7652 return getMOVHighToLow(Op, dl, DAG);
7654 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7655 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7657 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7658 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7660 if (isMOVLPMask(M, VT))
7661 return getMOVLP(Op, dl, DAG, HasSSE2);
7663 if (ShouldXformToMOVHLPS(M, VT) ||
7664 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7665 return CommuteVectorShuffle(SVOp, DAG);
7668 // No better options. Use a vshldq / vsrldq.
7669 MVT EltVT = VT.getVectorElementType();
7670 ShAmt *= EltVT.getSizeInBits();
7671 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7674 bool Commuted = false;
7675 // FIXME: This should also accept a bitcast of a splat? Be careful, not
7676 // 1,1,1,1 -> v8i16 though.
7677 V1IsSplat = isSplatVector(V1.getNode());
7678 V2IsSplat = isSplatVector(V2.getNode());
7680 // Canonicalize the splat or undef, if present, to be on the RHS.
7681 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7682 CommuteVectorShuffleMask(M, NumElems);
7684 std::swap(V1IsSplat, V2IsSplat);
7688 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7689 // Shuffling low element of v1 into undef, just return v1.
7692 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7693 // the instruction selector will not match, so get a canonical MOVL with
7694 // swapped operands to undo the commute.
7695 return getMOVL(DAG, dl, VT, V2, V1);
7698 if (isUNPCKLMask(M, VT, HasInt256))
7699 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7701 if (isUNPCKHMask(M, VT, HasInt256))
7702 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7705 // Normalize mask so all entries that point to V2 points to its first
7706 // element then try to match unpck{h|l} again. If match, return a
7707 // new vector_shuffle with the corrected mask.p
7708 SmallVector<int, 8> NewMask(M.begin(), M.end());
7709 NormalizeMask(NewMask, NumElems);
7710 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7711 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7712 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7713 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7717 // Commute is back and try unpck* again.
7718 // FIXME: this seems wrong.
7719 CommuteVectorShuffleMask(M, NumElems);
7721 std::swap(V1IsSplat, V2IsSplat);
7723 if (isUNPCKLMask(M, VT, HasInt256))
7724 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7726 if (isUNPCKHMask(M, VT, HasInt256))
7727 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7730 // Normalize the node to match x86 shuffle ops if needed
7731 if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
7732 return CommuteVectorShuffle(SVOp, DAG);
7734 // The checks below are all present in isShuffleMaskLegal, but they are
7735 // inlined here right now to enable us to directly emit target specific
7736 // nodes, and remove one by one until they don't return Op anymore.
7738 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7739 SVOp->getSplatIndex() == 0 && V2IsUndef) {
7740 if (VT == MVT::v2f64 || VT == MVT::v2i64)
7741 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7744 if (isPSHUFHWMask(M, VT, HasInt256))
7745 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7746 getShufflePSHUFHWImmediate(SVOp),
7749 if (isPSHUFLWMask(M, VT, HasInt256))
7750 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7751 getShufflePSHUFLWImmediate(SVOp),
7754 if (isSHUFPMask(M, VT))
7755 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7756 getShuffleSHUFImmediate(SVOp), DAG);
7758 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7759 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7760 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7761 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7763 //===--------------------------------------------------------------------===//
7764 // Generate target specific nodes for 128 or 256-bit shuffles only
7765 // supported in the AVX instruction set.
7768 // Handle VMOVDDUPY permutations
7769 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7770 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7772 // Handle VPERMILPS/D* permutations
7773 if (isVPERMILPMask(M, VT)) {
7774 if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
7775 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7776 getShuffleSHUFImmediate(SVOp), DAG);
7777 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7778 getShuffleSHUFImmediate(SVOp), DAG);
7782 if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
7783 return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
7784 Idx*(NumElems/2), DAG, dl);
7786 // Handle VPERM2F128/VPERM2I128 permutations
7787 if (isVPERM2X128Mask(M, VT, HasFp256))
7788 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7789 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7791 SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7792 if (BlendOp.getNode())
7795 if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
7796 return getINSERTPS(SVOp, dl, DAG);
7799 if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
7800 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
7802 if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
7803 VT.is512BitVector()) {
7804 MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
7805 MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
7806 SmallVector<SDValue, 16> permclMask;
7807 for (unsigned i = 0; i != NumElems; ++i) {
7808 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
7811 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
7813 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7814 return DAG.getNode(X86ISD::VPERMV, dl, VT,
7815 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7816 return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
7817 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
7820 //===--------------------------------------------------------------------===//
7821 // Since no target specific shuffle was selected for this generic one,
7822 // lower it into other known shuffles. FIXME: this isn't true yet, but
7823 // this is the plan.
7826 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7827 if (VT == MVT::v8i16) {
7828 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7829 if (NewOp.getNode())
7833 if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
7834 SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
7835 if (NewOp.getNode())
7839 if (VT == MVT::v16i8) {
7840 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
7841 if (NewOp.getNode())
7845 if (VT == MVT::v32i8) {
7846 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7847 if (NewOp.getNode())
7851 // Handle all 128-bit wide vectors with 4 elements, and match them with
7852 // several different shuffle types.
7853 if (NumElems == 4 && VT.is128BitVector())
7854 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7856 // Handle general 256-bit shuffles
7857 if (VT.is256BitVector())
7858 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7863 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7864 MVT VT = Op.getSimpleValueType();
7867 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
7870 if (VT.getSizeInBits() == 8) {
7871 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7872 Op.getOperand(0), Op.getOperand(1));
7873 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7874 DAG.getValueType(VT));
7875 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7878 if (VT.getSizeInBits() == 16) {
7879 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7880 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7882 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7883 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7884 DAG.getNode(ISD::BITCAST, dl,
7888 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7889 Op.getOperand(0), Op.getOperand(1));
7890 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7891 DAG.getValueType(VT));
7892 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7895 if (VT == MVT::f32) {
7896 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7897 // the result back to FR32 register. It's only worth matching if the
7898 // result has a single use which is a store or a bitcast to i32. And in
7899 // the case of a store, it's not worth it if the index is a constant 0,
7900 // because a MOVSSmr can be used instead, which is smaller and faster.
7901 if (!Op.hasOneUse())
7903 SDNode *User = *Op.getNode()->use_begin();
7904 if ((User->getOpcode() != ISD::STORE ||
7905 (isa<ConstantSDNode>(Op.getOperand(1)) &&
7906 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7907 (User->getOpcode() != ISD::BITCAST ||
7908 User->getValueType(0) != MVT::i32))
7910 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7911 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7914 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7917 if (VT == MVT::i32 || VT == MVT::i64) {
7918 // ExtractPS/pextrq works with constant index.
7919 if (isa<ConstantSDNode>(Op.getOperand(1)))
7925 /// Extract one bit from mask vector, like v16i1 or v8i1.
7926 /// AVX-512 feature.
7928 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
7929 SDValue Vec = Op.getOperand(0);
7931 MVT VecVT = Vec.getSimpleValueType();
7932 SDValue Idx = Op.getOperand(1);
7933 MVT EltVT = Op.getSimpleValueType();
7935 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
7937 // variable index can't be handled in mask registers,
7938 // extend vector to VR512
7939 if (!isa<ConstantSDNode>(Idx)) {
7940 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
7941 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
7942 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
7943 ExtVT.getVectorElementType(), Ext, Idx);
7944 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
7947 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7948 const TargetRegisterClass* rc = getRegClassFor(VecVT);
7949 unsigned MaxSift = rc->getSize()*8 - 1;
7950 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
7951 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
7952 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
7953 DAG.getConstant(MaxSift, MVT::i8));
7954 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
7955 DAG.getIntPtrConstant(0));
7959 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7960 SelectionDAG &DAG) const {
7962 SDValue Vec = Op.getOperand(0);
7963 MVT VecVT = Vec.getSimpleValueType();
7964 SDValue Idx = Op.getOperand(1);
7966 if (Op.getSimpleValueType() == MVT::i1)
7967 return ExtractBitFromMaskVector(Op, DAG);
7969 if (!isa<ConstantSDNode>(Idx)) {
7970 if (VecVT.is512BitVector() ||
7971 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
7972 VecVT.getVectorElementType().getSizeInBits() == 32)) {
7975 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
7976 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
7977 MaskEltVT.getSizeInBits());
7979 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
7980 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
7981 getZeroVector(MaskVT, Subtarget, DAG, dl),
7982 Idx, DAG.getConstant(0, getPointerTy()));
7983 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
7984 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
7985 Perm, DAG.getConstant(0, getPointerTy()));
7990 // If this is a 256-bit vector result, first extract the 128-bit vector and
7991 // then extract the element from the 128-bit vector.
7992 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
7994 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7995 // Get the 128-bit vector.
7996 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7997 MVT EltVT = VecVT.getVectorElementType();
7999 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
8001 //if (IdxVal >= NumElems/2)
8002 // IdxVal -= NumElems/2;
8003 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
8004 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
8005 DAG.getConstant(IdxVal, MVT::i32));
8008 assert(VecVT.is128BitVector() && "Unexpected vector length");
8010 if (Subtarget->hasSSE41()) {
8011 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
8016 MVT VT = Op.getSimpleValueType();
8017 // TODO: handle v16i8.
8018 if (VT.getSizeInBits() == 16) {
8019 SDValue Vec = Op.getOperand(0);
8020 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8022 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8023 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8024 DAG.getNode(ISD::BITCAST, dl,
8027 // Transform it so it match pextrw which produces a 32-bit result.
8028 MVT EltVT = MVT::i32;
8029 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
8030 Op.getOperand(0), Op.getOperand(1));
8031 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
8032 DAG.getValueType(VT));
8033 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8036 if (VT.getSizeInBits() == 32) {
8037 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8041 // SHUFPS the element to the lowest double word, then movss.
8042 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
8043 MVT VVT = Op.getOperand(0).getSimpleValueType();
8044 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8045 DAG.getUNDEF(VVT), Mask);
8046 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8047 DAG.getIntPtrConstant(0));
8050 if (VT.getSizeInBits() == 64) {
8051 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
8052 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
8053 // to match extract_elt for f64.
8054 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8058 // UNPCKHPD the element to the lowest double word, then movsd.
8059 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
8060 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
8061 int Mask[2] = { 1, -1 };
8062 MVT VVT = Op.getOperand(0).getSimpleValueType();
8063 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8064 DAG.getUNDEF(VVT), Mask);
8065 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8066 DAG.getIntPtrConstant(0));
8072 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8073 MVT VT = Op.getSimpleValueType();
8074 MVT EltVT = VT.getVectorElementType();
8077 SDValue N0 = Op.getOperand(0);
8078 SDValue N1 = Op.getOperand(1);
8079 SDValue N2 = Op.getOperand(2);
8081 if (!VT.is128BitVector())
8084 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
8085 isa<ConstantSDNode>(N2)) {
8087 if (VT == MVT::v8i16)
8088 Opc = X86ISD::PINSRW;
8089 else if (VT == MVT::v16i8)
8090 Opc = X86ISD::PINSRB;
8092 Opc = X86ISD::PINSRB;
8094 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
8096 if (N1.getValueType() != MVT::i32)
8097 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8098 if (N2.getValueType() != MVT::i32)
8099 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8100 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
8103 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
8104 // Bits [7:6] of the constant are the source select. This will always be
8105 // zero here. The DAG Combiner may combine an extract_elt index into these
8106 // bits. For example (insert (extract, 3), 2) could be matched by putting
8107 // the '3' into bits [7:6] of X86ISD::INSERTPS.
8108 // Bits [5:4] of the constant are the destination select. This is the
8109 // value of the incoming immediate.
8110 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
8111 // combine either bitwise AND or insert of float 0.0 to set these bits.
8112 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
8113 // Create this as a scalar to vector..
8114 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
8115 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
8118 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
8119 // PINSR* works with constant index.
8125 /// Insert one bit to mask vector, like v16i1 or v8i1.
8126 /// AVX-512 feature.
8128 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
8130 SDValue Vec = Op.getOperand(0);
8131 SDValue Elt = Op.getOperand(1);
8132 SDValue Idx = Op.getOperand(2);
8133 MVT VecVT = Vec.getSimpleValueType();
8135 if (!isa<ConstantSDNode>(Idx)) {
8136 // Non constant index. Extend source and destination,
8137 // insert element and then truncate the result.
8138 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
8139 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
8140 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
8141 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
8142 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
8143 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
8146 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8147 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
8148 if (Vec.getOpcode() == ISD::UNDEF)
8149 return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8150 DAG.getConstant(IdxVal, MVT::i8));
8151 const TargetRegisterClass* rc = getRegClassFor(VecVT);
8152 unsigned MaxSift = rc->getSize()*8 - 1;
8153 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8154 DAG.getConstant(MaxSift, MVT::i8));
8155 EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
8156 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8157 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
8160 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
8161 MVT VT = Op.getSimpleValueType();
8162 MVT EltVT = VT.getVectorElementType();
8164 if (EltVT == MVT::i1)
8165 return InsertBitToMaskVector(Op, DAG);
8168 SDValue N0 = Op.getOperand(0);
8169 SDValue N1 = Op.getOperand(1);
8170 SDValue N2 = Op.getOperand(2);
8172 // If this is a 256-bit vector result, first extract the 128-bit vector,
8173 // insert the element into the extracted half and then place it back.
8174 if (VT.is256BitVector() || VT.is512BitVector()) {
8175 if (!isa<ConstantSDNode>(N2))
8178 // Get the desired 128-bit vector half.
8179 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
8180 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
8182 // Insert the element into the desired half.
8183 unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
8184 unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
8186 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
8187 DAG.getConstant(IdxIn128, MVT::i32));
8189 // Insert the changed part back to the 256-bit vector
8190 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
8193 if (Subtarget->hasSSE41())
8194 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
8196 if (EltVT == MVT::i8)
8199 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
8200 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
8201 // as its second argument.
8202 if (N1.getValueType() != MVT::i32)
8203 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8204 if (N2.getValueType() != MVT::i32)
8205 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8206 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
8211 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
8213 MVT OpVT = Op.getSimpleValueType();
8215 // If this is a 256-bit vector result, first insert into a 128-bit
8216 // vector and then insert into the 256-bit vector.
8217 if (!OpVT.is128BitVector()) {
8218 // Insert into a 128-bit vector.
8219 unsigned SizeFactor = OpVT.getSizeInBits()/128;
8220 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
8221 OpVT.getVectorNumElements() / SizeFactor);
8223 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
8225 // Insert the 128-bit vector.
8226 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
8229 if (OpVT == MVT::v1i64 &&
8230 Op.getOperand(0).getValueType() == MVT::i64)
8231 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
8233 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
8234 assert(OpVT.is128BitVector() && "Expected an SSE type!");
8235 return DAG.getNode(ISD::BITCAST, dl, OpVT,
8236 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
8239 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
8240 // a simple subregister reference or explicit instructions to grab
8241 // upper bits of a vector.
8242 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8243 SelectionDAG &DAG) {
8245 SDValue In = Op.getOperand(0);
8246 SDValue Idx = Op.getOperand(1);
8247 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8248 MVT ResVT = Op.getSimpleValueType();
8249 MVT InVT = In.getSimpleValueType();
8251 if (Subtarget->hasFp256()) {
8252 if (ResVT.is128BitVector() &&
8253 (InVT.is256BitVector() || InVT.is512BitVector()) &&
8254 isa<ConstantSDNode>(Idx)) {
8255 return Extract128BitVector(In, IdxVal, DAG, dl);
8257 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
8258 isa<ConstantSDNode>(Idx)) {
8259 return Extract256BitVector(In, IdxVal, DAG, dl);
8265 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
8266 // simple superregister reference or explicit instructions to insert
8267 // the upper bits of a vector.
8268 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8269 SelectionDAG &DAG) {
8270 if (Subtarget->hasFp256()) {
8271 SDLoc dl(Op.getNode());
8272 SDValue Vec = Op.getNode()->getOperand(0);
8273 SDValue SubVec = Op.getNode()->getOperand(1);
8274 SDValue Idx = Op.getNode()->getOperand(2);
8276 if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8277 Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8278 SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8279 isa<ConstantSDNode>(Idx)) {
8280 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8281 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8284 if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8285 SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8286 isa<ConstantSDNode>(Idx)) {
8287 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8288 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8294 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8295 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8296 // one of the above mentioned nodes. It has to be wrapped because otherwise
8297 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8298 // be used to form addressing mode. These wrapped nodes will be selected
8301 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8302 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8304 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8306 unsigned char OpFlag = 0;
8307 unsigned WrapperKind = X86ISD::Wrapper;
8308 CodeModel::Model M = getTargetMachine().getCodeModel();
8310 if (Subtarget->isPICStyleRIPRel() &&
8311 (M == CodeModel::Small || M == CodeModel::Kernel))
8312 WrapperKind = X86ISD::WrapperRIP;
8313 else if (Subtarget->isPICStyleGOT())
8314 OpFlag = X86II::MO_GOTOFF;
8315 else if (Subtarget->isPICStyleStubPIC())
8316 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8318 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8320 CP->getOffset(), OpFlag);
8322 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8323 // With PIC, the address is actually $g + Offset.
8325 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8326 DAG.getNode(X86ISD::GlobalBaseReg,
8327 SDLoc(), getPointerTy()),
8334 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8335 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8337 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8339 unsigned char OpFlag = 0;
8340 unsigned WrapperKind = X86ISD::Wrapper;
8341 CodeModel::Model M = getTargetMachine().getCodeModel();
8343 if (Subtarget->isPICStyleRIPRel() &&
8344 (M == CodeModel::Small || M == CodeModel::Kernel))
8345 WrapperKind = X86ISD::WrapperRIP;
8346 else if (Subtarget->isPICStyleGOT())
8347 OpFlag = X86II::MO_GOTOFF;
8348 else if (Subtarget->isPICStyleStubPIC())
8349 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8351 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8354 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8356 // With PIC, the address is actually $g + Offset.
8358 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8359 DAG.getNode(X86ISD::GlobalBaseReg,
8360 SDLoc(), getPointerTy()),
8367 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8368 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8370 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8372 unsigned char OpFlag = 0;
8373 unsigned WrapperKind = X86ISD::Wrapper;
8374 CodeModel::Model M = getTargetMachine().getCodeModel();
8376 if (Subtarget->isPICStyleRIPRel() &&
8377 (M == CodeModel::Small || M == CodeModel::Kernel)) {
8378 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8379 OpFlag = X86II::MO_GOTPCREL;
8380 WrapperKind = X86ISD::WrapperRIP;
8381 } else if (Subtarget->isPICStyleGOT()) {
8382 OpFlag = X86II::MO_GOT;
8383 } else if (Subtarget->isPICStyleStubPIC()) {
8384 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8385 } else if (Subtarget->isPICStyleStubNoDynamic()) {
8386 OpFlag = X86II::MO_DARWIN_NONLAZY;
8389 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8392 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8394 // With PIC, the address is actually $g + Offset.
8395 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
8396 !Subtarget->is64Bit()) {
8397 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8398 DAG.getNode(X86ISD::GlobalBaseReg,
8399 SDLoc(), getPointerTy()),
8403 // For symbols that require a load from a stub to get the address, emit the
8405 if (isGlobalStubReference(OpFlag))
8406 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8407 MachinePointerInfo::getGOT(), false, false, false, 0);
8413 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8414 // Create the TargetBlockAddressAddress node.
8415 unsigned char OpFlags =
8416 Subtarget->ClassifyBlockAddressReference();
8417 CodeModel::Model M = getTargetMachine().getCodeModel();
8418 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8419 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8421 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8424 if (Subtarget->isPICStyleRIPRel() &&
8425 (M == CodeModel::Small || M == CodeModel::Kernel))
8426 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8428 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8430 // With PIC, the address is actually $g + Offset.
8431 if (isGlobalRelativeToPICBase(OpFlags)) {
8432 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8433 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8441 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8442 int64_t Offset, SelectionDAG &DAG) const {
8443 // Create the TargetGlobalAddress node, folding in the constant
8444 // offset if it is legal.
8445 unsigned char OpFlags =
8446 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
8447 CodeModel::Model M = getTargetMachine().getCodeModel();
8449 if (OpFlags == X86II::MO_NO_FLAG &&
8450 X86::isOffsetSuitableForCodeModel(Offset, M)) {
8451 // A direct static reference to a global.
8452 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8455 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8458 if (Subtarget->isPICStyleRIPRel() &&
8459 (M == CodeModel::Small || M == CodeModel::Kernel))
8460 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8462 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8464 // With PIC, the address is actually $g + Offset.
8465 if (isGlobalRelativeToPICBase(OpFlags)) {
8466 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8467 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8471 // For globals that require a load from a stub to get the address, emit the
8473 if (isGlobalStubReference(OpFlags))
8474 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8475 MachinePointerInfo::getGOT(), false, false, false, 0);
8477 // If there was a non-zero offset that we didn't fold, create an explicit
8480 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8481 DAG.getConstant(Offset, getPointerTy()));
8487 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8488 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8489 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8490 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8494 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8495 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8496 unsigned char OperandFlags, bool LocalDynamic = false) {
8497 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8498 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8500 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8501 GA->getValueType(0),
8505 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8509 SDValue Ops[] = { Chain, TGA, *InFlag };
8510 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8512 SDValue Ops[] = { Chain, TGA };
8513 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8516 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8517 MFI->setAdjustsStack(true);
8519 SDValue Flag = Chain.getValue(1);
8520 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8523 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8525 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8528 SDLoc dl(GA); // ? function entry point might be better
8529 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8530 DAG.getNode(X86ISD::GlobalBaseReg,
8531 SDLoc(), PtrVT), InFlag);
8532 InFlag = Chain.getValue(1);
8534 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8537 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8539 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8541 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
8542 X86::RAX, X86II::MO_TLSGD);
8545 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8551 // Get the start address of the TLS block for this module.
8552 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8553 .getInfo<X86MachineFunctionInfo>();
8554 MFI->incNumLocalDynamicTLSAccesses();
8558 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
8559 X86II::MO_TLSLD, /*LocalDynamic=*/true);
8562 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8563 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8564 InFlag = Chain.getValue(1);
8565 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8566 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8569 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8573 unsigned char OperandFlags = X86II::MO_DTPOFF;
8574 unsigned WrapperKind = X86ISD::Wrapper;
8575 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8576 GA->getValueType(0),
8577 GA->getOffset(), OperandFlags);
8578 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8580 // Add x@dtpoff with the base.
8581 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8584 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8585 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8586 const EVT PtrVT, TLSModel::Model model,
8587 bool is64Bit, bool isPIC) {
8590 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8591 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8592 is64Bit ? 257 : 256));
8594 SDValue ThreadPointer =
8595 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
8596 MachinePointerInfo(Ptr), false, false, false, 0);
8598 unsigned char OperandFlags = 0;
8599 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
8601 unsigned WrapperKind = X86ISD::Wrapper;
8602 if (model == TLSModel::LocalExec) {
8603 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8604 } else if (model == TLSModel::InitialExec) {
8606 OperandFlags = X86II::MO_GOTTPOFF;
8607 WrapperKind = X86ISD::WrapperRIP;
8609 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8612 llvm_unreachable("Unexpected model");
8615 // emit "addl x@ntpoff,%eax" (local exec)
8616 // or "addl x@indntpoff,%eax" (initial exec)
8617 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8619 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
8620 GA->getOffset(), OperandFlags);
8621 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8623 if (model == TLSModel::InitialExec) {
8624 if (isPIC && !is64Bit) {
8625 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8626 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8630 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8631 MachinePointerInfo::getGOT(), false, false, false, 0);
8634 // The address of the thread local variable is the add of the thread
8635 // pointer with the offset of the variable.
8636 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8640 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8642 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8643 const GlobalValue *GV = GA->getGlobal();
8645 if (Subtarget->isTargetELF()) {
8646 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8649 case TLSModel::GeneralDynamic:
8650 if (Subtarget->is64Bit())
8651 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8652 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8653 case TLSModel::LocalDynamic:
8654 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8655 Subtarget->is64Bit());
8656 case TLSModel::InitialExec:
8657 case TLSModel::LocalExec:
8658 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8659 Subtarget->is64Bit(),
8660 getTargetMachine().getRelocationModel() == Reloc::PIC_);
8662 llvm_unreachable("Unknown TLS model.");
8665 if (Subtarget->isTargetDarwin()) {
8666 // Darwin only has one model of TLS. Lower to that.
8667 unsigned char OpFlag = 0;
8668 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8669 X86ISD::WrapperRIP : X86ISD::Wrapper;
8671 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8673 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8674 !Subtarget->is64Bit();
8676 OpFlag = X86II::MO_TLVP_PIC_BASE;
8678 OpFlag = X86II::MO_TLVP;
8680 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8681 GA->getValueType(0),
8682 GA->getOffset(), OpFlag);
8683 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8685 // With PIC32, the address is actually $g + Offset.
8687 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8688 DAG.getNode(X86ISD::GlobalBaseReg,
8689 SDLoc(), getPointerTy()),
8692 // Lowering the machine isd will make sure everything is in the right
8694 SDValue Chain = DAG.getEntryNode();
8695 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8696 SDValue Args[] = { Chain, Offset };
8697 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
8699 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8700 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8701 MFI->setAdjustsStack(true);
8703 // And our return value (tls address) is in the standard call return value
8705 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8706 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8710 if (Subtarget->isTargetKnownWindowsMSVC() ||
8711 Subtarget->isTargetWindowsGNU()) {
8712 // Just use the implicit TLS architecture
8713 // Need to generate someting similar to:
8714 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8716 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
8717 // mov rcx, qword [rdx+rcx*8]
8718 // mov eax, .tls$:tlsvar
8719 // [rax+rcx] contains the address
8720 // Windows 64bit: gs:0x58
8721 // Windows 32bit: fs:__tls_array
8723 // If GV is an alias then use the aliasee for determining
8724 // thread-localness.
8725 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
8726 GV = GA->getAliasedGlobal();
8728 SDValue Chain = DAG.getEntryNode();
8730 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8731 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8732 // use its literal value of 0x2C.
8733 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8734 ? Type::getInt8PtrTy(*DAG.getContext(),
8736 : Type::getInt32PtrTy(*DAG.getContext(),
8740 Subtarget->is64Bit()
8741 ? DAG.getIntPtrConstant(0x58)
8742 : (Subtarget->isTargetWindowsGNU()
8743 ? DAG.getIntPtrConstant(0x2C)
8744 : DAG.getExternalSymbol("_tls_array", getPointerTy()));
8746 SDValue ThreadPointer =
8747 DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8748 MachinePointerInfo(Ptr), false, false, false, 0);
8750 // Load the _tls_index variable
8751 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8752 if (Subtarget->is64Bit())
8753 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8754 IDX, MachinePointerInfo(), MVT::i32,
8757 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
8758 false, false, false, 0);
8760 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
8762 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
8764 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
8765 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
8766 false, false, false, 0);
8768 // Get the offset of start of .tls section
8769 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8770 GA->getValueType(0),
8771 GA->getOffset(), X86II::MO_SECREL);
8772 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
8774 // The address of the thread local variable is the add of the thread
8775 // pointer with the offset of the variable.
8776 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
8779 llvm_unreachable("TLS not implemented for this target.");
8782 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
8783 /// and take a 2 x i32 value to shift plus a shift amount.
8784 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
8785 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
8786 MVT VT = Op.getSimpleValueType();
8787 unsigned VTBits = VT.getSizeInBits();
8789 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
8790 SDValue ShOpLo = Op.getOperand(0);
8791 SDValue ShOpHi = Op.getOperand(1);
8792 SDValue ShAmt = Op.getOperand(2);
8793 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
8794 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
8796 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8797 DAG.getConstant(VTBits - 1, MVT::i8));
8798 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
8799 DAG.getConstant(VTBits - 1, MVT::i8))
8800 : DAG.getConstant(0, VT);
8803 if (Op.getOpcode() == ISD::SHL_PARTS) {
8804 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
8805 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
8807 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
8808 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
8811 // If the shift amount is larger or equal than the width of a part we can't
8812 // rely on the results of shld/shrd. Insert a test and select the appropriate
8813 // values for large shift amounts.
8814 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8815 DAG.getConstant(VTBits, MVT::i8));
8816 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8817 AndNode, DAG.getConstant(0, MVT::i8));
8820 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8821 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
8822 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
8824 if (Op.getOpcode() == ISD::SHL_PARTS) {
8825 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
8826 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
8828 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
8829 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
8832 SDValue Ops[2] = { Lo, Hi };
8833 return DAG.getMergeValues(Ops, dl);
8836 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
8837 SelectionDAG &DAG) const {
8838 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
8840 if (SrcVT.isVector())
8843 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
8844 "Unknown SINT_TO_FP to lower!");
8846 // These are really Legal; return the operand so the caller accepts it as
8848 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
8850 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
8851 Subtarget->is64Bit()) {
8856 unsigned Size = SrcVT.getSizeInBits()/8;
8857 MachineFunction &MF = DAG.getMachineFunction();
8858 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8859 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8860 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8862 MachinePointerInfo::getFixedStack(SSFI),
8864 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8867 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8869 SelectionDAG &DAG) const {
8873 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8875 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8877 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8879 unsigned ByteSize = SrcVT.getSizeInBits()/8;
8881 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8882 MachineMemOperand *MMO;
8884 int SSFI = FI->getIndex();
8886 DAG.getMachineFunction()
8887 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8888 MachineMemOperand::MOLoad, ByteSize, ByteSize);
8890 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8891 StackSlot = StackSlot.getOperand(1);
8893 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8894 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8896 Tys, Ops, SrcVT, MMO);
8899 Chain = Result.getValue(1);
8900 SDValue InFlag = Result.getValue(2);
8902 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8903 // shouldn't be necessary except that RFP cannot be live across
8904 // multiple blocks. When stackifier is fixed, they can be uncoupled.
8905 MachineFunction &MF = DAG.getMachineFunction();
8906 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8907 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8908 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8909 Tys = DAG.getVTList(MVT::Other);
8911 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8913 MachineMemOperand *MMO =
8914 DAG.getMachineFunction()
8915 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8916 MachineMemOperand::MOStore, SSFISize, SSFISize);
8918 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8919 Ops, Op.getValueType(), MMO);
8920 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8921 MachinePointerInfo::getFixedStack(SSFI),
8922 false, false, false, 0);
8928 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8929 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8930 SelectionDAG &DAG) const {
8931 // This algorithm is not obvious. Here it is what we're trying to output:
8934 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8935 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8939 pshufd $0x4e, %xmm0, %xmm1
8945 LLVMContext *Context = DAG.getContext();
8947 // Build some magic constants.
8948 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8949 Constant *C0 = ConstantDataVector::get(*Context, CV0);
8950 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8952 SmallVector<Constant*,2> CV1;
8954 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8955 APInt(64, 0x4330000000000000ULL))));
8957 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8958 APInt(64, 0x4530000000000000ULL))));
8959 Constant *C1 = ConstantVector::get(CV1);
8960 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8962 // Load the 64-bit value into an XMM register.
8963 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8965 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8966 MachinePointerInfo::getConstantPool(),
8967 false, false, false, 16);
8968 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8969 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8972 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8973 MachinePointerInfo::getConstantPool(),
8974 false, false, false, 16);
8975 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8976 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8979 if (Subtarget->hasSSE3()) {
8980 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8981 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8983 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8984 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8986 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8987 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8991 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8992 DAG.getIntPtrConstant(0));
8995 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8996 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8997 SelectionDAG &DAG) const {
8999 // FP constant to bias correct the final result.
9000 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
9003 // Load the 32-bit value into an XMM register.
9004 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
9007 // Zero out the upper parts of the register.
9008 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
9010 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9011 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
9012 DAG.getIntPtrConstant(0));
9014 // Or the load with the bias.
9015 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
9016 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9017 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9019 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9020 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9021 MVT::v2f64, Bias)));
9022 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9023 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
9024 DAG.getIntPtrConstant(0));
9026 // Subtract the bias.
9027 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
9029 // Handle final rounding.
9030 EVT DestVT = Op.getValueType();
9032 if (DestVT.bitsLT(MVT::f64))
9033 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
9034 DAG.getIntPtrConstant(0));
9035 if (DestVT.bitsGT(MVT::f64))
9036 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
9038 // Handle final rounding.
9042 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
9043 SelectionDAG &DAG) const {
9044 SDValue N0 = Op.getOperand(0);
9045 MVT SVT = N0.getSimpleValueType();
9048 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
9049 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
9050 "Custom UINT_TO_FP is not supported!");
9052 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
9053 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
9054 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
9057 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
9058 SelectionDAG &DAG) const {
9059 SDValue N0 = Op.getOperand(0);
9062 if (Op.getValueType().isVector())
9063 return lowerUINT_TO_FP_vec(Op, DAG);
9065 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
9066 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
9067 // the optimization here.
9068 if (DAG.SignBitIsZero(N0))
9069 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
9071 MVT SrcVT = N0.getSimpleValueType();
9072 MVT DstVT = Op.getSimpleValueType();
9073 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
9074 return LowerUINT_TO_FP_i64(Op, DAG);
9075 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
9076 return LowerUINT_TO_FP_i32(Op, DAG);
9077 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
9080 // Make a 64-bit buffer, and use it to build an FILD.
9081 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
9082 if (SrcVT == MVT::i32) {
9083 SDValue WordOff = DAG.getConstant(4, getPointerTy());
9084 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
9085 getPointerTy(), StackSlot, WordOff);
9086 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9087 StackSlot, MachinePointerInfo(),
9089 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
9090 OffsetSlot, MachinePointerInfo(),
9092 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
9096 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
9097 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9098 StackSlot, MachinePointerInfo(),
9100 // For i64 source, we need to add the appropriate power of 2 if the input
9101 // was negative. This is the same as the optimization in
9102 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
9103 // we must be careful to do the computation in x87 extended precision, not
9104 // in SSE. (The generic code can't know it's OK to do this, or how to.)
9105 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
9106 MachineMemOperand *MMO =
9107 DAG.getMachineFunction()
9108 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9109 MachineMemOperand::MOLoad, 8, 8);
9111 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
9112 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
9113 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
9116 APInt FF(32, 0x5F800000ULL);
9118 // Check whether the sign bit is set.
9119 SDValue SignSet = DAG.getSetCC(dl,
9120 getSetCCResultType(*DAG.getContext(), MVT::i64),
9121 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
9124 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
9125 SDValue FudgePtr = DAG.getConstantPool(
9126 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
9129 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
9130 SDValue Zero = DAG.getIntPtrConstant(0);
9131 SDValue Four = DAG.getIntPtrConstant(4);
9132 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
9134 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
9136 // Load the value out, extending it from f32 to f80.
9137 // FIXME: Avoid the extend by constructing the right constant pool?
9138 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
9139 FudgePtr, MachinePointerInfo::getConstantPool(),
9140 MVT::f32, false, false, 4);
9141 // Extend everything to 80 bits to force it to be done on x87.
9142 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
9143 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
9146 std::pair<SDValue,SDValue>
9147 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
9148 bool IsSigned, bool IsReplace) const {
9151 EVT DstTy = Op.getValueType();
9153 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
9154 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
9158 assert(DstTy.getSimpleVT() <= MVT::i64 &&
9159 DstTy.getSimpleVT() >= MVT::i16 &&
9160 "Unknown FP_TO_INT to lower!");
9162 // These are really Legal.
9163 if (DstTy == MVT::i32 &&
9164 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9165 return std::make_pair(SDValue(), SDValue());
9166 if (Subtarget->is64Bit() &&
9167 DstTy == MVT::i64 &&
9168 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9169 return std::make_pair(SDValue(), SDValue());
9171 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
9172 // stack slot, or into the FTOL runtime function.
9173 MachineFunction &MF = DAG.getMachineFunction();
9174 unsigned MemSize = DstTy.getSizeInBits()/8;
9175 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9176 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9179 if (!IsSigned && isIntegerTypeFTOL(DstTy))
9180 Opc = X86ISD::WIN_FTOL;
9182 switch (DstTy.getSimpleVT().SimpleTy) {
9183 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
9184 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
9185 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
9186 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
9189 SDValue Chain = DAG.getEntryNode();
9190 SDValue Value = Op.getOperand(0);
9191 EVT TheVT = Op.getOperand(0).getValueType();
9192 // FIXME This causes a redundant load/store if the SSE-class value is already
9193 // in memory, such as if it is on the callstack.
9194 if (isScalarFPTypeInSSEReg(TheVT)) {
9195 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
9196 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
9197 MachinePointerInfo::getFixedStack(SSFI),
9199 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
9201 Chain, StackSlot, DAG.getValueType(TheVT)
9204 MachineMemOperand *MMO =
9205 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9206 MachineMemOperand::MOLoad, MemSize, MemSize);
9207 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
9208 Chain = Value.getValue(1);
9209 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9210 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9213 MachineMemOperand *MMO =
9214 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9215 MachineMemOperand::MOStore, MemSize, MemSize);
9217 if (Opc != X86ISD::WIN_FTOL) {
9218 // Build the FP_TO_INT*_IN_MEM
9219 SDValue Ops[] = { Chain, Value, StackSlot };
9220 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
9222 return std::make_pair(FIST, StackSlot);
9224 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
9225 DAG.getVTList(MVT::Other, MVT::Glue),
9227 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
9228 MVT::i32, ftol.getValue(1));
9229 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
9230 MVT::i32, eax.getValue(2));
9231 SDValue Ops[] = { eax, edx };
9232 SDValue pair = IsReplace
9233 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
9234 : DAG.getMergeValues(Ops, DL);
9235 return std::make_pair(pair, SDValue());
9239 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
9240 const X86Subtarget *Subtarget) {
9241 MVT VT = Op->getSimpleValueType(0);
9242 SDValue In = Op->getOperand(0);
9243 MVT InVT = In.getSimpleValueType();
9246 // Optimize vectors in AVX mode:
9249 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
9250 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
9251 // Concat upper and lower parts.
9254 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
9255 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
9256 // Concat upper and lower parts.
9259 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
9260 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
9261 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
9264 if (Subtarget->hasInt256())
9265 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
9267 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
9268 SDValue Undef = DAG.getUNDEF(InVT);
9269 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9270 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9271 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9273 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9274 VT.getVectorNumElements()/2);
9276 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9277 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9279 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9282 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9283 SelectionDAG &DAG) {
9284 MVT VT = Op->getSimpleValueType(0);
9285 SDValue In = Op->getOperand(0);
9286 MVT InVT = In.getSimpleValueType();
9288 unsigned int NumElts = VT.getVectorNumElements();
9289 if (NumElts != 8 && NumElts != 16)
9292 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9293 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9295 EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9296 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9297 // Now we have only mask extension
9298 assert(InVT.getVectorElementType() == MVT::i1);
9299 SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9300 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9301 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9302 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9303 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9304 MachinePointerInfo::getConstantPool(),
9305 false, false, false, Alignment);
9307 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9308 if (VT.is512BitVector())
9310 return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9313 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9314 SelectionDAG &DAG) {
9315 if (Subtarget->hasFp256()) {
9316 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9324 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9325 SelectionDAG &DAG) {
9327 MVT VT = Op.getSimpleValueType();
9328 SDValue In = Op.getOperand(0);
9329 MVT SVT = In.getSimpleValueType();
9331 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9332 return LowerZERO_EXTEND_AVX512(Op, DAG);
9334 if (Subtarget->hasFp256()) {
9335 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9340 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9341 VT.getVectorNumElements() != SVT.getVectorNumElements());
9345 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9347 MVT VT = Op.getSimpleValueType();
9348 SDValue In = Op.getOperand(0);
9349 MVT InVT = In.getSimpleValueType();
9351 if (VT == MVT::i1) {
9352 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9353 "Invalid scalar TRUNCATE operation");
9354 if (InVT == MVT::i32)
9356 if (InVT.getSizeInBits() == 64)
9357 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9358 else if (InVT.getSizeInBits() < 32)
9359 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9360 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
9362 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9363 "Invalid TRUNCATE operation");
9365 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9366 if (VT.getVectorElementType().getSizeInBits() >=8)
9367 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9369 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9370 unsigned NumElts = InVT.getVectorNumElements();
9371 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9372 if (InVT.getSizeInBits() < 512) {
9373 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9374 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9378 SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9379 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9380 SDValue CP = DAG.getConstantPool(C, getPointerTy());
9381 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9382 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9383 MachinePointerInfo::getConstantPool(),
9384 false, false, false, Alignment);
9385 SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9386 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9387 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9390 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9391 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9392 if (Subtarget->hasInt256()) {
9393 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9394 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9395 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9397 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9398 DAG.getIntPtrConstant(0));
9401 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9402 DAG.getIntPtrConstant(0));
9403 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9404 DAG.getIntPtrConstant(2));
9405 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9406 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9407 static const int ShufMask[] = {0, 2, 4, 6};
9408 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
9411 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9412 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9413 if (Subtarget->hasInt256()) {
9414 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9416 SmallVector<SDValue,32> pshufbMask;
9417 for (unsigned i = 0; i < 2; ++i) {
9418 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9419 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9420 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9421 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9422 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9423 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9424 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9425 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9426 for (unsigned j = 0; j < 8; ++j)
9427 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9429 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
9430 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9431 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9433 static const int ShufMask[] = {0, 2, -1, -1};
9434 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
9436 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9437 DAG.getIntPtrConstant(0));
9438 return DAG.getNode(ISD::BITCAST, DL, VT, In);
9441 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9442 DAG.getIntPtrConstant(0));
9444 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9445 DAG.getIntPtrConstant(4));
9447 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9448 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9451 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
9452 -1, -1, -1, -1, -1, -1, -1, -1};
9454 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9455 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9456 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9458 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9459 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9461 // The MOVLHPS Mask:
9462 static const int ShufMask2[] = {0, 1, 4, 5};
9463 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9464 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9467 // Handle truncation of V256 to V128 using shuffles.
9468 if (!VT.is128BitVector() || !InVT.is256BitVector())
9471 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9473 unsigned NumElems = VT.getVectorNumElements();
9474 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
9476 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9477 // Prepare truncation shuffle mask
9478 for (unsigned i = 0; i != NumElems; ++i)
9480 SDValue V = DAG.getVectorShuffle(NVT, DL,
9481 DAG.getNode(ISD::BITCAST, DL, NVT, In),
9482 DAG.getUNDEF(NVT), &MaskVec[0]);
9483 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9484 DAG.getIntPtrConstant(0));
9487 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9488 SelectionDAG &DAG) const {
9489 assert(!Op.getSimpleValueType().isVector());
9491 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9492 /*IsSigned=*/ true, /*IsReplace=*/ false);
9493 SDValue FIST = Vals.first, StackSlot = Vals.second;
9494 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9495 if (!FIST.getNode()) return Op;
9497 if (StackSlot.getNode())
9499 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9500 FIST, StackSlot, MachinePointerInfo(),
9501 false, false, false, 0);
9503 // The node is the result.
9507 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9508 SelectionDAG &DAG) const {
9509 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9510 /*IsSigned=*/ false, /*IsReplace=*/ false);
9511 SDValue FIST = Vals.first, StackSlot = Vals.second;
9512 assert(FIST.getNode() && "Unexpected failure");
9514 if (StackSlot.getNode())
9516 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9517 FIST, StackSlot, MachinePointerInfo(),
9518 false, false, false, 0);
9520 // The node is the result.
9524 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9526 MVT VT = Op.getSimpleValueType();
9527 SDValue In = Op.getOperand(0);
9528 MVT SVT = In.getSimpleValueType();
9530 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9532 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9533 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9534 In, DAG.getUNDEF(SVT)));
9537 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
9538 LLVMContext *Context = DAG.getContext();
9540 MVT VT = Op.getSimpleValueType();
9542 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9543 if (VT.isVector()) {
9544 EltVT = VT.getVectorElementType();
9545 NumElts = VT.getVectorNumElements();
9548 if (EltVT == MVT::f64)
9549 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9550 APInt(64, ~(1ULL << 63))));
9552 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9553 APInt(32, ~(1U << 31))));
9554 C = ConstantVector::getSplat(NumElts, C);
9555 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9556 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9557 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9558 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9559 MachinePointerInfo::getConstantPool(),
9560 false, false, false, Alignment);
9561 if (VT.isVector()) {
9562 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9563 return DAG.getNode(ISD::BITCAST, dl, VT,
9564 DAG.getNode(ISD::AND, dl, ANDVT,
9565 DAG.getNode(ISD::BITCAST, dl, ANDVT,
9567 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9569 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9572 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
9573 LLVMContext *Context = DAG.getContext();
9575 MVT VT = Op.getSimpleValueType();
9577 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9578 if (VT.isVector()) {
9579 EltVT = VT.getVectorElementType();
9580 NumElts = VT.getVectorNumElements();
9583 if (EltVT == MVT::f64)
9584 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9585 APInt(64, 1ULL << 63)));
9587 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9588 APInt(32, 1U << 31)));
9589 C = ConstantVector::getSplat(NumElts, C);
9590 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9591 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9592 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9593 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9594 MachinePointerInfo::getConstantPool(),
9595 false, false, false, Alignment);
9596 if (VT.isVector()) {
9597 MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
9598 return DAG.getNode(ISD::BITCAST, dl, VT,
9599 DAG.getNode(ISD::XOR, dl, XORVT,
9600 DAG.getNode(ISD::BITCAST, dl, XORVT,
9602 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9605 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9608 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
9609 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9610 LLVMContext *Context = DAG.getContext();
9611 SDValue Op0 = Op.getOperand(0);
9612 SDValue Op1 = Op.getOperand(1);
9614 MVT VT = Op.getSimpleValueType();
9615 MVT SrcVT = Op1.getSimpleValueType();
9617 // If second operand is smaller, extend it first.
9618 if (SrcVT.bitsLT(VT)) {
9619 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9622 // And if it is bigger, shrink it first.
9623 if (SrcVT.bitsGT(VT)) {
9624 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9628 // At this point the operands and the result should have the same
9629 // type, and that won't be f80 since that is not custom lowered.
9631 // First get the sign bit of second operand.
9632 SmallVector<Constant*,4> CV;
9633 if (SrcVT == MVT::f64) {
9634 const fltSemantics &Sem = APFloat::IEEEdouble;
9635 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9636 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9638 const fltSemantics &Sem = APFloat::IEEEsingle;
9639 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9640 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9641 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9642 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9644 Constant *C = ConstantVector::get(CV);
9645 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9646 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9647 MachinePointerInfo::getConstantPool(),
9648 false, false, false, 16);
9649 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9651 // Shift sign bit right or left if the two operands have different types.
9652 if (SrcVT.bitsGT(VT)) {
9653 // Op0 is MVT::f32, Op1 is MVT::f64.
9654 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9655 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9656 DAG.getConstant(32, MVT::i32));
9657 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9658 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9659 DAG.getIntPtrConstant(0));
9662 // Clear first operand sign bit.
9664 if (VT == MVT::f64) {
9665 const fltSemantics &Sem = APFloat::IEEEdouble;
9666 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9667 APInt(64, ~(1ULL << 63)))));
9668 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9670 const fltSemantics &Sem = APFloat::IEEEsingle;
9671 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9672 APInt(32, ~(1U << 31)))));
9673 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9674 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9675 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9677 C = ConstantVector::get(CV);
9678 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9679 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9680 MachinePointerInfo::getConstantPool(),
9681 false, false, false, 16);
9682 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9684 // Or the value with the sign bit.
9685 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9688 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9689 SDValue N0 = Op.getOperand(0);
9691 MVT VT = Op.getSimpleValueType();
9693 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9694 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9695 DAG.getConstant(1, VT));
9696 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9699 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9701 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
9702 SelectionDAG &DAG) {
9703 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9705 if (!Subtarget->hasSSE41())
9708 if (!Op->hasOneUse())
9711 SDNode *N = Op.getNode();
9714 SmallVector<SDValue, 8> Opnds;
9715 DenseMap<SDValue, unsigned> VecInMap;
9716 SmallVector<SDValue, 8> VecIns;
9717 EVT VT = MVT::Other;
9719 // Recognize a special case where a vector is casted into wide integer to
9721 Opnds.push_back(N->getOperand(0));
9722 Opnds.push_back(N->getOperand(1));
9724 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9725 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9726 // BFS traverse all OR'd operands.
9727 if (I->getOpcode() == ISD::OR) {
9728 Opnds.push_back(I->getOperand(0));
9729 Opnds.push_back(I->getOperand(1));
9730 // Re-evaluate the number of nodes to be traversed.
9731 e += 2; // 2 more nodes (LHS and RHS) are pushed.
9735 // Quit if a non-EXTRACT_VECTOR_ELT
9736 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9739 // Quit if without a constant index.
9740 SDValue Idx = I->getOperand(1);
9741 if (!isa<ConstantSDNode>(Idx))
9744 SDValue ExtractedFromVec = I->getOperand(0);
9745 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9746 if (M == VecInMap.end()) {
9747 VT = ExtractedFromVec.getValueType();
9748 // Quit if not 128/256-bit vector.
9749 if (!VT.is128BitVector() && !VT.is256BitVector())
9751 // Quit if not the same type.
9752 if (VecInMap.begin() != VecInMap.end() &&
9753 VT != VecInMap.begin()->first.getValueType())
9755 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9756 VecIns.push_back(ExtractedFromVec);
9758 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9761 assert((VT.is128BitVector() || VT.is256BitVector()) &&
9762 "Not extracted from 128-/256-bit vector.");
9764 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
9766 for (DenseMap<SDValue, unsigned>::const_iterator
9767 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
9768 // Quit if not all elements are used.
9769 if (I->second != FullMask)
9773 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9775 // Cast all vectors into TestVT for PTEST.
9776 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
9777 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
9779 // If more than one full vectors are evaluated, OR them first before PTEST.
9780 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
9781 // Each iteration will OR 2 nodes and append the result until there is only
9782 // 1 node left, i.e. the final OR'd value of all vectors.
9783 SDValue LHS = VecIns[Slot];
9784 SDValue RHS = VecIns[Slot + 1];
9785 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
9788 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
9789 VecIns.back(), VecIns.back());
9792 /// \brief return true if \c Op has a use that doesn't just read flags.
9793 static bool hasNonFlagsUse(SDValue Op) {
9794 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
9797 unsigned UOpNo = UI.getOperandNo();
9798 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9799 // Look pass truncate.
9800 UOpNo = User->use_begin().getOperandNo();
9801 User = *User->use_begin();
9804 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
9805 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
9811 /// Emit nodes that will be selected as "test Op0,Op0", or something
9813 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
9814 SelectionDAG &DAG) const {
9815 if (Op.getValueType() == MVT::i1)
9816 // KORTEST instruction should be selected
9817 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9818 DAG.getConstant(0, Op.getValueType()));
9820 // CF and OF aren't always set the way we want. Determine which
9821 // of these we need.
9822 bool NeedCF = false;
9823 bool NeedOF = false;
9826 case X86::COND_A: case X86::COND_AE:
9827 case X86::COND_B: case X86::COND_BE:
9830 case X86::COND_G: case X86::COND_GE:
9831 case X86::COND_L: case X86::COND_LE:
9832 case X86::COND_O: case X86::COND_NO:
9836 // See if we can use the EFLAGS value from the operand instead of
9837 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
9838 // we prove that the arithmetic won't overflow, we can't use OF or CF.
9839 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
9840 // Emit a CMP with 0, which is the TEST pattern.
9841 //if (Op.getValueType() == MVT::i1)
9842 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
9843 // DAG.getConstant(0, MVT::i1));
9844 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9845 DAG.getConstant(0, Op.getValueType()));
9847 unsigned Opcode = 0;
9848 unsigned NumOperands = 0;
9850 // Truncate operations may prevent the merge of the SETCC instruction
9851 // and the arithmetic instruction before it. Attempt to truncate the operands
9852 // of the arithmetic instruction and use a reduced bit-width instruction.
9853 bool NeedTruncation = false;
9854 SDValue ArithOp = Op;
9855 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
9856 SDValue Arith = Op->getOperand(0);
9857 // Both the trunc and the arithmetic op need to have one user each.
9858 if (Arith->hasOneUse())
9859 switch (Arith.getOpcode()) {
9866 NeedTruncation = true;
9872 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
9873 // which may be the result of a CAST. We use the variable 'Op', which is the
9874 // non-casted variable when we check for possible users.
9875 switch (ArithOp.getOpcode()) {
9877 // Due to an isel shortcoming, be conservative if this add is likely to be
9878 // selected as part of a load-modify-store instruction. When the root node
9879 // in a match is a store, isel doesn't know how to remap non-chain non-flag
9880 // uses of other nodes in the match, such as the ADD in this case. This
9881 // leads to the ADD being left around and reselected, with the result being
9882 // two adds in the output. Alas, even if none our users are stores, that
9883 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
9884 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
9885 // climbing the DAG back to the root, and it doesn't seem to be worth the
9887 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9888 UE = Op.getNode()->use_end(); UI != UE; ++UI)
9889 if (UI->getOpcode() != ISD::CopyToReg &&
9890 UI->getOpcode() != ISD::SETCC &&
9891 UI->getOpcode() != ISD::STORE)
9894 if (ConstantSDNode *C =
9895 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
9896 // An add of one will be selected as an INC.
9897 if (C->getAPIntValue() == 1) {
9898 Opcode = X86ISD::INC;
9903 // An add of negative one (subtract of one) will be selected as a DEC.
9904 if (C->getAPIntValue().isAllOnesValue()) {
9905 Opcode = X86ISD::DEC;
9911 // Otherwise use a regular EFLAGS-setting add.
9912 Opcode = X86ISD::ADD;
9917 // If we have a constant logical shift that's only used in a comparison
9918 // against zero turn it into an equivalent AND. This allows turning it into
9919 // a TEST instruction later.
9920 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) &&
9921 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
9922 EVT VT = Op.getValueType();
9923 unsigned BitWidth = VT.getSizeInBits();
9924 unsigned ShAmt = Op->getConstantOperandVal(1);
9925 if (ShAmt >= BitWidth) // Avoid undefined shifts.
9927 APInt Mask = ArithOp.getOpcode() == ISD::SRL
9928 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
9929 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
9930 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
9932 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
9933 DAG.getConstant(Mask, VT));
9934 DAG.ReplaceAllUsesWith(Op, New);
9940 // If the primary and result isn't used, don't bother using X86ISD::AND,
9941 // because a TEST instruction will be better.
9942 if (!hasNonFlagsUse(Op))
9948 // Due to the ISEL shortcoming noted above, be conservative if this op is
9949 // likely to be selected as part of a load-modify-store instruction.
9950 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9951 UE = Op.getNode()->use_end(); UI != UE; ++UI)
9952 if (UI->getOpcode() == ISD::STORE)
9955 // Otherwise use a regular EFLAGS-setting instruction.
9956 switch (ArithOp.getOpcode()) {
9957 default: llvm_unreachable("unexpected operator!");
9958 case ISD::SUB: Opcode = X86ISD::SUB; break;
9959 case ISD::XOR: Opcode = X86ISD::XOR; break;
9960 case ISD::AND: Opcode = X86ISD::AND; break;
9962 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9963 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
9964 if (EFLAGS.getNode())
9967 Opcode = X86ISD::OR;
9981 return SDValue(Op.getNode(), 1);
9987 // If we found that truncation is beneficial, perform the truncation and
9989 if (NeedTruncation) {
9990 EVT VT = Op.getValueType();
9991 SDValue WideVal = Op->getOperand(0);
9992 EVT WideVT = WideVal.getValueType();
9993 unsigned ConvertedOp = 0;
9994 // Use a target machine opcode to prevent further DAGCombine
9995 // optimizations that may separate the arithmetic operations
9996 // from the setcc node.
9997 switch (WideVal.getOpcode()) {
9999 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
10000 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
10001 case ISD::AND: ConvertedOp = X86ISD::AND; break;
10002 case ISD::OR: ConvertedOp = X86ISD::OR; break;
10003 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
10007 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10008 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
10009 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
10010 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
10011 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
10017 // Emit a CMP with 0, which is the TEST pattern.
10018 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10019 DAG.getConstant(0, Op.getValueType()));
10021 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10022 SmallVector<SDValue, 4> Ops;
10023 for (unsigned i = 0; i != NumOperands; ++i)
10024 Ops.push_back(Op.getOperand(i));
10026 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
10027 DAG.ReplaceAllUsesWith(Op, New);
10028 return SDValue(New.getNode(), 1);
10031 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
10033 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
10034 SDLoc dl, SelectionDAG &DAG) const {
10035 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
10036 if (C->getAPIntValue() == 0)
10037 return EmitTest(Op0, X86CC, dl, DAG);
10039 if (Op0.getValueType() == MVT::i1)
10040 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
10043 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
10044 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
10045 // Do the comparison at i32 if it's smaller, besides the Atom case.
10046 // This avoids subregister aliasing issues. Keep the smaller reference
10047 // if we're optimizing for size, however, as that'll allow better folding
10048 // of memory operations.
10049 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
10050 !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
10051 AttributeSet::FunctionIndex, Attribute::MinSize) &&
10052 !Subtarget->isAtom()) {
10053 unsigned ExtendOp =
10054 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
10055 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
10056 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
10058 // Use SUB instead of CMP to enable CSE between SUB and CMP.
10059 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
10060 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
10062 return SDValue(Sub.getNode(), 1);
10064 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
10067 /// Convert a comparison if required by the subtarget.
10068 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
10069 SelectionDAG &DAG) const {
10070 // If the subtarget does not support the FUCOMI instruction, floating-point
10071 // comparisons have to be converted.
10072 if (Subtarget->hasCMov() ||
10073 Cmp.getOpcode() != X86ISD::CMP ||
10074 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
10075 !Cmp.getOperand(1).getValueType().isFloatingPoint())
10078 // The instruction selector will select an FUCOM instruction instead of
10079 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
10080 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
10081 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
10083 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
10084 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
10085 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
10086 DAG.getConstant(8, MVT::i8));
10087 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
10088 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
10091 static bool isAllOnes(SDValue V) {
10092 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10093 return C && C->isAllOnesValue();
10096 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
10097 /// if it's possible.
10098 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
10099 SDLoc dl, SelectionDAG &DAG) const {
10100 SDValue Op0 = And.getOperand(0);
10101 SDValue Op1 = And.getOperand(1);
10102 if (Op0.getOpcode() == ISD::TRUNCATE)
10103 Op0 = Op0.getOperand(0);
10104 if (Op1.getOpcode() == ISD::TRUNCATE)
10105 Op1 = Op1.getOperand(0);
10108 if (Op1.getOpcode() == ISD::SHL)
10109 std::swap(Op0, Op1);
10110 if (Op0.getOpcode() == ISD::SHL) {
10111 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
10112 if (And00C->getZExtValue() == 1) {
10113 // If we looked past a truncate, check that it's only truncating away
10115 unsigned BitWidth = Op0.getValueSizeInBits();
10116 unsigned AndBitWidth = And.getValueSizeInBits();
10117 if (BitWidth > AndBitWidth) {
10119 DAG.ComputeMaskedBits(Op0, Zeros, Ones);
10120 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
10124 RHS = Op0.getOperand(1);
10126 } else if (Op1.getOpcode() == ISD::Constant) {
10127 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
10128 uint64_t AndRHSVal = AndRHS->getZExtValue();
10129 SDValue AndLHS = Op0;
10131 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
10132 LHS = AndLHS.getOperand(0);
10133 RHS = AndLHS.getOperand(1);
10136 // Use BT if the immediate can't be encoded in a TEST instruction.
10137 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
10139 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
10143 if (LHS.getNode()) {
10144 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
10145 // instruction. Since the shift amount is in-range-or-undefined, we know
10146 // that doing a bittest on the i32 value is ok. We extend to i32 because
10147 // the encoding for the i16 version is larger than the i32 version.
10148 // Also promote i16 to i32 for performance / code size reason.
10149 if (LHS.getValueType() == MVT::i8 ||
10150 LHS.getValueType() == MVT::i16)
10151 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
10153 // If the operand types disagree, extend the shift amount to match. Since
10154 // BT ignores high bits (like shifts) we can use anyextend.
10155 if (LHS.getValueType() != RHS.getValueType())
10156 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
10158 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
10159 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
10160 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10161 DAG.getConstant(Cond, MVT::i8), BT);
10167 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
10169 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
10174 // SSE Condition code mapping:
10183 switch (SetCCOpcode) {
10184 default: llvm_unreachable("Unexpected SETCC condition");
10186 case ISD::SETEQ: SSECC = 0; break;
10188 case ISD::SETGT: Swap = true; // Fallthrough
10190 case ISD::SETOLT: SSECC = 1; break;
10192 case ISD::SETGE: Swap = true; // Fallthrough
10194 case ISD::SETOLE: SSECC = 2; break;
10195 case ISD::SETUO: SSECC = 3; break;
10197 case ISD::SETNE: SSECC = 4; break;
10198 case ISD::SETULE: Swap = true; // Fallthrough
10199 case ISD::SETUGE: SSECC = 5; break;
10200 case ISD::SETULT: Swap = true; // Fallthrough
10201 case ISD::SETUGT: SSECC = 6; break;
10202 case ISD::SETO: SSECC = 7; break;
10204 case ISD::SETONE: SSECC = 8; break;
10207 std::swap(Op0, Op1);
10212 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
10213 // ones, and then concatenate the result back.
10214 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
10215 MVT VT = Op.getSimpleValueType();
10217 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
10218 "Unsupported value type for operation");
10220 unsigned NumElems = VT.getVectorNumElements();
10222 SDValue CC = Op.getOperand(2);
10224 // Extract the LHS vectors
10225 SDValue LHS = Op.getOperand(0);
10226 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10227 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10229 // Extract the RHS vectors
10230 SDValue RHS = Op.getOperand(1);
10231 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10232 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10234 // Issue the operation on the smaller types and concatenate the result back
10235 MVT EltVT = VT.getVectorElementType();
10236 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10237 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10238 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
10239 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
10242 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
10243 const X86Subtarget *Subtarget) {
10244 SDValue Op0 = Op.getOperand(0);
10245 SDValue Op1 = Op.getOperand(1);
10246 SDValue CC = Op.getOperand(2);
10247 MVT VT = Op.getSimpleValueType();
10250 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
10251 Op.getValueType().getScalarType() == MVT::i1 &&
10252 "Cannot set masked compare for this operation");
10254 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10256 bool Unsigned = false;
10259 switch (SetCCOpcode) {
10260 default: llvm_unreachable("Unexpected SETCC condition");
10261 case ISD::SETNE: SSECC = 4; break;
10262 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
10263 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
10264 case ISD::SETLT: Swap = true; //fall-through
10265 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
10266 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
10267 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
10268 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
10269 case ISD::SETULE: Unsigned = true; //fall-through
10270 case ISD::SETLE: SSECC = 2; break;
10274 std::swap(Op0, Op1);
10276 return DAG.getNode(Opc, dl, VT, Op0, Op1);
10277 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
10278 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10279 DAG.getConstant(SSECC, MVT::i8));
10282 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
10283 /// operand \p Op1. If non-trivial (for example because it's not constant)
10284 /// return an empty value.
10285 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
10287 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
10291 MVT VT = Op1.getSimpleValueType();
10292 MVT EVT = VT.getVectorElementType();
10293 unsigned n = VT.getVectorNumElements();
10294 SmallVector<SDValue, 8> ULTOp1;
10296 for (unsigned i = 0; i < n; ++i) {
10297 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
10298 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
10301 // Avoid underflow.
10302 APInt Val = Elt->getAPIntValue();
10306 ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
10309 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
10312 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
10313 SelectionDAG &DAG) {
10314 SDValue Op0 = Op.getOperand(0);
10315 SDValue Op1 = Op.getOperand(1);
10316 SDValue CC = Op.getOperand(2);
10317 MVT VT = Op.getSimpleValueType();
10318 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10319 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10324 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10325 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10328 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10329 unsigned Opc = X86ISD::CMPP;
10330 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10331 assert(VT.getVectorNumElements() <= 16);
10332 Opc = X86ISD::CMPM;
10334 // In the two special cases we can't handle, emit two comparisons.
10337 unsigned CombineOpc;
10338 if (SetCCOpcode == ISD::SETUEQ) {
10339 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10341 assert(SetCCOpcode == ISD::SETONE);
10342 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10345 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10346 DAG.getConstant(CC0, MVT::i8));
10347 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10348 DAG.getConstant(CC1, MVT::i8));
10349 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10351 // Handle all other FP comparisons here.
10352 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10353 DAG.getConstant(SSECC, MVT::i8));
10356 // Break 256-bit integer vector compare into smaller ones.
10357 if (VT.is256BitVector() && !Subtarget->hasInt256())
10358 return Lower256IntVSETCC(Op, DAG);
10360 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10361 EVT OpVT = Op1.getValueType();
10362 if (Subtarget->hasAVX512()) {
10363 if (Op1.getValueType().is512BitVector() ||
10364 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10365 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
10367 // In AVX-512 architecture setcc returns mask with i1 elements,
10368 // But there is no compare instruction for i8 and i16 elements.
10369 // We are not talking about 512-bit operands in this case, these
10370 // types are illegal.
10372 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10373 OpVT.getVectorElementType().getSizeInBits() >= 8))
10374 return DAG.getNode(ISD::TRUNCATE, dl, VT,
10375 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10378 // We are handling one of the integer comparisons here. Since SSE only has
10379 // GT and EQ comparisons for integer, swapping operands and multiple
10380 // operations may be required for some comparisons.
10382 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10383 bool Subus = false;
10385 switch (SetCCOpcode) {
10386 default: llvm_unreachable("Unexpected SETCC condition");
10387 case ISD::SETNE: Invert = true;
10388 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
10389 case ISD::SETLT: Swap = true;
10390 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
10391 case ISD::SETGE: Swap = true;
10392 case ISD::SETLE: Opc = X86ISD::PCMPGT;
10393 Invert = true; break;
10394 case ISD::SETULT: Swap = true;
10395 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
10396 FlipSigns = true; break;
10397 case ISD::SETUGE: Swap = true;
10398 case ISD::SETULE: Opc = X86ISD::PCMPGT;
10399 FlipSigns = true; Invert = true; break;
10402 // Special case: Use min/max operations for SETULE/SETUGE
10403 MVT VET = VT.getVectorElementType();
10405 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10406 || (Subtarget->hasSSE2() && (VET == MVT::i8));
10409 switch (SetCCOpcode) {
10411 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10412 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10415 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10418 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
10419 if (!MinMax && hasSubus) {
10420 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
10422 // t = psubus Op0, Op1
10423 // pcmpeq t, <0..0>
10424 switch (SetCCOpcode) {
10426 case ISD::SETULT: {
10427 // If the comparison is against a constant we can turn this into a
10428 // setule. With psubus, setule does not require a swap. This is
10429 // beneficial because the constant in the register is no longer
10430 // destructed as the destination so it can be hoisted out of a loop.
10431 // Only do this pre-AVX since vpcmp* is no longer destructive.
10432 if (Subtarget->hasAVX())
10434 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
10435 if (ULEOp1.getNode()) {
10437 Subus = true; Invert = false; Swap = false;
10441 // Psubus is better than flip-sign because it requires no inversion.
10442 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
10443 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
10447 Opc = X86ISD::SUBUS;
10453 std::swap(Op0, Op1);
10455 // Check that the operation in question is available (most are plain SSE2,
10456 // but PCMPGTQ and PCMPEQQ have different requirements).
10457 if (VT == MVT::v2i64) {
10458 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10459 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10461 // First cast everything to the right type.
10462 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10463 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10465 // Since SSE has no unsigned integer comparisons, we need to flip the sign
10466 // bits of the inputs before performing those operations. The lower
10467 // compare is always unsigned.
10470 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10472 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10473 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10474 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10475 Sign, Zero, Sign, Zero);
10477 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10478 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10480 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10481 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10482 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10484 // Create masks for only the low parts/high parts of the 64 bit integers.
10485 static const int MaskHi[] = { 1, 1, 3, 3 };
10486 static const int MaskLo[] = { 0, 0, 2, 2 };
10487 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10488 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10489 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10491 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10492 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10495 Result = DAG.getNOT(dl, Result, MVT::v4i32);
10497 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10500 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10501 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10502 // pcmpeqd + pshufd + pand.
10503 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10505 // First cast everything to the right type.
10506 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10507 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10510 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
10512 // Make sure the lower and upper halves are both all-ones.
10513 static const int Mask[] = { 1, 0, 3, 2 };
10514 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
10515 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
10518 Result = DAG.getNOT(dl, Result, MVT::v4i32);
10520 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10524 // Since SSE has no unsigned integer comparisons, we need to flip the sign
10525 // bits of the inputs before performing those operations.
10527 EVT EltVT = VT.getVectorElementType();
10528 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
10529 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
10530 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
10533 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
10535 // If the logical-not of the result is required, perform that now.
10537 Result = DAG.getNOT(dl, Result, VT);
10540 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
10543 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
10544 getZeroVector(VT, Subtarget, DAG, dl));
10549 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
10551 MVT VT = Op.getSimpleValueType();
10553 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
10555 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
10556 && "SetCC type must be 8-bit or 1-bit integer");
10557 SDValue Op0 = Op.getOperand(0);
10558 SDValue Op1 = Op.getOperand(1);
10560 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10562 // Optimize to BT if possible.
10563 // Lower (X & (1 << N)) == 0 to BT(X, N).
10564 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
10565 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
10566 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
10567 Op1.getOpcode() == ISD::Constant &&
10568 cast<ConstantSDNode>(Op1)->isNullValue() &&
10569 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10570 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
10571 if (NewSetCC.getNode())
10575 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
10577 if (Op1.getOpcode() == ISD::Constant &&
10578 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
10579 cast<ConstantSDNode>(Op1)->isNullValue()) &&
10580 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10582 // If the input is a setcc, then reuse the input setcc or use a new one with
10583 // the inverted condition.
10584 if (Op0.getOpcode() == X86ISD::SETCC) {
10585 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
10586 bool Invert = (CC == ISD::SETNE) ^
10587 cast<ConstantSDNode>(Op1)->isNullValue();
10591 CCode = X86::GetOppositeBranchCondition(CCode);
10592 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10593 DAG.getConstant(CCode, MVT::i8),
10594 Op0.getOperand(1));
10596 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10600 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
10601 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
10602 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10604 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
10605 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
10608 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
10609 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
10610 if (X86CC == X86::COND_INVALID)
10613 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
10614 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
10615 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10616 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
10618 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10622 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10623 static bool isX86LogicalCmp(SDValue Op) {
10624 unsigned Opc = Op.getNode()->getOpcode();
10625 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10626 Opc == X86ISD::SAHF)
10628 if (Op.getResNo() == 1 &&
10629 (Opc == X86ISD::ADD ||
10630 Opc == X86ISD::SUB ||
10631 Opc == X86ISD::ADC ||
10632 Opc == X86ISD::SBB ||
10633 Opc == X86ISD::SMUL ||
10634 Opc == X86ISD::UMUL ||
10635 Opc == X86ISD::INC ||
10636 Opc == X86ISD::DEC ||
10637 Opc == X86ISD::OR ||
10638 Opc == X86ISD::XOR ||
10639 Opc == X86ISD::AND))
10642 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
10648 static bool isZero(SDValue V) {
10649 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10650 return C && C->isNullValue();
10653 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
10654 if (V.getOpcode() != ISD::TRUNCATE)
10657 SDValue VOp0 = V.getOperand(0);
10658 unsigned InBits = VOp0.getValueSizeInBits();
10659 unsigned Bits = V.getValueSizeInBits();
10660 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
10663 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
10664 bool addTest = true;
10665 SDValue Cond = Op.getOperand(0);
10666 SDValue Op1 = Op.getOperand(1);
10667 SDValue Op2 = Op.getOperand(2);
10669 EVT VT = Op1.getValueType();
10672 // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
10673 // are available. Otherwise fp cmovs get lowered into a less efficient branch
10674 // sequence later on.
10675 if (Cond.getOpcode() == ISD::SETCC &&
10676 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
10677 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
10678 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
10679 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
10680 int SSECC = translateX86FSETCC(
10681 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
10684 if (Subtarget->hasAVX512()) {
10685 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
10686 DAG.getConstant(SSECC, MVT::i8));
10687 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
10689 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
10690 DAG.getConstant(SSECC, MVT::i8));
10691 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
10692 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
10693 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
10697 if (Cond.getOpcode() == ISD::SETCC) {
10698 SDValue NewCond = LowerSETCC(Cond, DAG);
10699 if (NewCond.getNode())
10703 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
10704 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
10705 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
10706 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
10707 if (Cond.getOpcode() == X86ISD::SETCC &&
10708 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
10709 isZero(Cond.getOperand(1).getOperand(1))) {
10710 SDValue Cmp = Cond.getOperand(1);
10712 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
10714 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
10715 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
10716 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
10718 SDValue CmpOp0 = Cmp.getOperand(0);
10719 // Apply further optimizations for special cases
10720 // (select (x != 0), -1, 0) -> neg & sbb
10721 // (select (x == 0), 0, -1) -> neg & sbb
10722 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
10723 if (YC->isNullValue() &&
10724 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
10725 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
10726 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
10727 DAG.getConstant(0, CmpOp0.getValueType()),
10729 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10730 DAG.getConstant(X86::COND_B, MVT::i8),
10731 SDValue(Neg.getNode(), 1));
10735 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10736 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10737 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10739 SDValue Res = // Res = 0 or -1.
10740 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10741 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
10743 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
10744 Res = DAG.getNOT(DL, Res, Res.getValueType());
10746 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
10747 if (!N2C || !N2C->isNullValue())
10748 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
10753 // Look past (and (setcc_carry (cmp ...)), 1).
10754 if (Cond.getOpcode() == ISD::AND &&
10755 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10756 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10757 if (C && C->getAPIntValue() == 1)
10758 Cond = Cond.getOperand(0);
10761 // If condition flag is set by a X86ISD::CMP, then use it as the condition
10762 // setting operand in place of the X86ISD::SETCC.
10763 unsigned CondOpcode = Cond.getOpcode();
10764 if (CondOpcode == X86ISD::SETCC ||
10765 CondOpcode == X86ISD::SETCC_CARRY) {
10766 CC = Cond.getOperand(0);
10768 SDValue Cmp = Cond.getOperand(1);
10769 unsigned Opc = Cmp.getOpcode();
10770 MVT VT = Op.getSimpleValueType();
10772 bool IllegalFPCMov = false;
10773 if (VT.isFloatingPoint() && !VT.isVector() &&
10774 !isScalarFPTypeInSSEReg(VT)) // FPStack?
10775 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
10777 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
10778 Opc == X86ISD::BT) { // FIXME
10782 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10783 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10784 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10785 Cond.getOperand(0).getValueType() != MVT::i8)) {
10786 SDValue LHS = Cond.getOperand(0);
10787 SDValue RHS = Cond.getOperand(1);
10788 unsigned X86Opcode;
10791 switch (CondOpcode) {
10792 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10793 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10794 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10795 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10796 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10797 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10798 default: llvm_unreachable("unexpected overflowing operator");
10800 if (CondOpcode == ISD::UMULO)
10801 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10804 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10806 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
10808 if (CondOpcode == ISD::UMULO)
10809 Cond = X86Op.getValue(2);
10811 Cond = X86Op.getValue(1);
10813 CC = DAG.getConstant(X86Cond, MVT::i8);
10818 // Look pass the truncate if the high bits are known zero.
10819 if (isTruncWithZeroHighBitsInput(Cond, DAG))
10820 Cond = Cond.getOperand(0);
10822 // We know the result of AND is compared against zero. Try to match
10824 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10825 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
10826 if (NewSetCC.getNode()) {
10827 CC = NewSetCC.getOperand(0);
10828 Cond = NewSetCC.getOperand(1);
10835 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10836 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
10839 // a < b ? -1 : 0 -> RES = ~setcc_carry
10840 // a < b ? 0 : -1 -> RES = setcc_carry
10841 // a >= b ? -1 : 0 -> RES = setcc_carry
10842 // a >= b ? 0 : -1 -> RES = ~setcc_carry
10843 if (Cond.getOpcode() == X86ISD::SUB) {
10844 Cond = ConvertCmpIfNecessary(Cond, DAG);
10845 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
10847 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
10848 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
10849 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10850 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
10851 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
10852 return DAG.getNOT(DL, Res, Res.getValueType());
10857 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
10858 // widen the cmov and push the truncate through. This avoids introducing a new
10859 // branch during isel and doesn't add any extensions.
10860 if (Op.getValueType() == MVT::i8 &&
10861 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
10862 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
10863 if (T1.getValueType() == T2.getValueType() &&
10864 // Blacklist CopyFromReg to avoid partial register stalls.
10865 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
10866 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
10867 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
10868 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
10872 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
10873 // condition is true.
10874 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
10875 SDValue Ops[] = { Op2, Op1, CC, Cond };
10876 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
10879 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
10880 MVT VT = Op->getSimpleValueType(0);
10881 SDValue In = Op->getOperand(0);
10882 MVT InVT = In.getSimpleValueType();
10885 unsigned int NumElts = VT.getVectorNumElements();
10886 if (NumElts != 8 && NumElts != 16)
10889 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
10890 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10892 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10893 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
10895 MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
10896 Constant *C = ConstantInt::get(*DAG.getContext(),
10897 APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
10899 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
10900 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
10901 SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
10902 MachinePointerInfo::getConstantPool(),
10903 false, false, false, Alignment);
10904 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
10905 if (VT.is512BitVector())
10907 return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
10910 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
10911 SelectionDAG &DAG) {
10912 MVT VT = Op->getSimpleValueType(0);
10913 SDValue In = Op->getOperand(0);
10914 MVT InVT = In.getSimpleValueType();
10917 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
10918 return LowerSIGN_EXTEND_AVX512(Op, DAG);
10920 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
10921 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
10922 (VT != MVT::v16i16 || InVT != MVT::v16i8))
10925 if (Subtarget->hasInt256())
10926 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10928 // Optimize vectors in AVX mode
10929 // Sign extend v8i16 to v8i32 and
10932 // Divide input vector into two parts
10933 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
10934 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
10935 // concat the vectors to original VT
10937 unsigned NumElems = InVT.getVectorNumElements();
10938 SDValue Undef = DAG.getUNDEF(InVT);
10940 SmallVector<int,8> ShufMask1(NumElems, -1);
10941 for (unsigned i = 0; i != NumElems/2; ++i)
10944 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
10946 SmallVector<int,8> ShufMask2(NumElems, -1);
10947 for (unsigned i = 0; i != NumElems/2; ++i)
10948 ShufMask2[i] = i + NumElems/2;
10950 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
10952 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
10953 VT.getVectorNumElements()/2);
10955 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
10956 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
10958 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
10961 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
10962 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
10963 // from the AND / OR.
10964 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
10965 Opc = Op.getOpcode();
10966 if (Opc != ISD::OR && Opc != ISD::AND)
10968 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10969 Op.getOperand(0).hasOneUse() &&
10970 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
10971 Op.getOperand(1).hasOneUse());
10974 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
10975 // 1 and that the SETCC node has a single use.
10976 static bool isXor1OfSetCC(SDValue Op) {
10977 if (Op.getOpcode() != ISD::XOR)
10979 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10980 if (N1C && N1C->getAPIntValue() == 1) {
10981 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10982 Op.getOperand(0).hasOneUse();
10987 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
10988 bool addTest = true;
10989 SDValue Chain = Op.getOperand(0);
10990 SDValue Cond = Op.getOperand(1);
10991 SDValue Dest = Op.getOperand(2);
10994 bool Inverted = false;
10996 if (Cond.getOpcode() == ISD::SETCC) {
10997 // Check for setcc([su]{add,sub,mul}o == 0).
10998 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
10999 isa<ConstantSDNode>(Cond.getOperand(1)) &&
11000 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
11001 Cond.getOperand(0).getResNo() == 1 &&
11002 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
11003 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
11004 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
11005 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
11006 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
11007 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
11009 Cond = Cond.getOperand(0);
11011 SDValue NewCond = LowerSETCC(Cond, DAG);
11012 if (NewCond.getNode())
11017 // FIXME: LowerXALUO doesn't handle these!!
11018 else if (Cond.getOpcode() == X86ISD::ADD ||
11019 Cond.getOpcode() == X86ISD::SUB ||
11020 Cond.getOpcode() == X86ISD::SMUL ||
11021 Cond.getOpcode() == X86ISD::UMUL)
11022 Cond = LowerXALUO(Cond, DAG);
11025 // Look pass (and (setcc_carry (cmp ...)), 1).
11026 if (Cond.getOpcode() == ISD::AND &&
11027 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
11028 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11029 if (C && C->getAPIntValue() == 1)
11030 Cond = Cond.getOperand(0);
11033 // If condition flag is set by a X86ISD::CMP, then use it as the condition
11034 // setting operand in place of the X86ISD::SETCC.
11035 unsigned CondOpcode = Cond.getOpcode();
11036 if (CondOpcode == X86ISD::SETCC ||
11037 CondOpcode == X86ISD::SETCC_CARRY) {
11038 CC = Cond.getOperand(0);
11040 SDValue Cmp = Cond.getOperand(1);
11041 unsigned Opc = Cmp.getOpcode();
11042 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
11043 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
11047 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
11051 // These can only come from an arithmetic instruction with overflow,
11052 // e.g. SADDO, UADDO.
11053 Cond = Cond.getNode()->getOperand(1);
11059 CondOpcode = Cond.getOpcode();
11060 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11061 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11062 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11063 Cond.getOperand(0).getValueType() != MVT::i8)) {
11064 SDValue LHS = Cond.getOperand(0);
11065 SDValue RHS = Cond.getOperand(1);
11066 unsigned X86Opcode;
11069 // Keep this in sync with LowerXALUO, otherwise we might create redundant
11070 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
11072 switch (CondOpcode) {
11073 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11075 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11077 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
11080 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11081 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11083 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11085 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
11088 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11089 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11090 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11091 default: llvm_unreachable("unexpected overflowing operator");
11094 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
11095 if (CondOpcode == ISD::UMULO)
11096 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11099 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11101 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
11103 if (CondOpcode == ISD::UMULO)
11104 Cond = X86Op.getValue(2);
11106 Cond = X86Op.getValue(1);
11108 CC = DAG.getConstant(X86Cond, MVT::i8);
11112 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
11113 SDValue Cmp = Cond.getOperand(0).getOperand(1);
11114 if (CondOpc == ISD::OR) {
11115 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
11116 // two branches instead of an explicit OR instruction with a
11118 if (Cmp == Cond.getOperand(1).getOperand(1) &&
11119 isX86LogicalCmp(Cmp)) {
11120 CC = Cond.getOperand(0).getOperand(0);
11121 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11122 Chain, Dest, CC, Cmp);
11123 CC = Cond.getOperand(1).getOperand(0);
11127 } else { // ISD::AND
11128 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
11129 // two branches instead of an explicit AND instruction with a
11130 // separate test. However, we only do this if this block doesn't
11131 // have a fall-through edge, because this requires an explicit
11132 // jmp when the condition is false.
11133 if (Cmp == Cond.getOperand(1).getOperand(1) &&
11134 isX86LogicalCmp(Cmp) &&
11135 Op.getNode()->hasOneUse()) {
11136 X86::CondCode CCode =
11137 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11138 CCode = X86::GetOppositeBranchCondition(CCode);
11139 CC = DAG.getConstant(CCode, MVT::i8);
11140 SDNode *User = *Op.getNode()->use_begin();
11141 // Look for an unconditional branch following this conditional branch.
11142 // We need this because we need to reverse the successors in order
11143 // to implement FCMP_OEQ.
11144 if (User->getOpcode() == ISD::BR) {
11145 SDValue FalseBB = User->getOperand(1);
11147 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11148 assert(NewBR == User);
11152 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11153 Chain, Dest, CC, Cmp);
11154 X86::CondCode CCode =
11155 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
11156 CCode = X86::GetOppositeBranchCondition(CCode);
11157 CC = DAG.getConstant(CCode, MVT::i8);
11163 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
11164 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
11165 // It should be transformed during dag combiner except when the condition
11166 // is set by a arithmetics with overflow node.
11167 X86::CondCode CCode =
11168 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11169 CCode = X86::GetOppositeBranchCondition(CCode);
11170 CC = DAG.getConstant(CCode, MVT::i8);
11171 Cond = Cond.getOperand(0).getOperand(1);
11173 } else if (Cond.getOpcode() == ISD::SETCC &&
11174 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
11175 // For FCMP_OEQ, we can emit
11176 // two branches instead of an explicit AND instruction with a
11177 // separate test. However, we only do this if this block doesn't
11178 // have a fall-through edge, because this requires an explicit
11179 // jmp when the condition is false.
11180 if (Op.getNode()->hasOneUse()) {
11181 SDNode *User = *Op.getNode()->use_begin();
11182 // Look for an unconditional branch following this conditional branch.
11183 // We need this because we need to reverse the successors in order
11184 // to implement FCMP_OEQ.
11185 if (User->getOpcode() == ISD::BR) {
11186 SDValue FalseBB = User->getOperand(1);
11188 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11189 assert(NewBR == User);
11193 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11194 Cond.getOperand(0), Cond.getOperand(1));
11195 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11196 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11197 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11198 Chain, Dest, CC, Cmp);
11199 CC = DAG.getConstant(X86::COND_P, MVT::i8);
11204 } else if (Cond.getOpcode() == ISD::SETCC &&
11205 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
11206 // For FCMP_UNE, we can emit
11207 // two branches instead of an explicit AND instruction with a
11208 // separate test. However, we only do this if this block doesn't
11209 // have a fall-through edge, because this requires an explicit
11210 // jmp when the condition is false.
11211 if (Op.getNode()->hasOneUse()) {
11212 SDNode *User = *Op.getNode()->use_begin();
11213 // Look for an unconditional branch following this conditional branch.
11214 // We need this because we need to reverse the successors in order
11215 // to implement FCMP_UNE.
11216 if (User->getOpcode() == ISD::BR) {
11217 SDValue FalseBB = User->getOperand(1);
11219 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11220 assert(NewBR == User);
11223 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11224 Cond.getOperand(0), Cond.getOperand(1));
11225 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11226 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11227 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11228 Chain, Dest, CC, Cmp);
11229 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
11239 // Look pass the truncate if the high bits are known zero.
11240 if (isTruncWithZeroHighBitsInput(Cond, DAG))
11241 Cond = Cond.getOperand(0);
11243 // We know the result of AND is compared against zero. Try to match
11245 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11246 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
11247 if (NewSetCC.getNode()) {
11248 CC = NewSetCC.getOperand(0);
11249 Cond = NewSetCC.getOperand(1);
11256 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11257 Cond = EmitTest(Cond, X86::COND_NE, dl, DAG);
11259 Cond = ConvertCmpIfNecessary(Cond, DAG);
11260 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11261 Chain, Dest, CC, Cond);
11264 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
11265 // Calls to _alloca is needed to probe the stack when allocating more than 4k
11266 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
11267 // that the guard pages used by the OS virtual memory manager are allocated in
11268 // correct sequence.
11270 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
11271 SelectionDAG &DAG) const {
11272 MachineFunction &MF = DAG.getMachineFunction();
11273 bool SplitStack = MF.shouldSplitStack();
11274 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
11279 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11280 SDNode* Node = Op.getNode();
11282 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
11283 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
11284 " not tell us which reg is the stack pointer!");
11285 EVT VT = Node->getValueType(0);
11286 SDValue Tmp1 = SDValue(Node, 0);
11287 SDValue Tmp2 = SDValue(Node, 1);
11288 SDValue Tmp3 = Node->getOperand(2);
11289 SDValue Chain = Tmp1.getOperand(0);
11291 // Chain the dynamic stack allocation so that it doesn't modify the stack
11292 // pointer when other instructions are using the stack.
11293 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
11296 SDValue Size = Tmp2.getOperand(1);
11297 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
11298 Chain = SP.getValue(1);
11299 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
11300 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
11301 unsigned StackAlign = TFI.getStackAlignment();
11302 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
11303 if (Align > StackAlign)
11304 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
11305 DAG.getConstant(-(uint64_t)Align, VT));
11306 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
11308 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
11309 DAG.getIntPtrConstant(0, true), SDValue(),
11312 SDValue Ops[2] = { Tmp1, Tmp2 };
11313 return DAG.getMergeValues(Ops, dl);
11317 SDValue Chain = Op.getOperand(0);
11318 SDValue Size = Op.getOperand(1);
11319 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11320 EVT VT = Op.getNode()->getValueType(0);
11322 bool Is64Bit = Subtarget->is64Bit();
11323 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
11326 MachineRegisterInfo &MRI = MF.getRegInfo();
11329 // The 64 bit implementation of segmented stacks needs to clobber both r10
11330 // r11. This makes it impossible to use it along with nested parameters.
11331 const Function *F = MF.getFunction();
11333 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
11335 if (I->hasNestAttr())
11336 report_fatal_error("Cannot use segmented stacks with functions that "
11337 "have nested arguments.");
11340 const TargetRegisterClass *AddrRegClass =
11341 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
11342 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
11343 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
11344 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
11345 DAG.getRegister(Vreg, SPTy));
11346 SDValue Ops1[2] = { Value, Chain };
11347 return DAG.getMergeValues(Ops1, dl);
11350 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
11352 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
11353 Flag = Chain.getValue(1);
11354 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11356 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
11358 const X86RegisterInfo *RegInfo =
11359 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11360 unsigned SPReg = RegInfo->getStackRegister();
11361 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
11362 Chain = SP.getValue(1);
11365 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11366 DAG.getConstant(-(uint64_t)Align, VT));
11367 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
11370 SDValue Ops1[2] = { SP, Chain };
11371 return DAG.getMergeValues(Ops1, dl);
11375 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
11376 MachineFunction &MF = DAG.getMachineFunction();
11377 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
11379 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11382 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
11383 // vastart just stores the address of the VarArgsFrameIndex slot into the
11384 // memory location argument.
11385 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11387 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
11388 MachinePointerInfo(SV), false, false, 0);
11392 // gp_offset (0 - 6 * 8)
11393 // fp_offset (48 - 48 + 8 * 16)
11394 // overflow_arg_area (point to parameters coming in memory).
11396 SmallVector<SDValue, 8> MemOps;
11397 SDValue FIN = Op.getOperand(1);
11399 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
11400 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
11402 FIN, MachinePointerInfo(SV), false, false, 0);
11403 MemOps.push_back(Store);
11406 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11407 FIN, DAG.getIntPtrConstant(4));
11408 Store = DAG.getStore(Op.getOperand(0), DL,
11409 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
11411 FIN, MachinePointerInfo(SV, 4), false, false, 0);
11412 MemOps.push_back(Store);
11414 // Store ptr to overflow_arg_area
11415 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11416 FIN, DAG.getIntPtrConstant(4));
11417 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11419 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11420 MachinePointerInfo(SV, 8),
11422 MemOps.push_back(Store);
11424 // Store ptr to reg_save_area.
11425 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11426 FIN, DAG.getIntPtrConstant(8));
11427 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11429 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11430 MachinePointerInfo(SV, 16), false, false, 0);
11431 MemOps.push_back(Store);
11432 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
11435 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11436 assert(Subtarget->is64Bit() &&
11437 "LowerVAARG only handles 64-bit va_arg!");
11438 assert((Subtarget->isTargetLinux() ||
11439 Subtarget->isTargetDarwin()) &&
11440 "Unhandled target in LowerVAARG");
11441 assert(Op.getNode()->getNumOperands() == 4);
11442 SDValue Chain = Op.getOperand(0);
11443 SDValue SrcPtr = Op.getOperand(1);
11444 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11445 unsigned Align = Op.getConstantOperandVal(3);
11448 EVT ArgVT = Op.getNode()->getValueType(0);
11449 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11450 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11453 // Decide which area this value should be read from.
11454 // TODO: Implement the AMD64 ABI in its entirety. This simple
11455 // selection mechanism works only for the basic types.
11456 if (ArgVT == MVT::f80) {
11457 llvm_unreachable("va_arg for f80 not yet implemented");
11458 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11459 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
11460 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11461 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
11463 llvm_unreachable("Unhandled argument type in LowerVAARG");
11466 if (ArgMode == 2) {
11467 // Sanity Check: Make sure using fp_offset makes sense.
11468 assert(!getTargetMachine().Options.UseSoftFloat &&
11469 !(DAG.getMachineFunction()
11470 .getFunction()->getAttributes()
11471 .hasAttribute(AttributeSet::FunctionIndex,
11472 Attribute::NoImplicitFloat)) &&
11473 Subtarget->hasSSE1());
11476 // Insert VAARG_64 node into the DAG
11477 // VAARG_64 returns two values: Variable Argument Address, Chain
11478 SmallVector<SDValue, 11> InstOps;
11479 InstOps.push_back(Chain);
11480 InstOps.push_back(SrcPtr);
11481 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11482 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11483 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11484 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11485 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11486 VTs, InstOps, MVT::i64,
11487 MachinePointerInfo(SV),
11489 /*Volatile=*/false,
11491 /*WriteMem=*/true);
11492 Chain = VAARG.getValue(1);
11494 // Load the next argument and return it
11495 return DAG.getLoad(ArgVT, dl,
11498 MachinePointerInfo(),
11499 false, false, false, 0);
11502 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11503 SelectionDAG &DAG) {
11504 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
11505 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
11506 SDValue Chain = Op.getOperand(0);
11507 SDValue DstPtr = Op.getOperand(1);
11508 SDValue SrcPtr = Op.getOperand(2);
11509 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
11510 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11513 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
11514 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
11516 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
11519 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
11520 // amount is a constant. Takes immediate version of shift as input.
11521 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
11522 SDValue SrcOp, uint64_t ShiftAmt,
11523 SelectionDAG &DAG) {
11524 MVT ElementType = VT.getVectorElementType();
11526 // Check for ShiftAmt >= element width
11527 if (ShiftAmt >= ElementType.getSizeInBits()) {
11528 if (Opc == X86ISD::VSRAI)
11529 ShiftAmt = ElementType.getSizeInBits() - 1;
11531 return DAG.getConstant(0, VT);
11534 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
11535 && "Unknown target vector shift-by-constant node");
11537 // Fold this packed vector shift into a build vector if SrcOp is a
11538 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
11539 if (VT == SrcOp.getSimpleValueType() &&
11540 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
11541 SmallVector<SDValue, 8> Elts;
11542 unsigned NumElts = SrcOp->getNumOperands();
11543 ConstantSDNode *ND;
11546 default: llvm_unreachable(nullptr);
11547 case X86ISD::VSHLI:
11548 for (unsigned i=0; i!=NumElts; ++i) {
11549 SDValue CurrentOp = SrcOp->getOperand(i);
11550 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11551 Elts.push_back(CurrentOp);
11554 ND = cast<ConstantSDNode>(CurrentOp);
11555 const APInt &C = ND->getAPIntValue();
11556 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
11559 case X86ISD::VSRLI:
11560 for (unsigned i=0; i!=NumElts; ++i) {
11561 SDValue CurrentOp = SrcOp->getOperand(i);
11562 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11563 Elts.push_back(CurrentOp);
11566 ND = cast<ConstantSDNode>(CurrentOp);
11567 const APInt &C = ND->getAPIntValue();
11568 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
11571 case X86ISD::VSRAI:
11572 for (unsigned i=0; i!=NumElts; ++i) {
11573 SDValue CurrentOp = SrcOp->getOperand(i);
11574 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11575 Elts.push_back(CurrentOp);
11578 ND = cast<ConstantSDNode>(CurrentOp);
11579 const APInt &C = ND->getAPIntValue();
11580 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
11585 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
11588 return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
11591 // getTargetVShiftNode - Handle vector element shifts where the shift amount
11592 // may or may not be a constant. Takes immediate version of shift as input.
11593 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
11594 SDValue SrcOp, SDValue ShAmt,
11595 SelectionDAG &DAG) {
11596 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
11598 // Catch shift-by-constant.
11599 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
11600 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
11601 CShAmt->getZExtValue(), DAG);
11603 // Change opcode to non-immediate version
11605 default: llvm_unreachable("Unknown target vector shift node");
11606 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
11607 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
11608 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
11611 // Need to build a vector containing shift amount
11612 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
11615 ShOps[1] = DAG.getConstant(0, MVT::i32);
11616 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
11617 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
11619 // The return type has to be a 128-bit type with the same element
11620 // type as the input type.
11621 MVT EltVT = VT.getVectorElementType();
11622 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
11624 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
11625 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
11628 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
11630 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11632 default: return SDValue(); // Don't custom lower most intrinsics.
11633 // Comparison intrinsics.
11634 case Intrinsic::x86_sse_comieq_ss:
11635 case Intrinsic::x86_sse_comilt_ss:
11636 case Intrinsic::x86_sse_comile_ss:
11637 case Intrinsic::x86_sse_comigt_ss:
11638 case Intrinsic::x86_sse_comige_ss:
11639 case Intrinsic::x86_sse_comineq_ss:
11640 case Intrinsic::x86_sse_ucomieq_ss:
11641 case Intrinsic::x86_sse_ucomilt_ss:
11642 case Intrinsic::x86_sse_ucomile_ss:
11643 case Intrinsic::x86_sse_ucomigt_ss:
11644 case Intrinsic::x86_sse_ucomige_ss:
11645 case Intrinsic::x86_sse_ucomineq_ss:
11646 case Intrinsic::x86_sse2_comieq_sd:
11647 case Intrinsic::x86_sse2_comilt_sd:
11648 case Intrinsic::x86_sse2_comile_sd:
11649 case Intrinsic::x86_sse2_comigt_sd:
11650 case Intrinsic::x86_sse2_comige_sd:
11651 case Intrinsic::x86_sse2_comineq_sd:
11652 case Intrinsic::x86_sse2_ucomieq_sd:
11653 case Intrinsic::x86_sse2_ucomilt_sd:
11654 case Intrinsic::x86_sse2_ucomile_sd:
11655 case Intrinsic::x86_sse2_ucomigt_sd:
11656 case Intrinsic::x86_sse2_ucomige_sd:
11657 case Intrinsic::x86_sse2_ucomineq_sd: {
11661 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11662 case Intrinsic::x86_sse_comieq_ss:
11663 case Intrinsic::x86_sse2_comieq_sd:
11664 Opc = X86ISD::COMI;
11667 case Intrinsic::x86_sse_comilt_ss:
11668 case Intrinsic::x86_sse2_comilt_sd:
11669 Opc = X86ISD::COMI;
11672 case Intrinsic::x86_sse_comile_ss:
11673 case Intrinsic::x86_sse2_comile_sd:
11674 Opc = X86ISD::COMI;
11677 case Intrinsic::x86_sse_comigt_ss:
11678 case Intrinsic::x86_sse2_comigt_sd:
11679 Opc = X86ISD::COMI;
11682 case Intrinsic::x86_sse_comige_ss:
11683 case Intrinsic::x86_sse2_comige_sd:
11684 Opc = X86ISD::COMI;
11687 case Intrinsic::x86_sse_comineq_ss:
11688 case Intrinsic::x86_sse2_comineq_sd:
11689 Opc = X86ISD::COMI;
11692 case Intrinsic::x86_sse_ucomieq_ss:
11693 case Intrinsic::x86_sse2_ucomieq_sd:
11694 Opc = X86ISD::UCOMI;
11697 case Intrinsic::x86_sse_ucomilt_ss:
11698 case Intrinsic::x86_sse2_ucomilt_sd:
11699 Opc = X86ISD::UCOMI;
11702 case Intrinsic::x86_sse_ucomile_ss:
11703 case Intrinsic::x86_sse2_ucomile_sd:
11704 Opc = X86ISD::UCOMI;
11707 case Intrinsic::x86_sse_ucomigt_ss:
11708 case Intrinsic::x86_sse2_ucomigt_sd:
11709 Opc = X86ISD::UCOMI;
11712 case Intrinsic::x86_sse_ucomige_ss:
11713 case Intrinsic::x86_sse2_ucomige_sd:
11714 Opc = X86ISD::UCOMI;
11717 case Intrinsic::x86_sse_ucomineq_ss:
11718 case Intrinsic::x86_sse2_ucomineq_sd:
11719 Opc = X86ISD::UCOMI;
11724 SDValue LHS = Op.getOperand(1);
11725 SDValue RHS = Op.getOperand(2);
11726 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
11727 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
11728 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
11729 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11730 DAG.getConstant(X86CC, MVT::i8), Cond);
11731 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11734 // Arithmetic intrinsics.
11735 case Intrinsic::x86_sse2_pmulu_dq:
11736 case Intrinsic::x86_avx2_pmulu_dq:
11737 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
11738 Op.getOperand(1), Op.getOperand(2));
11740 case Intrinsic::x86_sse41_pmuldq:
11741 case Intrinsic::x86_avx2_pmul_dq:
11742 return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
11743 Op.getOperand(1), Op.getOperand(2));
11745 case Intrinsic::x86_sse2_pmulhu_w:
11746 case Intrinsic::x86_avx2_pmulhu_w:
11747 return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
11748 Op.getOperand(1), Op.getOperand(2));
11750 case Intrinsic::x86_sse2_pmulh_w:
11751 case Intrinsic::x86_avx2_pmulh_w:
11752 return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
11753 Op.getOperand(1), Op.getOperand(2));
11755 // SSE2/AVX2 sub with unsigned saturation intrinsics
11756 case Intrinsic::x86_sse2_psubus_b:
11757 case Intrinsic::x86_sse2_psubus_w:
11758 case Intrinsic::x86_avx2_psubus_b:
11759 case Intrinsic::x86_avx2_psubus_w:
11760 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
11761 Op.getOperand(1), Op.getOperand(2));
11763 // SSE3/AVX horizontal add/sub intrinsics
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 case Intrinsic::x86_sse3_hsub_ps:
11769 case Intrinsic::x86_sse3_hsub_pd:
11770 case Intrinsic::x86_avx_hsub_ps_256:
11771 case Intrinsic::x86_avx_hsub_pd_256:
11772 case Intrinsic::x86_ssse3_phadd_w_128:
11773 case Intrinsic::x86_ssse3_phadd_d_128:
11774 case Intrinsic::x86_avx2_phadd_w:
11775 case Intrinsic::x86_avx2_phadd_d:
11776 case Intrinsic::x86_ssse3_phsub_w_128:
11777 case Intrinsic::x86_ssse3_phsub_d_128:
11778 case Intrinsic::x86_avx2_phsub_w:
11779 case Intrinsic::x86_avx2_phsub_d: {
11782 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11783 case Intrinsic::x86_sse3_hadd_ps:
11784 case Intrinsic::x86_sse3_hadd_pd:
11785 case Intrinsic::x86_avx_hadd_ps_256:
11786 case Intrinsic::x86_avx_hadd_pd_256:
11787 Opcode = X86ISD::FHADD;
11789 case Intrinsic::x86_sse3_hsub_ps:
11790 case Intrinsic::x86_sse3_hsub_pd:
11791 case Intrinsic::x86_avx_hsub_ps_256:
11792 case Intrinsic::x86_avx_hsub_pd_256:
11793 Opcode = X86ISD::FHSUB;
11795 case Intrinsic::x86_ssse3_phadd_w_128:
11796 case Intrinsic::x86_ssse3_phadd_d_128:
11797 case Intrinsic::x86_avx2_phadd_w:
11798 case Intrinsic::x86_avx2_phadd_d:
11799 Opcode = X86ISD::HADD;
11801 case Intrinsic::x86_ssse3_phsub_w_128:
11802 case Intrinsic::x86_ssse3_phsub_d_128:
11803 case Intrinsic::x86_avx2_phsub_w:
11804 case Intrinsic::x86_avx2_phsub_d:
11805 Opcode = X86ISD::HSUB;
11808 return DAG.getNode(Opcode, dl, Op.getValueType(),
11809 Op.getOperand(1), Op.getOperand(2));
11812 // SSE2/SSE41/AVX2 integer max/min intrinsics.
11813 case Intrinsic::x86_sse2_pmaxu_b:
11814 case Intrinsic::x86_sse41_pmaxuw:
11815 case Intrinsic::x86_sse41_pmaxud:
11816 case Intrinsic::x86_avx2_pmaxu_b:
11817 case Intrinsic::x86_avx2_pmaxu_w:
11818 case Intrinsic::x86_avx2_pmaxu_d:
11819 case Intrinsic::x86_sse2_pminu_b:
11820 case Intrinsic::x86_sse41_pminuw:
11821 case Intrinsic::x86_sse41_pminud:
11822 case Intrinsic::x86_avx2_pminu_b:
11823 case Intrinsic::x86_avx2_pminu_w:
11824 case Intrinsic::x86_avx2_pminu_d:
11825 case Intrinsic::x86_sse41_pmaxsb:
11826 case Intrinsic::x86_sse2_pmaxs_w:
11827 case Intrinsic::x86_sse41_pmaxsd:
11828 case Intrinsic::x86_avx2_pmaxs_b:
11829 case Intrinsic::x86_avx2_pmaxs_w:
11830 case Intrinsic::x86_avx2_pmaxs_d:
11831 case Intrinsic::x86_sse41_pminsb:
11832 case Intrinsic::x86_sse2_pmins_w:
11833 case Intrinsic::x86_sse41_pminsd:
11834 case Intrinsic::x86_avx2_pmins_b:
11835 case Intrinsic::x86_avx2_pmins_w:
11836 case Intrinsic::x86_avx2_pmins_d: {
11839 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11840 case Intrinsic::x86_sse2_pmaxu_b:
11841 case Intrinsic::x86_sse41_pmaxuw:
11842 case Intrinsic::x86_sse41_pmaxud:
11843 case Intrinsic::x86_avx2_pmaxu_b:
11844 case Intrinsic::x86_avx2_pmaxu_w:
11845 case Intrinsic::x86_avx2_pmaxu_d:
11846 Opcode = X86ISD::UMAX;
11848 case Intrinsic::x86_sse2_pminu_b:
11849 case Intrinsic::x86_sse41_pminuw:
11850 case Intrinsic::x86_sse41_pminud:
11851 case Intrinsic::x86_avx2_pminu_b:
11852 case Intrinsic::x86_avx2_pminu_w:
11853 case Intrinsic::x86_avx2_pminu_d:
11854 Opcode = X86ISD::UMIN;
11856 case Intrinsic::x86_sse41_pmaxsb:
11857 case Intrinsic::x86_sse2_pmaxs_w:
11858 case Intrinsic::x86_sse41_pmaxsd:
11859 case Intrinsic::x86_avx2_pmaxs_b:
11860 case Intrinsic::x86_avx2_pmaxs_w:
11861 case Intrinsic::x86_avx2_pmaxs_d:
11862 Opcode = X86ISD::SMAX;
11864 case Intrinsic::x86_sse41_pminsb:
11865 case Intrinsic::x86_sse2_pmins_w:
11866 case Intrinsic::x86_sse41_pminsd:
11867 case Intrinsic::x86_avx2_pmins_b:
11868 case Intrinsic::x86_avx2_pmins_w:
11869 case Intrinsic::x86_avx2_pmins_d:
11870 Opcode = X86ISD::SMIN;
11873 return DAG.getNode(Opcode, dl, Op.getValueType(),
11874 Op.getOperand(1), Op.getOperand(2));
11877 // SSE/SSE2/AVX floating point max/min intrinsics.
11878 case Intrinsic::x86_sse_max_ps:
11879 case Intrinsic::x86_sse2_max_pd:
11880 case Intrinsic::x86_avx_max_ps_256:
11881 case Intrinsic::x86_avx_max_pd_256:
11882 case Intrinsic::x86_sse_min_ps:
11883 case Intrinsic::x86_sse2_min_pd:
11884 case Intrinsic::x86_avx_min_ps_256:
11885 case Intrinsic::x86_avx_min_pd_256: {
11888 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11889 case Intrinsic::x86_sse_max_ps:
11890 case Intrinsic::x86_sse2_max_pd:
11891 case Intrinsic::x86_avx_max_ps_256:
11892 case Intrinsic::x86_avx_max_pd_256:
11893 Opcode = X86ISD::FMAX;
11895 case Intrinsic::x86_sse_min_ps:
11896 case Intrinsic::x86_sse2_min_pd:
11897 case Intrinsic::x86_avx_min_ps_256:
11898 case Intrinsic::x86_avx_min_pd_256:
11899 Opcode = X86ISD::FMIN;
11902 return DAG.getNode(Opcode, dl, Op.getValueType(),
11903 Op.getOperand(1), Op.getOperand(2));
11906 // AVX2 variable shift intrinsics
11907 case Intrinsic::x86_avx2_psllv_d:
11908 case Intrinsic::x86_avx2_psllv_q:
11909 case Intrinsic::x86_avx2_psllv_d_256:
11910 case Intrinsic::x86_avx2_psllv_q_256:
11911 case Intrinsic::x86_avx2_psrlv_d:
11912 case Intrinsic::x86_avx2_psrlv_q:
11913 case Intrinsic::x86_avx2_psrlv_d_256:
11914 case Intrinsic::x86_avx2_psrlv_q_256:
11915 case Intrinsic::x86_avx2_psrav_d:
11916 case Intrinsic::x86_avx2_psrav_d_256: {
11919 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11920 case Intrinsic::x86_avx2_psllv_d:
11921 case Intrinsic::x86_avx2_psllv_q:
11922 case Intrinsic::x86_avx2_psllv_d_256:
11923 case Intrinsic::x86_avx2_psllv_q_256:
11926 case Intrinsic::x86_avx2_psrlv_d:
11927 case Intrinsic::x86_avx2_psrlv_q:
11928 case Intrinsic::x86_avx2_psrlv_d_256:
11929 case Intrinsic::x86_avx2_psrlv_q_256:
11932 case Intrinsic::x86_avx2_psrav_d:
11933 case Intrinsic::x86_avx2_psrav_d_256:
11937 return DAG.getNode(Opcode, dl, Op.getValueType(),
11938 Op.getOperand(1), Op.getOperand(2));
11941 case Intrinsic::x86_ssse3_pshuf_b_128:
11942 case Intrinsic::x86_avx2_pshuf_b:
11943 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
11944 Op.getOperand(1), Op.getOperand(2));
11946 case Intrinsic::x86_ssse3_psign_b_128:
11947 case Intrinsic::x86_ssse3_psign_w_128:
11948 case Intrinsic::x86_ssse3_psign_d_128:
11949 case Intrinsic::x86_avx2_psign_b:
11950 case Intrinsic::x86_avx2_psign_w:
11951 case Intrinsic::x86_avx2_psign_d:
11952 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
11953 Op.getOperand(1), Op.getOperand(2));
11955 case Intrinsic::x86_sse41_insertps:
11956 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
11957 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11959 case Intrinsic::x86_avx_vperm2f128_ps_256:
11960 case Intrinsic::x86_avx_vperm2f128_pd_256:
11961 case Intrinsic::x86_avx_vperm2f128_si_256:
11962 case Intrinsic::x86_avx2_vperm2i128:
11963 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
11964 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11966 case Intrinsic::x86_avx2_permd:
11967 case Intrinsic::x86_avx2_permps:
11968 // Operands intentionally swapped. Mask is last operand to intrinsic,
11969 // but second operand for node/instruction.
11970 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
11971 Op.getOperand(2), Op.getOperand(1));
11973 case Intrinsic::x86_sse_sqrt_ps:
11974 case Intrinsic::x86_sse2_sqrt_pd:
11975 case Intrinsic::x86_avx_sqrt_ps_256:
11976 case Intrinsic::x86_avx_sqrt_pd_256:
11977 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
11979 // ptest and testp intrinsics. The intrinsic these come from are designed to
11980 // return an integer value, not just an instruction so lower it to the ptest
11981 // or testp pattern and a setcc for the result.
11982 case Intrinsic::x86_sse41_ptestz:
11983 case Intrinsic::x86_sse41_ptestc:
11984 case Intrinsic::x86_sse41_ptestnzc:
11985 case Intrinsic::x86_avx_ptestz_256:
11986 case Intrinsic::x86_avx_ptestc_256:
11987 case Intrinsic::x86_avx_ptestnzc_256:
11988 case Intrinsic::x86_avx_vtestz_ps:
11989 case Intrinsic::x86_avx_vtestc_ps:
11990 case Intrinsic::x86_avx_vtestnzc_ps:
11991 case Intrinsic::x86_avx_vtestz_pd:
11992 case Intrinsic::x86_avx_vtestc_pd:
11993 case Intrinsic::x86_avx_vtestnzc_pd:
11994 case Intrinsic::x86_avx_vtestz_ps_256:
11995 case Intrinsic::x86_avx_vtestc_ps_256:
11996 case Intrinsic::x86_avx_vtestnzc_ps_256:
11997 case Intrinsic::x86_avx_vtestz_pd_256:
11998 case Intrinsic::x86_avx_vtestc_pd_256:
11999 case Intrinsic::x86_avx_vtestnzc_pd_256: {
12000 bool IsTestPacked = false;
12003 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
12004 case Intrinsic::x86_avx_vtestz_ps:
12005 case Intrinsic::x86_avx_vtestz_pd:
12006 case Intrinsic::x86_avx_vtestz_ps_256:
12007 case Intrinsic::x86_avx_vtestz_pd_256:
12008 IsTestPacked = true; // Fallthrough
12009 case Intrinsic::x86_sse41_ptestz:
12010 case Intrinsic::x86_avx_ptestz_256:
12012 X86CC = X86::COND_E;
12014 case Intrinsic::x86_avx_vtestc_ps:
12015 case Intrinsic::x86_avx_vtestc_pd:
12016 case Intrinsic::x86_avx_vtestc_ps_256:
12017 case Intrinsic::x86_avx_vtestc_pd_256:
12018 IsTestPacked = true; // Fallthrough
12019 case Intrinsic::x86_sse41_ptestc:
12020 case Intrinsic::x86_avx_ptestc_256:
12022 X86CC = X86::COND_B;
12024 case Intrinsic::x86_avx_vtestnzc_ps:
12025 case Intrinsic::x86_avx_vtestnzc_pd:
12026 case Intrinsic::x86_avx_vtestnzc_ps_256:
12027 case Intrinsic::x86_avx_vtestnzc_pd_256:
12028 IsTestPacked = true; // Fallthrough
12029 case Intrinsic::x86_sse41_ptestnzc:
12030 case Intrinsic::x86_avx_ptestnzc_256:
12032 X86CC = X86::COND_A;
12036 SDValue LHS = Op.getOperand(1);
12037 SDValue RHS = Op.getOperand(2);
12038 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
12039 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
12040 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12041 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
12042 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12044 case Intrinsic::x86_avx512_kortestz_w:
12045 case Intrinsic::x86_avx512_kortestc_w: {
12046 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
12047 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
12048 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
12049 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12050 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
12051 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
12052 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12055 // SSE/AVX shift intrinsics
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 case Intrinsic::x86_sse2_psrl_w:
12063 case Intrinsic::x86_sse2_psrl_d:
12064 case Intrinsic::x86_sse2_psrl_q:
12065 case Intrinsic::x86_avx2_psrl_w:
12066 case Intrinsic::x86_avx2_psrl_d:
12067 case Intrinsic::x86_avx2_psrl_q:
12068 case Intrinsic::x86_sse2_psra_w:
12069 case Intrinsic::x86_sse2_psra_d:
12070 case Intrinsic::x86_avx2_psra_w:
12071 case Intrinsic::x86_avx2_psra_d: {
12074 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12075 case Intrinsic::x86_sse2_psll_w:
12076 case Intrinsic::x86_sse2_psll_d:
12077 case Intrinsic::x86_sse2_psll_q:
12078 case Intrinsic::x86_avx2_psll_w:
12079 case Intrinsic::x86_avx2_psll_d:
12080 case Intrinsic::x86_avx2_psll_q:
12081 Opcode = X86ISD::VSHL;
12083 case Intrinsic::x86_sse2_psrl_w:
12084 case Intrinsic::x86_sse2_psrl_d:
12085 case Intrinsic::x86_sse2_psrl_q:
12086 case Intrinsic::x86_avx2_psrl_w:
12087 case Intrinsic::x86_avx2_psrl_d:
12088 case Intrinsic::x86_avx2_psrl_q:
12089 Opcode = X86ISD::VSRL;
12091 case Intrinsic::x86_sse2_psra_w:
12092 case Intrinsic::x86_sse2_psra_d:
12093 case Intrinsic::x86_avx2_psra_w:
12094 case Intrinsic::x86_avx2_psra_d:
12095 Opcode = X86ISD::VSRA;
12098 return DAG.getNode(Opcode, dl, Op.getValueType(),
12099 Op.getOperand(1), Op.getOperand(2));
12102 // SSE/AVX immediate shift intrinsics
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 case Intrinsic::x86_sse2_psrli_w:
12110 case Intrinsic::x86_sse2_psrli_d:
12111 case Intrinsic::x86_sse2_psrli_q:
12112 case Intrinsic::x86_avx2_psrli_w:
12113 case Intrinsic::x86_avx2_psrli_d:
12114 case Intrinsic::x86_avx2_psrli_q:
12115 case Intrinsic::x86_sse2_psrai_w:
12116 case Intrinsic::x86_sse2_psrai_d:
12117 case Intrinsic::x86_avx2_psrai_w:
12118 case Intrinsic::x86_avx2_psrai_d: {
12121 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12122 case Intrinsic::x86_sse2_pslli_w:
12123 case Intrinsic::x86_sse2_pslli_d:
12124 case Intrinsic::x86_sse2_pslli_q:
12125 case Intrinsic::x86_avx2_pslli_w:
12126 case Intrinsic::x86_avx2_pslli_d:
12127 case Intrinsic::x86_avx2_pslli_q:
12128 Opcode = X86ISD::VSHLI;
12130 case Intrinsic::x86_sse2_psrli_w:
12131 case Intrinsic::x86_sse2_psrli_d:
12132 case Intrinsic::x86_sse2_psrli_q:
12133 case Intrinsic::x86_avx2_psrli_w:
12134 case Intrinsic::x86_avx2_psrli_d:
12135 case Intrinsic::x86_avx2_psrli_q:
12136 Opcode = X86ISD::VSRLI;
12138 case Intrinsic::x86_sse2_psrai_w:
12139 case Intrinsic::x86_sse2_psrai_d:
12140 case Intrinsic::x86_avx2_psrai_w:
12141 case Intrinsic::x86_avx2_psrai_d:
12142 Opcode = X86ISD::VSRAI;
12145 return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
12146 Op.getOperand(1), Op.getOperand(2), DAG);
12149 case Intrinsic::x86_sse42_pcmpistria128:
12150 case Intrinsic::x86_sse42_pcmpestria128:
12151 case Intrinsic::x86_sse42_pcmpistric128:
12152 case Intrinsic::x86_sse42_pcmpestric128:
12153 case Intrinsic::x86_sse42_pcmpistrio128:
12154 case Intrinsic::x86_sse42_pcmpestrio128:
12155 case Intrinsic::x86_sse42_pcmpistris128:
12156 case Intrinsic::x86_sse42_pcmpestris128:
12157 case Intrinsic::x86_sse42_pcmpistriz128:
12158 case Intrinsic::x86_sse42_pcmpestriz128: {
12162 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12163 case Intrinsic::x86_sse42_pcmpistria128:
12164 Opcode = X86ISD::PCMPISTRI;
12165 X86CC = X86::COND_A;
12167 case Intrinsic::x86_sse42_pcmpestria128:
12168 Opcode = X86ISD::PCMPESTRI;
12169 X86CC = X86::COND_A;
12171 case Intrinsic::x86_sse42_pcmpistric128:
12172 Opcode = X86ISD::PCMPISTRI;
12173 X86CC = X86::COND_B;
12175 case Intrinsic::x86_sse42_pcmpestric128:
12176 Opcode = X86ISD::PCMPESTRI;
12177 X86CC = X86::COND_B;
12179 case Intrinsic::x86_sse42_pcmpistrio128:
12180 Opcode = X86ISD::PCMPISTRI;
12181 X86CC = X86::COND_O;
12183 case Intrinsic::x86_sse42_pcmpestrio128:
12184 Opcode = X86ISD::PCMPESTRI;
12185 X86CC = X86::COND_O;
12187 case Intrinsic::x86_sse42_pcmpistris128:
12188 Opcode = X86ISD::PCMPISTRI;
12189 X86CC = X86::COND_S;
12191 case Intrinsic::x86_sse42_pcmpestris128:
12192 Opcode = X86ISD::PCMPESTRI;
12193 X86CC = X86::COND_S;
12195 case Intrinsic::x86_sse42_pcmpistriz128:
12196 Opcode = X86ISD::PCMPISTRI;
12197 X86CC = X86::COND_E;
12199 case Intrinsic::x86_sse42_pcmpestriz128:
12200 Opcode = X86ISD::PCMPESTRI;
12201 X86CC = X86::COND_E;
12204 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12205 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12206 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
12207 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12208 DAG.getConstant(X86CC, MVT::i8),
12209 SDValue(PCMP.getNode(), 1));
12210 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12213 case Intrinsic::x86_sse42_pcmpistri128:
12214 case Intrinsic::x86_sse42_pcmpestri128: {
12216 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
12217 Opcode = X86ISD::PCMPISTRI;
12219 Opcode = X86ISD::PCMPESTRI;
12221 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12222 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12223 return DAG.getNode(Opcode, dl, VTs, NewOps);
12225 case Intrinsic::x86_fma_vfmadd_ps:
12226 case Intrinsic::x86_fma_vfmadd_pd:
12227 case Intrinsic::x86_fma_vfmsub_ps:
12228 case Intrinsic::x86_fma_vfmsub_pd:
12229 case Intrinsic::x86_fma_vfnmadd_ps:
12230 case Intrinsic::x86_fma_vfnmadd_pd:
12231 case Intrinsic::x86_fma_vfnmsub_ps:
12232 case Intrinsic::x86_fma_vfnmsub_pd:
12233 case Intrinsic::x86_fma_vfmaddsub_ps:
12234 case Intrinsic::x86_fma_vfmaddsub_pd:
12235 case Intrinsic::x86_fma_vfmsubadd_ps:
12236 case Intrinsic::x86_fma_vfmsubadd_pd:
12237 case Intrinsic::x86_fma_vfmadd_ps_256:
12238 case Intrinsic::x86_fma_vfmadd_pd_256:
12239 case Intrinsic::x86_fma_vfmsub_ps_256:
12240 case Intrinsic::x86_fma_vfmsub_pd_256:
12241 case Intrinsic::x86_fma_vfnmadd_ps_256:
12242 case Intrinsic::x86_fma_vfnmadd_pd_256:
12243 case Intrinsic::x86_fma_vfnmsub_ps_256:
12244 case Intrinsic::x86_fma_vfnmsub_pd_256:
12245 case Intrinsic::x86_fma_vfmaddsub_ps_256:
12246 case Intrinsic::x86_fma_vfmaddsub_pd_256:
12247 case Intrinsic::x86_fma_vfmsubadd_ps_256:
12248 case Intrinsic::x86_fma_vfmsubadd_pd_256:
12249 case Intrinsic::x86_fma_vfmadd_ps_512:
12250 case Intrinsic::x86_fma_vfmadd_pd_512:
12251 case Intrinsic::x86_fma_vfmsub_ps_512:
12252 case Intrinsic::x86_fma_vfmsub_pd_512:
12253 case Intrinsic::x86_fma_vfnmadd_ps_512:
12254 case Intrinsic::x86_fma_vfnmadd_pd_512:
12255 case Intrinsic::x86_fma_vfnmsub_ps_512:
12256 case Intrinsic::x86_fma_vfnmsub_pd_512:
12257 case Intrinsic::x86_fma_vfmaddsub_ps_512:
12258 case Intrinsic::x86_fma_vfmaddsub_pd_512:
12259 case Intrinsic::x86_fma_vfmsubadd_ps_512:
12260 case Intrinsic::x86_fma_vfmsubadd_pd_512: {
12263 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12264 case Intrinsic::x86_fma_vfmadd_ps:
12265 case Intrinsic::x86_fma_vfmadd_pd:
12266 case Intrinsic::x86_fma_vfmadd_ps_256:
12267 case Intrinsic::x86_fma_vfmadd_pd_256:
12268 case Intrinsic::x86_fma_vfmadd_ps_512:
12269 case Intrinsic::x86_fma_vfmadd_pd_512:
12270 Opc = X86ISD::FMADD;
12272 case Intrinsic::x86_fma_vfmsub_ps:
12273 case Intrinsic::x86_fma_vfmsub_pd:
12274 case Intrinsic::x86_fma_vfmsub_ps_256:
12275 case Intrinsic::x86_fma_vfmsub_pd_256:
12276 case Intrinsic::x86_fma_vfmsub_ps_512:
12277 case Intrinsic::x86_fma_vfmsub_pd_512:
12278 Opc = X86ISD::FMSUB;
12280 case Intrinsic::x86_fma_vfnmadd_ps:
12281 case Intrinsic::x86_fma_vfnmadd_pd:
12282 case Intrinsic::x86_fma_vfnmadd_ps_256:
12283 case Intrinsic::x86_fma_vfnmadd_pd_256:
12284 case Intrinsic::x86_fma_vfnmadd_ps_512:
12285 case Intrinsic::x86_fma_vfnmadd_pd_512:
12286 Opc = X86ISD::FNMADD;
12288 case Intrinsic::x86_fma_vfnmsub_ps:
12289 case Intrinsic::x86_fma_vfnmsub_pd:
12290 case Intrinsic::x86_fma_vfnmsub_ps_256:
12291 case Intrinsic::x86_fma_vfnmsub_pd_256:
12292 case Intrinsic::x86_fma_vfnmsub_ps_512:
12293 case Intrinsic::x86_fma_vfnmsub_pd_512:
12294 Opc = X86ISD::FNMSUB;
12296 case Intrinsic::x86_fma_vfmaddsub_ps:
12297 case Intrinsic::x86_fma_vfmaddsub_pd:
12298 case Intrinsic::x86_fma_vfmaddsub_ps_256:
12299 case Intrinsic::x86_fma_vfmaddsub_pd_256:
12300 case Intrinsic::x86_fma_vfmaddsub_ps_512:
12301 case Intrinsic::x86_fma_vfmaddsub_pd_512:
12302 Opc = X86ISD::FMADDSUB;
12304 case Intrinsic::x86_fma_vfmsubadd_ps:
12305 case Intrinsic::x86_fma_vfmsubadd_pd:
12306 case Intrinsic::x86_fma_vfmsubadd_ps_256:
12307 case Intrinsic::x86_fma_vfmsubadd_pd_256:
12308 case Intrinsic::x86_fma_vfmsubadd_ps_512:
12309 case Intrinsic::x86_fma_vfmsubadd_pd_512:
12310 Opc = X86ISD::FMSUBADD;
12314 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
12315 Op.getOperand(2), Op.getOperand(3));
12320 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12321 SDValue Base, SDValue Index,
12322 SDValue ScaleOp, SDValue Chain,
12323 const X86Subtarget * Subtarget) {
12325 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12326 assert(C && "Invalid scale type");
12327 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12328 SDValue Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12329 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12330 Index.getSimpleValueType().getVectorNumElements());
12331 SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12332 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12333 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12334 SDValue Segment = DAG.getRegister(0, MVT::i32);
12335 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12336 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12337 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12338 return DAG.getMergeValues(RetOps, dl);
12341 static SDValue getMGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12342 SDValue Src, SDValue Mask, SDValue Base,
12343 SDValue Index, SDValue ScaleOp, SDValue Chain,
12344 const X86Subtarget * Subtarget) {
12346 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12347 assert(C && "Invalid scale type");
12348 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12349 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12350 Index.getSimpleValueType().getVectorNumElements());
12351 SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12352 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12353 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12354 SDValue Segment = DAG.getRegister(0, MVT::i32);
12355 if (Src.getOpcode() == ISD::UNDEF)
12356 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12357 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12358 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12359 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12360 return DAG.getMergeValues(RetOps, dl);
12363 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12364 SDValue Src, SDValue Base, SDValue Index,
12365 SDValue ScaleOp, SDValue Chain) {
12367 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12368 assert(C && "Invalid scale type");
12369 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12370 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12371 SDValue Segment = DAG.getRegister(0, MVT::i32);
12372 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12373 Index.getSimpleValueType().getVectorNumElements());
12374 SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12375 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12376 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12377 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12378 return SDValue(Res, 1);
12381 static SDValue getMScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12382 SDValue Src, SDValue Mask, SDValue Base,
12383 SDValue Index, SDValue ScaleOp, SDValue Chain) {
12385 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12386 assert(C && "Invalid scale type");
12387 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12388 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12389 SDValue Segment = DAG.getRegister(0, MVT::i32);
12390 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12391 Index.getSimpleValueType().getVectorNumElements());
12392 SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12393 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12394 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12395 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12396 return SDValue(Res, 1);
12399 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
12400 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
12401 // also used to custom lower READCYCLECOUNTER nodes.
12402 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
12403 SelectionDAG &DAG, const X86Subtarget *Subtarget,
12404 SmallVectorImpl<SDValue> &Results) {
12405 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12406 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
12409 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
12410 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
12411 // and the EAX register is loaded with the low-order 32 bits.
12412 if (Subtarget->is64Bit()) {
12413 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
12414 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
12417 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
12418 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
12421 SDValue Chain = HI.getValue(1);
12423 if (Opcode == X86ISD::RDTSCP_DAG) {
12424 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
12426 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
12427 // the ECX register. Add 'ecx' explicitly to the chain.
12428 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
12430 // Explicitly store the content of ECX at the location passed in input
12431 // to the 'rdtscp' intrinsic.
12432 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
12433 MachinePointerInfo(), false, false, 0);
12436 if (Subtarget->is64Bit()) {
12437 // The EDX register is loaded with the high-order 32 bits of the MSR, and
12438 // the EAX register is loaded with the low-order 32 bits.
12439 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
12440 DAG.getConstant(32, MVT::i8));
12441 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
12442 Results.push_back(Chain);
12446 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12447 SDValue Ops[] = { LO, HI };
12448 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
12449 Results.push_back(Pair);
12450 Results.push_back(Chain);
12453 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12454 SelectionDAG &DAG) {
12455 SmallVector<SDValue, 2> Results;
12457 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
12459 return DAG.getMergeValues(Results, DL);
12462 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
12463 SelectionDAG &DAG) {
12465 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12467 default: return SDValue(); // Don't custom lower most intrinsics.
12469 // RDRAND/RDSEED intrinsics.
12470 case Intrinsic::x86_rdrand_16:
12471 case Intrinsic::x86_rdrand_32:
12472 case Intrinsic::x86_rdrand_64:
12473 case Intrinsic::x86_rdseed_16:
12474 case Intrinsic::x86_rdseed_32:
12475 case Intrinsic::x86_rdseed_64: {
12476 unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
12477 IntNo == Intrinsic::x86_rdseed_32 ||
12478 IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
12480 // Emit the node with the right value type.
12481 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
12482 SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
12484 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
12485 // Otherwise return the value from Rand, which is always 0, casted to i32.
12486 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
12487 DAG.getConstant(1, Op->getValueType(1)),
12488 DAG.getConstant(X86::COND_B, MVT::i32),
12489 SDValue(Result.getNode(), 1) };
12490 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
12491 DAG.getVTList(Op->getValueType(1), MVT::Glue),
12494 // Return { result, isValid, chain }.
12495 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
12496 SDValue(Result.getNode(), 2));
12498 //int_gather(index, base, scale);
12499 case Intrinsic::x86_avx512_gather_qpd_512:
12500 case Intrinsic::x86_avx512_gather_qps_512:
12501 case Intrinsic::x86_avx512_gather_dpd_512:
12502 case Intrinsic::x86_avx512_gather_qpi_512:
12503 case Intrinsic::x86_avx512_gather_qpq_512:
12504 case Intrinsic::x86_avx512_gather_dpq_512:
12505 case Intrinsic::x86_avx512_gather_dps_512:
12506 case Intrinsic::x86_avx512_gather_dpi_512: {
12509 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12510 case Intrinsic::x86_avx512_gather_qps_512: Opc = X86::VGATHERQPSZrm; break;
12511 case Intrinsic::x86_avx512_gather_qpd_512: Opc = X86::VGATHERQPDZrm; break;
12512 case Intrinsic::x86_avx512_gather_dpd_512: Opc = X86::VGATHERDPDZrm; break;
12513 case Intrinsic::x86_avx512_gather_dps_512: Opc = X86::VGATHERDPSZrm; break;
12514 case Intrinsic::x86_avx512_gather_qpi_512: Opc = X86::VPGATHERQDZrm; break;
12515 case Intrinsic::x86_avx512_gather_qpq_512: Opc = X86::VPGATHERQQZrm; break;
12516 case Intrinsic::x86_avx512_gather_dpi_512: Opc = X86::VPGATHERDDZrm; break;
12517 case Intrinsic::x86_avx512_gather_dpq_512: Opc = X86::VPGATHERDQZrm; break;
12519 SDValue Chain = Op.getOperand(0);
12520 SDValue Index = Op.getOperand(2);
12521 SDValue Base = Op.getOperand(3);
12522 SDValue Scale = Op.getOperand(4);
12523 return getGatherNode(Opc, Op, DAG, Base, Index, Scale, Chain, Subtarget);
12525 //int_gather_mask(v1, mask, index, base, scale);
12526 case Intrinsic::x86_avx512_gather_qps_mask_512:
12527 case Intrinsic::x86_avx512_gather_qpd_mask_512:
12528 case Intrinsic::x86_avx512_gather_dpd_mask_512:
12529 case Intrinsic::x86_avx512_gather_dps_mask_512:
12530 case Intrinsic::x86_avx512_gather_qpi_mask_512:
12531 case Intrinsic::x86_avx512_gather_qpq_mask_512:
12532 case Intrinsic::x86_avx512_gather_dpi_mask_512:
12533 case Intrinsic::x86_avx512_gather_dpq_mask_512: {
12536 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12537 case Intrinsic::x86_avx512_gather_qps_mask_512:
12538 Opc = X86::VGATHERQPSZrm; break;
12539 case Intrinsic::x86_avx512_gather_qpd_mask_512:
12540 Opc = X86::VGATHERQPDZrm; break;
12541 case Intrinsic::x86_avx512_gather_dpd_mask_512:
12542 Opc = X86::VGATHERDPDZrm; break;
12543 case Intrinsic::x86_avx512_gather_dps_mask_512:
12544 Opc = X86::VGATHERDPSZrm; break;
12545 case Intrinsic::x86_avx512_gather_qpi_mask_512:
12546 Opc = X86::VPGATHERQDZrm; break;
12547 case Intrinsic::x86_avx512_gather_qpq_mask_512:
12548 Opc = X86::VPGATHERQQZrm; break;
12549 case Intrinsic::x86_avx512_gather_dpi_mask_512:
12550 Opc = X86::VPGATHERDDZrm; break;
12551 case Intrinsic::x86_avx512_gather_dpq_mask_512:
12552 Opc = X86::VPGATHERDQZrm; break;
12554 SDValue Chain = Op.getOperand(0);
12555 SDValue Src = Op.getOperand(2);
12556 SDValue Mask = Op.getOperand(3);
12557 SDValue Index = Op.getOperand(4);
12558 SDValue Base = Op.getOperand(5);
12559 SDValue Scale = Op.getOperand(6);
12560 return getMGatherNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
12563 //int_scatter(base, index, v1, scale);
12564 case Intrinsic::x86_avx512_scatter_qpd_512:
12565 case Intrinsic::x86_avx512_scatter_qps_512:
12566 case Intrinsic::x86_avx512_scatter_dpd_512:
12567 case Intrinsic::x86_avx512_scatter_qpi_512:
12568 case Intrinsic::x86_avx512_scatter_qpq_512:
12569 case Intrinsic::x86_avx512_scatter_dpq_512:
12570 case Intrinsic::x86_avx512_scatter_dps_512:
12571 case Intrinsic::x86_avx512_scatter_dpi_512: {
12574 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12575 case Intrinsic::x86_avx512_scatter_qpd_512:
12576 Opc = X86::VSCATTERQPDZmr; break;
12577 case Intrinsic::x86_avx512_scatter_qps_512:
12578 Opc = X86::VSCATTERQPSZmr; break;
12579 case Intrinsic::x86_avx512_scatter_dpd_512:
12580 Opc = X86::VSCATTERDPDZmr; break;
12581 case Intrinsic::x86_avx512_scatter_dps_512:
12582 Opc = X86::VSCATTERDPSZmr; break;
12583 case Intrinsic::x86_avx512_scatter_qpi_512:
12584 Opc = X86::VPSCATTERQDZmr; break;
12585 case Intrinsic::x86_avx512_scatter_qpq_512:
12586 Opc = X86::VPSCATTERQQZmr; break;
12587 case Intrinsic::x86_avx512_scatter_dpq_512:
12588 Opc = X86::VPSCATTERDQZmr; break;
12589 case Intrinsic::x86_avx512_scatter_dpi_512:
12590 Opc = X86::VPSCATTERDDZmr; break;
12592 SDValue Chain = Op.getOperand(0);
12593 SDValue Base = Op.getOperand(2);
12594 SDValue Index = Op.getOperand(3);
12595 SDValue Src = Op.getOperand(4);
12596 SDValue Scale = Op.getOperand(5);
12597 return getScatterNode(Opc, Op, DAG, Src, Base, Index, Scale, Chain);
12599 //int_scatter_mask(base, mask, index, v1, scale);
12600 case Intrinsic::x86_avx512_scatter_qps_mask_512:
12601 case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12602 case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12603 case Intrinsic::x86_avx512_scatter_dps_mask_512:
12604 case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12605 case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12606 case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12607 case Intrinsic::x86_avx512_scatter_dpq_mask_512: {
12610 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12611 case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12612 Opc = X86::VSCATTERQPDZmr; break;
12613 case Intrinsic::x86_avx512_scatter_qps_mask_512:
12614 Opc = X86::VSCATTERQPSZmr; break;
12615 case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12616 Opc = X86::VSCATTERDPDZmr; break;
12617 case Intrinsic::x86_avx512_scatter_dps_mask_512:
12618 Opc = X86::VSCATTERDPSZmr; break;
12619 case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12620 Opc = X86::VPSCATTERQDZmr; break;
12621 case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12622 Opc = X86::VPSCATTERQQZmr; break;
12623 case Intrinsic::x86_avx512_scatter_dpq_mask_512:
12624 Opc = X86::VPSCATTERDQZmr; break;
12625 case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12626 Opc = X86::VPSCATTERDDZmr; break;
12628 SDValue Chain = Op.getOperand(0);
12629 SDValue Base = Op.getOperand(2);
12630 SDValue Mask = Op.getOperand(3);
12631 SDValue Index = Op.getOperand(4);
12632 SDValue Src = Op.getOperand(5);
12633 SDValue Scale = Op.getOperand(6);
12634 return getMScatterNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
12636 // Read Time Stamp Counter (RDTSC).
12637 case Intrinsic::x86_rdtsc:
12638 // Read Time Stamp Counter and Processor ID (RDTSCP).
12639 case Intrinsic::x86_rdtscp: {
12642 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12643 case Intrinsic::x86_rdtsc:
12644 Opc = X86ISD::RDTSC_DAG; break;
12645 case Intrinsic::x86_rdtscp:
12646 Opc = X86ISD::RDTSCP_DAG; break;
12648 SmallVector<SDValue, 2> Results;
12649 getReadTimeStampCounter(Op.getNode(), dl, Opc, DAG, Subtarget, Results);
12650 return DAG.getMergeValues(Results, dl);
12652 // XTEST intrinsics.
12653 case Intrinsic::x86_xtest: {
12654 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
12655 SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
12656 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12657 DAG.getConstant(X86::COND_NE, MVT::i8),
12659 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
12660 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
12661 Ret, SDValue(InTrans.getNode(), 1));
12666 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
12667 SelectionDAG &DAG) const {
12668 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12669 MFI->setReturnAddressIsTaken(true);
12671 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
12674 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12676 EVT PtrVT = getPointerTy();
12679 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12680 const X86RegisterInfo *RegInfo =
12681 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12682 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
12683 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12684 DAG.getNode(ISD::ADD, dl, PtrVT,
12685 FrameAddr, Offset),
12686 MachinePointerInfo(), false, false, false, 0);
12689 // Just load the return address.
12690 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
12691 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12692 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
12695 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
12696 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12697 MFI->setFrameAddressIsTaken(true);
12699 EVT VT = Op.getValueType();
12700 SDLoc dl(Op); // FIXME probably not meaningful
12701 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12702 const X86RegisterInfo *RegInfo =
12703 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12704 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12705 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
12706 (FrameReg == X86::EBP && VT == MVT::i32)) &&
12707 "Invalid Frame Register!");
12708 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
12710 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
12711 MachinePointerInfo(),
12712 false, false, false, 0);
12716 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
12717 SelectionDAG &DAG) const {
12718 const X86RegisterInfo *RegInfo =
12719 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12720 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
12723 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
12724 SDValue Chain = Op.getOperand(0);
12725 SDValue Offset = Op.getOperand(1);
12726 SDValue Handler = Op.getOperand(2);
12729 EVT PtrVT = getPointerTy();
12730 const X86RegisterInfo *RegInfo =
12731 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12732 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12733 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
12734 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
12735 "Invalid Frame Register!");
12736 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
12737 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
12739 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
12740 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
12741 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
12742 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
12744 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
12746 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
12747 DAG.getRegister(StoreAddrReg, PtrVT));
12750 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
12751 SelectionDAG &DAG) const {
12753 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
12754 DAG.getVTList(MVT::i32, MVT::Other),
12755 Op.getOperand(0), Op.getOperand(1));
12758 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
12759 SelectionDAG &DAG) const {
12761 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
12762 Op.getOperand(0), Op.getOperand(1));
12765 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
12766 return Op.getOperand(0);
12769 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
12770 SelectionDAG &DAG) const {
12771 SDValue Root = Op.getOperand(0);
12772 SDValue Trmp = Op.getOperand(1); // trampoline
12773 SDValue FPtr = Op.getOperand(2); // nested function
12774 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
12777 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
12778 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12780 if (Subtarget->is64Bit()) {
12781 SDValue OutChains[6];
12783 // Large code-model.
12784 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
12785 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
12787 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
12788 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
12790 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
12792 // Load the pointer to the nested function into R11.
12793 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
12794 SDValue Addr = Trmp;
12795 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12796 Addr, MachinePointerInfo(TrmpAddr),
12799 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12800 DAG.getConstant(2, MVT::i64));
12801 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
12802 MachinePointerInfo(TrmpAddr, 2),
12805 // Load the 'nest' parameter value into R10.
12806 // R10 is specified in X86CallingConv.td
12807 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
12808 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12809 DAG.getConstant(10, MVT::i64));
12810 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12811 Addr, MachinePointerInfo(TrmpAddr, 10),
12814 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12815 DAG.getConstant(12, MVT::i64));
12816 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
12817 MachinePointerInfo(TrmpAddr, 12),
12820 // Jump to the nested function.
12821 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
12822 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12823 DAG.getConstant(20, MVT::i64));
12824 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12825 Addr, MachinePointerInfo(TrmpAddr, 20),
12828 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
12829 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12830 DAG.getConstant(22, MVT::i64));
12831 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
12832 MachinePointerInfo(TrmpAddr, 22),
12835 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
12837 const Function *Func =
12838 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
12839 CallingConv::ID CC = Func->getCallingConv();
12844 llvm_unreachable("Unsupported calling convention");
12845 case CallingConv::C:
12846 case CallingConv::X86_StdCall: {
12847 // Pass 'nest' parameter in ECX.
12848 // Must be kept in sync with X86CallingConv.td
12849 NestReg = X86::ECX;
12851 // Check that ECX wasn't needed by an 'inreg' parameter.
12852 FunctionType *FTy = Func->getFunctionType();
12853 const AttributeSet &Attrs = Func->getAttributes();
12855 if (!Attrs.isEmpty() && !Func->isVarArg()) {
12856 unsigned InRegCount = 0;
12859 for (FunctionType::param_iterator I = FTy->param_begin(),
12860 E = FTy->param_end(); I != E; ++I, ++Idx)
12861 if (Attrs.hasAttribute(Idx, Attribute::InReg))
12862 // FIXME: should only count parameters that are lowered to integers.
12863 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
12865 if (InRegCount > 2) {
12866 report_fatal_error("Nest register in use - reduce number of inreg"
12872 case CallingConv::X86_FastCall:
12873 case CallingConv::X86_ThisCall:
12874 case CallingConv::Fast:
12875 // Pass 'nest' parameter in EAX.
12876 // Must be kept in sync with X86CallingConv.td
12877 NestReg = X86::EAX;
12881 SDValue OutChains[4];
12882 SDValue Addr, Disp;
12884 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12885 DAG.getConstant(10, MVT::i32));
12886 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
12888 // This is storing the opcode for MOV32ri.
12889 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
12890 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
12891 OutChains[0] = DAG.getStore(Root, dl,
12892 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
12893 Trmp, MachinePointerInfo(TrmpAddr),
12896 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12897 DAG.getConstant(1, MVT::i32));
12898 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
12899 MachinePointerInfo(TrmpAddr, 1),
12902 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
12903 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12904 DAG.getConstant(5, MVT::i32));
12905 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
12906 MachinePointerInfo(TrmpAddr, 5),
12909 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12910 DAG.getConstant(6, MVT::i32));
12911 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
12912 MachinePointerInfo(TrmpAddr, 6),
12915 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
12919 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
12920 SelectionDAG &DAG) const {
12922 The rounding mode is in bits 11:10 of FPSR, and has the following
12924 00 Round to nearest
12929 FLT_ROUNDS, on the other hand, expects the following:
12936 To perform the conversion, we do:
12937 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
12940 MachineFunction &MF = DAG.getMachineFunction();
12941 const TargetMachine &TM = MF.getTarget();
12942 const TargetFrameLowering &TFI = *TM.getFrameLowering();
12943 unsigned StackAlignment = TFI.getStackAlignment();
12944 MVT VT = Op.getSimpleValueType();
12947 // Save FP Control Word to stack slot
12948 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
12949 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12951 MachineMemOperand *MMO =
12952 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12953 MachineMemOperand::MOStore, 2, 2);
12955 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
12956 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
12957 DAG.getVTList(MVT::Other),
12958 Ops, MVT::i16, MMO);
12960 // Load FP Control Word from stack slot
12961 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
12962 MachinePointerInfo(), false, false, false, 0);
12964 // Transform as necessary
12966 DAG.getNode(ISD::SRL, DL, MVT::i16,
12967 DAG.getNode(ISD::AND, DL, MVT::i16,
12968 CWD, DAG.getConstant(0x800, MVT::i16)),
12969 DAG.getConstant(11, MVT::i8));
12971 DAG.getNode(ISD::SRL, DL, MVT::i16,
12972 DAG.getNode(ISD::AND, DL, MVT::i16,
12973 CWD, DAG.getConstant(0x400, MVT::i16)),
12974 DAG.getConstant(9, MVT::i8));
12977 DAG.getNode(ISD::AND, DL, MVT::i16,
12978 DAG.getNode(ISD::ADD, DL, MVT::i16,
12979 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
12980 DAG.getConstant(1, MVT::i16)),
12981 DAG.getConstant(3, MVT::i16));
12983 return DAG.getNode((VT.getSizeInBits() < 16 ?
12984 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
12987 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
12988 MVT VT = Op.getSimpleValueType();
12990 unsigned NumBits = VT.getSizeInBits();
12993 Op = Op.getOperand(0);
12994 if (VT == MVT::i8) {
12995 // Zero extend to i32 since there is not an i8 bsr.
12997 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13000 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
13001 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13002 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13004 // If src is zero (i.e. bsr sets ZF), returns NumBits.
13007 DAG.getConstant(NumBits+NumBits-1, OpVT),
13008 DAG.getConstant(X86::COND_E, MVT::i8),
13011 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
13013 // Finally xor with NumBits-1.
13014 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13017 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13021 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
13022 MVT VT = Op.getSimpleValueType();
13024 unsigned NumBits = VT.getSizeInBits();
13027 Op = Op.getOperand(0);
13028 if (VT == MVT::i8) {
13029 // Zero extend to i32 since there is not an i8 bsr.
13031 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13034 // Issue a bsr (scan bits in reverse).
13035 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13036 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13038 // And xor with NumBits-1.
13039 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13042 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13046 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
13047 MVT VT = Op.getSimpleValueType();
13048 unsigned NumBits = VT.getSizeInBits();
13050 Op = Op.getOperand(0);
13052 // Issue a bsf (scan bits forward) which also sets EFLAGS.
13053 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13054 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
13056 // If src is zero (i.e. bsf sets ZF), returns NumBits.
13059 DAG.getConstant(NumBits, VT),
13060 DAG.getConstant(X86::COND_E, MVT::i8),
13063 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
13066 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
13067 // ones, and then concatenate the result back.
13068 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
13069 MVT VT = Op.getSimpleValueType();
13071 assert(VT.is256BitVector() && VT.isInteger() &&
13072 "Unsupported value type for operation");
13074 unsigned NumElems = VT.getVectorNumElements();
13077 // Extract the LHS vectors
13078 SDValue LHS = Op.getOperand(0);
13079 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13080 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13082 // Extract the RHS vectors
13083 SDValue RHS = Op.getOperand(1);
13084 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13085 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13087 MVT EltVT = VT.getVectorElementType();
13088 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13090 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13091 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
13092 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
13095 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
13096 assert(Op.getSimpleValueType().is256BitVector() &&
13097 Op.getSimpleValueType().isInteger() &&
13098 "Only handle AVX 256-bit vector integer operation");
13099 return Lower256IntArith(Op, DAG);
13102 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
13103 assert(Op.getSimpleValueType().is256BitVector() &&
13104 Op.getSimpleValueType().isInteger() &&
13105 "Only handle AVX 256-bit vector integer operation");
13106 return Lower256IntArith(Op, DAG);
13109 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
13110 SelectionDAG &DAG) {
13112 MVT VT = Op.getSimpleValueType();
13114 // Decompose 256-bit ops into smaller 128-bit ops.
13115 if (VT.is256BitVector() && !Subtarget->hasInt256())
13116 return Lower256IntArith(Op, DAG);
13118 SDValue A = Op.getOperand(0);
13119 SDValue B = Op.getOperand(1);
13121 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
13122 if (VT == MVT::v4i32) {
13123 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
13124 "Should not custom lower when pmuldq is available!");
13126 // Extract the odd parts.
13127 static const int UnpackMask[] = { 1, -1, 3, -1 };
13128 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
13129 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
13131 // Multiply the even parts.
13132 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
13133 // Now multiply odd parts.
13134 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
13136 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
13137 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
13139 // Merge the two vectors back together with a shuffle. This expands into 2
13141 static const int ShufMask[] = { 0, 4, 2, 6 };
13142 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
13145 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
13146 "Only know how to lower V2I64/V4I64/V8I64 multiply");
13148 // Ahi = psrlqi(a, 32);
13149 // Bhi = psrlqi(b, 32);
13151 // AloBlo = pmuludq(a, b);
13152 // AloBhi = pmuludq(a, Bhi);
13153 // AhiBlo = pmuludq(Ahi, b);
13155 // AloBhi = psllqi(AloBhi, 32);
13156 // AhiBlo = psllqi(AhiBlo, 32);
13157 // return AloBlo + AloBhi + AhiBlo;
13159 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
13160 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
13162 // Bit cast to 32-bit vectors for MULUDQ
13163 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
13164 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
13165 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
13166 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
13167 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
13168 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
13170 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
13171 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
13172 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
13174 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
13175 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
13177 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
13178 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
13181 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
13182 SelectionDAG &DAG) {
13183 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
13184 EVT VT = Op0.getValueType();
13187 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
13188 (VT == MVT::v8i32 && Subtarget->hasInt256()));
13190 // Get the high parts.
13191 const int Mask[] = {1, 2, 3, 4, 5, 6, 7, 8};
13192 SDValue Hi0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
13193 SDValue Hi1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
13195 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
13197 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
13198 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
13200 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
13201 SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
13202 DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
13203 SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
13204 DAG.getNode(Opcode, dl, MulVT, Hi0, Hi1));
13206 // Shuffle it back into the right order.
13207 const int HighMask[] = {1, 5, 3, 7, 9, 13, 11, 15};
13208 SDValue Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
13209 const int LowMask[] = {0, 4, 2, 6, 8, 12, 10, 14};
13210 SDValue Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
13212 // If we have a signed multiply but no PMULDQ fix up the high parts of a
13213 // unsigned multiply.
13214 if (IsSigned && !Subtarget->hasSSE41()) {
13216 DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
13217 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
13218 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
13219 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
13220 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
13222 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
13223 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
13226 return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Highs, Lows);
13229 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
13230 const X86Subtarget *Subtarget) {
13231 MVT VT = Op.getSimpleValueType();
13233 SDValue R = Op.getOperand(0);
13234 SDValue Amt = Op.getOperand(1);
13236 // Optimize shl/srl/sra with constant shift amount.
13237 if (isSplatVector(Amt.getNode())) {
13238 SDValue SclrAmt = Amt->getOperand(0);
13239 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
13240 uint64_t ShiftAmt = C->getZExtValue();
13242 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
13243 (Subtarget->hasInt256() &&
13244 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13245 (Subtarget->hasAVX512() &&
13246 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13247 if (Op.getOpcode() == ISD::SHL)
13248 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13250 if (Op.getOpcode() == ISD::SRL)
13251 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13253 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
13254 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13258 if (VT == MVT::v16i8) {
13259 if (Op.getOpcode() == ISD::SHL) {
13260 // Make a large shift.
13261 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13262 MVT::v8i16, R, ShiftAmt,
13264 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13265 // Zero out the rightmost bits.
13266 SmallVector<SDValue, 16> V(16,
13267 DAG.getConstant(uint8_t(-1U << ShiftAmt),
13269 return DAG.getNode(ISD::AND, dl, VT, SHL,
13270 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13272 if (Op.getOpcode() == ISD::SRL) {
13273 // Make a large shift.
13274 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13275 MVT::v8i16, R, ShiftAmt,
13277 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13278 // Zero out the leftmost bits.
13279 SmallVector<SDValue, 16> V(16,
13280 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13282 return DAG.getNode(ISD::AND, dl, VT, SRL,
13283 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13285 if (Op.getOpcode() == ISD::SRA) {
13286 if (ShiftAmt == 7) {
13287 // R s>> 7 === R s< 0
13288 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13289 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13292 // R s>> a === ((R u>> a) ^ m) - m
13293 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13294 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
13296 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13297 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13298 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13301 llvm_unreachable("Unknown shift opcode.");
13304 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
13305 if (Op.getOpcode() == ISD::SHL) {
13306 // Make a large shift.
13307 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13308 MVT::v16i16, R, ShiftAmt,
13310 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13311 // Zero out the rightmost bits.
13312 SmallVector<SDValue, 32> V(32,
13313 DAG.getConstant(uint8_t(-1U << ShiftAmt),
13315 return DAG.getNode(ISD::AND, dl, VT, SHL,
13316 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13318 if (Op.getOpcode() == ISD::SRL) {
13319 // Make a large shift.
13320 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13321 MVT::v16i16, R, ShiftAmt,
13323 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13324 // Zero out the leftmost bits.
13325 SmallVector<SDValue, 32> V(32,
13326 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13328 return DAG.getNode(ISD::AND, dl, VT, SRL,
13329 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13331 if (Op.getOpcode() == ISD::SRA) {
13332 if (ShiftAmt == 7) {
13333 // R s>> 7 === R s< 0
13334 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13335 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13338 // R s>> a === ((R u>> a) ^ m) - m
13339 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13340 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
13342 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13343 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13344 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13347 llvm_unreachable("Unknown shift opcode.");
13352 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13353 if (!Subtarget->is64Bit() &&
13354 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
13355 Amt.getOpcode() == ISD::BITCAST &&
13356 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13357 Amt = Amt.getOperand(0);
13358 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13359 VT.getVectorNumElements();
13360 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
13361 uint64_t ShiftAmt = 0;
13362 for (unsigned i = 0; i != Ratio; ++i) {
13363 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
13367 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
13369 // Check remaining shift amounts.
13370 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13371 uint64_t ShAmt = 0;
13372 for (unsigned j = 0; j != Ratio; ++j) {
13373 ConstantSDNode *C =
13374 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
13378 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
13380 if (ShAmt != ShiftAmt)
13383 switch (Op.getOpcode()) {
13385 llvm_unreachable("Unknown shift opcode!");
13387 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13390 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13393 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13401 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
13402 const X86Subtarget* Subtarget) {
13403 MVT VT = Op.getSimpleValueType();
13405 SDValue R = Op.getOperand(0);
13406 SDValue Amt = Op.getOperand(1);
13408 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
13409 VT == MVT::v4i32 || VT == MVT::v8i16 ||
13410 (Subtarget->hasInt256() &&
13411 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
13412 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13413 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13415 EVT EltVT = VT.getVectorElementType();
13417 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13418 unsigned NumElts = VT.getVectorNumElements();
13420 for (i = 0; i != NumElts; ++i) {
13421 if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
13425 for (j = i; j != NumElts; ++j) {
13426 SDValue Arg = Amt.getOperand(j);
13427 if (Arg.getOpcode() == ISD::UNDEF) continue;
13428 if (Arg != Amt.getOperand(i))
13431 if (i != NumElts && j == NumElts)
13432 BaseShAmt = Amt.getOperand(i);
13434 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13435 Amt = Amt.getOperand(0);
13436 if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
13437 cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
13438 SDValue InVec = Amt.getOperand(0);
13439 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13440 unsigned NumElts = InVec.getValueType().getVectorNumElements();
13442 for (; i != NumElts; ++i) {
13443 SDValue Arg = InVec.getOperand(i);
13444 if (Arg.getOpcode() == ISD::UNDEF) continue;
13448 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13449 if (ConstantSDNode *C =
13450 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13451 unsigned SplatIdx =
13452 cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
13453 if (C->getZExtValue() == SplatIdx)
13454 BaseShAmt = InVec.getOperand(1);
13457 if (!BaseShAmt.getNode())
13458 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
13459 DAG.getIntPtrConstant(0));
13463 if (BaseShAmt.getNode()) {
13464 if (EltVT.bitsGT(MVT::i32))
13465 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
13466 else if (EltVT.bitsLT(MVT::i32))
13467 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
13469 switch (Op.getOpcode()) {
13471 llvm_unreachable("Unknown shift opcode!");
13473 switch (VT.SimpleTy) {
13474 default: return SDValue();
13483 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
13486 switch (VT.SimpleTy) {
13487 default: return SDValue();
13494 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
13497 switch (VT.SimpleTy) {
13498 default: return SDValue();
13507 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
13513 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13514 if (!Subtarget->is64Bit() &&
13515 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
13516 (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
13517 Amt.getOpcode() == ISD::BITCAST &&
13518 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13519 Amt = Amt.getOperand(0);
13520 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13521 VT.getVectorNumElements();
13522 std::vector<SDValue> Vals(Ratio);
13523 for (unsigned i = 0; i != Ratio; ++i)
13524 Vals[i] = Amt.getOperand(i);
13525 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13526 for (unsigned j = 0; j != Ratio; ++j)
13527 if (Vals[j] != Amt.getOperand(i + j))
13530 switch (Op.getOpcode()) {
13532 llvm_unreachable("Unknown shift opcode!");
13534 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
13536 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
13538 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
13545 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
13546 SelectionDAG &DAG) {
13548 MVT VT = Op.getSimpleValueType();
13550 SDValue R = Op.getOperand(0);
13551 SDValue Amt = Op.getOperand(1);
13554 if (!Subtarget->hasSSE2())
13557 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
13561 V = LowerScalarVariableShift(Op, DAG, Subtarget);
13565 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
13567 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
13568 if (Subtarget->hasInt256()) {
13569 if (Op.getOpcode() == ISD::SRL &&
13570 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13571 VT == MVT::v4i64 || VT == MVT::v8i32))
13573 if (Op.getOpcode() == ISD::SHL &&
13574 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13575 VT == MVT::v4i64 || VT == MVT::v8i32))
13577 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
13581 // If possible, lower this packed shift into a vector multiply instead of
13582 // expanding it into a sequence of scalar shifts.
13583 // Do this only if the vector shift count is a constant build_vector.
13584 if (Op.getOpcode() == ISD::SHL &&
13585 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
13586 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
13587 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13588 SmallVector<SDValue, 8> Elts;
13589 EVT SVT = VT.getScalarType();
13590 unsigned SVTBits = SVT.getSizeInBits();
13591 const APInt &One = APInt(SVTBits, 1);
13592 unsigned NumElems = VT.getVectorNumElements();
13594 for (unsigned i=0; i !=NumElems; ++i) {
13595 SDValue Op = Amt->getOperand(i);
13596 if (Op->getOpcode() == ISD::UNDEF) {
13597 Elts.push_back(Op);
13601 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
13602 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
13603 uint64_t ShAmt = C.getZExtValue();
13604 if (ShAmt >= SVTBits) {
13605 Elts.push_back(DAG.getUNDEF(SVT));
13608 Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
13610 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
13611 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
13614 // Lower SHL with variable shift amount.
13615 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
13616 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
13618 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
13619 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
13620 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
13621 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
13624 // If possible, lower this shift as a sequence of two shifts by
13625 // constant plus a MOVSS/MOVSD instead of scalarizing it.
13627 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
13629 // Could be rewritten as:
13630 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
13632 // The advantage is that the two shifts from the example would be
13633 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
13634 // the vector shift into four scalar shifts plus four pairs of vector
13636 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
13637 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13638 unsigned TargetOpcode = X86ISD::MOVSS;
13639 bool CanBeSimplified;
13640 // The splat value for the first packed shift (the 'X' from the example).
13641 SDValue Amt1 = Amt->getOperand(0);
13642 // The splat value for the second packed shift (the 'Y' from the example).
13643 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
13644 Amt->getOperand(2);
13646 // See if it is possible to replace this node with a sequence of
13647 // two shifts followed by a MOVSS/MOVSD
13648 if (VT == MVT::v4i32) {
13649 // Check if it is legal to use a MOVSS.
13650 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
13651 Amt2 == Amt->getOperand(3);
13652 if (!CanBeSimplified) {
13653 // Otherwise, check if we can still simplify this node using a MOVSD.
13654 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
13655 Amt->getOperand(2) == Amt->getOperand(3);
13656 TargetOpcode = X86ISD::MOVSD;
13657 Amt2 = Amt->getOperand(2);
13660 // Do similar checks for the case where the machine value type
13662 CanBeSimplified = Amt1 == Amt->getOperand(1);
13663 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
13664 CanBeSimplified = Amt2 == Amt->getOperand(i);
13666 if (!CanBeSimplified) {
13667 TargetOpcode = X86ISD::MOVSD;
13668 CanBeSimplified = true;
13669 Amt2 = Amt->getOperand(4);
13670 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
13671 CanBeSimplified = Amt1 == Amt->getOperand(i);
13672 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
13673 CanBeSimplified = Amt2 == Amt->getOperand(j);
13677 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
13678 isa<ConstantSDNode>(Amt2)) {
13679 // Replace this node with two shifts followed by a MOVSS/MOVSD.
13680 EVT CastVT = MVT::v4i32;
13682 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
13683 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
13685 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
13686 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
13687 if (TargetOpcode == X86ISD::MOVSD)
13688 CastVT = MVT::v2i64;
13689 SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
13690 SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
13691 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
13693 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13697 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
13698 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
13701 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
13702 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
13704 // Turn 'a' into a mask suitable for VSELECT
13705 SDValue VSelM = DAG.getConstant(0x80, VT);
13706 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13707 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13709 SDValue CM1 = DAG.getConstant(0x0f, VT);
13710 SDValue CM2 = DAG.getConstant(0x3f, VT);
13712 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
13713 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
13714 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
13715 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13716 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13719 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13720 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13721 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13723 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
13724 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
13725 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
13726 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13727 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13730 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13731 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13732 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13734 // return VSELECT(r, r+r, a);
13735 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
13736 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
13740 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
13741 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
13742 // solution better.
13743 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
13744 MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
13746 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
13747 R = DAG.getNode(ExtOpc, dl, NewVT, R);
13748 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
13749 return DAG.getNode(ISD::TRUNCATE, dl, VT,
13750 DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
13753 // Decompose 256-bit shifts into smaller 128-bit shifts.
13754 if (VT.is256BitVector()) {
13755 unsigned NumElems = VT.getVectorNumElements();
13756 MVT EltVT = VT.getVectorElementType();
13757 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13759 // Extract the two vectors
13760 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
13761 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
13763 // Recreate the shift amount vectors
13764 SDValue Amt1, Amt2;
13765 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13766 // Constant shift amount
13767 SmallVector<SDValue, 4> Amt1Csts;
13768 SmallVector<SDValue, 4> Amt2Csts;
13769 for (unsigned i = 0; i != NumElems/2; ++i)
13770 Amt1Csts.push_back(Amt->getOperand(i));
13771 for (unsigned i = NumElems/2; i != NumElems; ++i)
13772 Amt2Csts.push_back(Amt->getOperand(i));
13774 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
13775 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
13777 // Variable shift amount
13778 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
13779 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
13782 // Issue new vector shifts for the smaller types
13783 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
13784 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
13786 // Concatenate the result back
13787 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
13793 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
13794 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
13795 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
13796 // looks for this combo and may remove the "setcc" instruction if the "setcc"
13797 // has only one use.
13798 SDNode *N = Op.getNode();
13799 SDValue LHS = N->getOperand(0);
13800 SDValue RHS = N->getOperand(1);
13801 unsigned BaseOp = 0;
13804 switch (Op.getOpcode()) {
13805 default: llvm_unreachable("Unknown ovf instruction!");
13807 // A subtract of one will be selected as a INC. Note that INC doesn't
13808 // set CF, so we can't do this for UADDO.
13809 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13811 BaseOp = X86ISD::INC;
13812 Cond = X86::COND_O;
13815 BaseOp = X86ISD::ADD;
13816 Cond = X86::COND_O;
13819 BaseOp = X86ISD::ADD;
13820 Cond = X86::COND_B;
13823 // A subtract of one will be selected as a DEC. Note that DEC doesn't
13824 // set CF, so we can't do this for USUBO.
13825 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13827 BaseOp = X86ISD::DEC;
13828 Cond = X86::COND_O;
13831 BaseOp = X86ISD::SUB;
13832 Cond = X86::COND_O;
13835 BaseOp = X86ISD::SUB;
13836 Cond = X86::COND_B;
13839 BaseOp = X86ISD::SMUL;
13840 Cond = X86::COND_O;
13842 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
13843 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
13845 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
13848 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13849 DAG.getConstant(X86::COND_O, MVT::i32),
13850 SDValue(Sum.getNode(), 2));
13852 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13856 // Also sets EFLAGS.
13857 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
13858 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
13861 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
13862 DAG.getConstant(Cond, MVT::i32),
13863 SDValue(Sum.getNode(), 1));
13865 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13868 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
13869 SelectionDAG &DAG) const {
13871 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
13872 MVT VT = Op.getSimpleValueType();
13874 if (!Subtarget->hasSSE2() || !VT.isVector())
13877 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
13878 ExtraVT.getScalarType().getSizeInBits();
13880 switch (VT.SimpleTy) {
13881 default: return SDValue();
13884 if (!Subtarget->hasFp256())
13886 if (!Subtarget->hasInt256()) {
13887 // needs to be split
13888 unsigned NumElems = VT.getVectorNumElements();
13890 // Extract the LHS vectors
13891 SDValue LHS = Op.getOperand(0);
13892 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13893 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13895 MVT EltVT = VT.getVectorElementType();
13896 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13898 EVT ExtraEltVT = ExtraVT.getVectorElementType();
13899 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
13900 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
13902 SDValue Extra = DAG.getValueType(ExtraVT);
13904 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
13905 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
13907 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
13912 SDValue Op0 = Op.getOperand(0);
13913 SDValue Op00 = Op0.getOperand(0);
13915 // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
13916 if (Op0.getOpcode() == ISD::BITCAST &&
13917 Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
13918 // (sext (vzext x)) -> (vsext x)
13919 Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
13920 if (Tmp1.getNode()) {
13921 EVT ExtraEltVT = ExtraVT.getVectorElementType();
13922 // This folding is only valid when the in-reg type is a vector of i8,
13924 if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
13925 ExtraEltVT == MVT::i32) {
13926 SDValue Tmp1Op0 = Tmp1.getOperand(0);
13927 assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
13928 "This optimization is invalid without a VZEXT.");
13929 return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
13935 // If the above didn't work, then just use Shift-Left + Shift-Right.
13936 Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
13938 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
13944 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
13945 SelectionDAG &DAG) {
13947 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
13948 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
13949 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
13950 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
13952 // The only fence that needs an instruction is a sequentially-consistent
13953 // cross-thread fence.
13954 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
13955 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
13956 // no-sse2). There isn't any reason to disable it if the target processor
13958 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
13959 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
13961 SDValue Chain = Op.getOperand(0);
13962 SDValue Zero = DAG.getConstant(0, MVT::i32);
13964 DAG.getRegister(X86::ESP, MVT::i32), // Base
13965 DAG.getTargetConstant(1, MVT::i8), // Scale
13966 DAG.getRegister(0, MVT::i32), // Index
13967 DAG.getTargetConstant(0, MVT::i32), // Disp
13968 DAG.getRegister(0, MVT::i32), // Segment.
13972 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
13973 return SDValue(Res, 0);
13976 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
13977 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
13980 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
13981 SelectionDAG &DAG) {
13982 MVT T = Op.getSimpleValueType();
13986 switch(T.SimpleTy) {
13987 default: llvm_unreachable("Invalid value type!");
13988 case MVT::i8: Reg = X86::AL; size = 1; break;
13989 case MVT::i16: Reg = X86::AX; size = 2; break;
13990 case MVT::i32: Reg = X86::EAX; size = 4; break;
13992 assert(Subtarget->is64Bit() && "Node not type legal!");
13993 Reg = X86::RAX; size = 8;
13996 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
13997 Op.getOperand(2), SDValue());
13998 SDValue Ops[] = { cpIn.getValue(0),
14001 DAG.getTargetConstant(size, MVT::i8),
14002 cpIn.getValue(1) };
14003 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14004 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
14005 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
14008 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
14012 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
14013 SelectionDAG &DAG) {
14014 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
14015 MVT DstVT = Op.getSimpleValueType();
14016 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
14017 Subtarget->hasMMX() && "Unexpected custom BITCAST");
14018 assert((DstVT == MVT::i64 ||
14019 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
14020 "Unexpected custom BITCAST");
14021 // i64 <=> MMX conversions are Legal.
14022 if (SrcVT==MVT::i64 && DstVT.isVector())
14024 if (DstVT==MVT::i64 && SrcVT.isVector())
14026 // MMX <=> MMX conversions are Legal.
14027 if (SrcVT.isVector() && DstVT.isVector())
14029 // All other conversions need to be expanded.
14033 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
14034 SDNode *Node = Op.getNode();
14036 EVT T = Node->getValueType(0);
14037 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
14038 DAG.getConstant(0, T), Node->getOperand(2));
14039 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
14040 cast<AtomicSDNode>(Node)->getMemoryVT(),
14041 Node->getOperand(0),
14042 Node->getOperand(1), negOp,
14043 cast<AtomicSDNode>(Node)->getMemOperand(),
14044 cast<AtomicSDNode>(Node)->getOrdering(),
14045 cast<AtomicSDNode>(Node)->getSynchScope());
14048 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
14049 SDNode *Node = Op.getNode();
14051 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14053 // Convert seq_cst store -> xchg
14054 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
14055 // FIXME: On 32-bit, store -> fist or movq would be more efficient
14056 // (The only way to get a 16-byte store is cmpxchg16b)
14057 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
14058 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
14059 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14060 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
14061 cast<AtomicSDNode>(Node)->getMemoryVT(),
14062 Node->getOperand(0),
14063 Node->getOperand(1), Node->getOperand(2),
14064 cast<AtomicSDNode>(Node)->getMemOperand(),
14065 cast<AtomicSDNode>(Node)->getOrdering(),
14066 cast<AtomicSDNode>(Node)->getSynchScope());
14067 return Swap.getValue(1);
14069 // Other atomic stores have a simple pattern.
14073 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
14074 EVT VT = Op.getNode()->getSimpleValueType(0);
14076 // Let legalize expand this if it isn't a legal type yet.
14077 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14080 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14083 bool ExtraOp = false;
14084 switch (Op.getOpcode()) {
14085 default: llvm_unreachable("Invalid code");
14086 case ISD::ADDC: Opc = X86ISD::ADD; break;
14087 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
14088 case ISD::SUBC: Opc = X86ISD::SUB; break;
14089 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
14093 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14095 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14096 Op.getOperand(1), Op.getOperand(2));
14099 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
14100 SelectionDAG &DAG) {
14101 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
14103 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
14104 // which returns the values as { float, float } (in XMM0) or
14105 // { double, double } (which is returned in XMM0, XMM1).
14107 SDValue Arg = Op.getOperand(0);
14108 EVT ArgVT = Arg.getValueType();
14109 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14111 TargetLowering::ArgListTy Args;
14112 TargetLowering::ArgListEntry Entry;
14116 Entry.isSExt = false;
14117 Entry.isZExt = false;
14118 Args.push_back(Entry);
14120 bool isF64 = ArgVT == MVT::f64;
14121 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
14122 // the small struct {f32, f32} is returned in (eax, edx). For f64,
14123 // the results are returned via SRet in memory.
14124 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
14125 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14126 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
14128 Type *RetTy = isF64
14129 ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
14130 : (Type*)VectorType::get(ArgTy, 4);
14132 CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
14133 false, false, false, false, 0,
14134 CallingConv::C, /*isTaillCall=*/false,
14135 /*doesNotRet=*/false, /*isReturnValueUsed*/true,
14136 Callee, Args, DAG, dl);
14137 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
14140 // Returned in xmm0 and xmm1.
14141 return CallResult.first;
14143 // Returned in bits 0:31 and 32:64 xmm0.
14144 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14145 CallResult.first, DAG.getIntPtrConstant(0));
14146 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14147 CallResult.first, DAG.getIntPtrConstant(1));
14148 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
14149 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
14152 /// LowerOperation - Provide custom lowering hooks for some operations.
14154 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
14155 switch (Op.getOpcode()) {
14156 default: llvm_unreachable("Should not custom lower this!");
14157 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
14158 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
14159 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op, Subtarget, DAG);
14160 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
14161 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
14162 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
14163 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
14164 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
14165 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
14166 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
14167 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
14168 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
14169 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
14170 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
14171 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
14172 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
14173 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
14174 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
14175 case ISD::SHL_PARTS:
14176 case ISD::SRA_PARTS:
14177 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
14178 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
14179 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
14180 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
14181 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
14182 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
14183 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
14184 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
14185 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
14186 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
14187 case ISD::FABS: return LowerFABS(Op, DAG);
14188 case ISD::FNEG: return LowerFNEG(Op, DAG);
14189 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
14190 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
14191 case ISD::SETCC: return LowerSETCC(Op, DAG);
14192 case ISD::SELECT: return LowerSELECT(Op, DAG);
14193 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
14194 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
14195 case ISD::VASTART: return LowerVASTART(Op, DAG);
14196 case ISD::VAARG: return LowerVAARG(Op, DAG);
14197 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
14198 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
14199 case ISD::INTRINSIC_VOID:
14200 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
14201 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
14202 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
14203 case ISD::FRAME_TO_ARGS_OFFSET:
14204 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
14205 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
14206 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
14207 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
14208 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
14209 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
14210 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
14211 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
14212 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
14213 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
14214 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
14215 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
14216 case ISD::UMUL_LOHI:
14217 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
14220 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
14226 case ISD::UMULO: return LowerXALUO(Op, DAG);
14227 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
14228 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
14232 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
14233 case ISD::ADD: return LowerADD(Op, DAG);
14234 case ISD::SUB: return LowerSUB(Op, DAG);
14235 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
14239 static void ReplaceATOMIC_LOAD(SDNode *Node,
14240 SmallVectorImpl<SDValue> &Results,
14241 SelectionDAG &DAG) {
14243 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14245 // Convert wide load -> cmpxchg8b/cmpxchg16b
14246 // FIXME: On 32-bit, load -> fild or movq would be more efficient
14247 // (The only way to get a 16-byte load is cmpxchg16b)
14248 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
14249 SDValue Zero = DAG.getConstant(0, VT);
14250 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
14251 Node->getOperand(0),
14252 Node->getOperand(1), Zero, Zero,
14253 cast<AtomicSDNode>(Node)->getMemOperand(),
14254 cast<AtomicSDNode>(Node)->getOrdering(),
14255 cast<AtomicSDNode>(Node)->getOrdering(),
14256 cast<AtomicSDNode>(Node)->getSynchScope());
14257 Results.push_back(Swap.getValue(0));
14258 Results.push_back(Swap.getValue(1));
14262 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
14263 SelectionDAG &DAG, unsigned NewOp) {
14265 assert (Node->getValueType(0) == MVT::i64 &&
14266 "Only know how to expand i64 atomics");
14268 SDValue Chain = Node->getOperand(0);
14269 SDValue In1 = Node->getOperand(1);
14270 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14271 Node->getOperand(2), DAG.getIntPtrConstant(0));
14272 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14273 Node->getOperand(2), DAG.getIntPtrConstant(1));
14274 SDValue Ops[] = { Chain, In1, In2L, In2H };
14275 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
14277 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, MVT::i64,
14278 cast<MemSDNode>(Node)->getMemOperand());
14279 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
14280 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF));
14281 Results.push_back(Result.getValue(2));
14284 /// ReplaceNodeResults - Replace a node with an illegal result type
14285 /// with a new node built out of custom code.
14286 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
14287 SmallVectorImpl<SDValue>&Results,
14288 SelectionDAG &DAG) const {
14290 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14291 switch (N->getOpcode()) {
14293 llvm_unreachable("Do not know how to custom type legalize this operation!");
14294 case ISD::SIGN_EXTEND_INREG:
14299 // We don't want to expand or promote these.
14301 case ISD::FP_TO_SINT:
14302 case ISD::FP_TO_UINT: {
14303 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
14305 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
14308 std::pair<SDValue,SDValue> Vals =
14309 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
14310 SDValue FIST = Vals.first, StackSlot = Vals.second;
14311 if (FIST.getNode()) {
14312 EVT VT = N->getValueType(0);
14313 // Return a load from the stack slot.
14314 if (StackSlot.getNode())
14315 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
14316 MachinePointerInfo(),
14317 false, false, false, 0));
14319 Results.push_back(FIST);
14323 case ISD::UINT_TO_FP: {
14324 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14325 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
14326 N->getValueType(0) != MVT::v2f32)
14328 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
14330 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
14332 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
14333 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
14334 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
14335 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
14336 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
14337 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
14340 case ISD::FP_ROUND: {
14341 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
14343 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
14344 Results.push_back(V);
14347 case ISD::INTRINSIC_W_CHAIN: {
14348 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
14350 default : llvm_unreachable("Do not know how to custom type "
14351 "legalize this intrinsic operation!");
14352 case Intrinsic::x86_rdtsc:
14353 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14355 case Intrinsic::x86_rdtscp:
14356 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
14360 case ISD::READCYCLECOUNTER: {
14361 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14364 case ISD::ATOMIC_CMP_SWAP: {
14365 EVT T = N->getValueType(0);
14366 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
14367 bool Regs64bit = T == MVT::i128;
14368 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
14369 SDValue cpInL, cpInH;
14370 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14371 DAG.getConstant(0, HalfT));
14372 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14373 DAG.getConstant(1, HalfT));
14374 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
14375 Regs64bit ? X86::RAX : X86::EAX,
14377 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
14378 Regs64bit ? X86::RDX : X86::EDX,
14379 cpInH, cpInL.getValue(1));
14380 SDValue swapInL, swapInH;
14381 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14382 DAG.getConstant(0, HalfT));
14383 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14384 DAG.getConstant(1, HalfT));
14385 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
14386 Regs64bit ? X86::RBX : X86::EBX,
14387 swapInL, cpInH.getValue(1));
14388 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
14389 Regs64bit ? X86::RCX : X86::ECX,
14390 swapInH, swapInL.getValue(1));
14391 SDValue Ops[] = { swapInH.getValue(0),
14393 swapInH.getValue(1) };
14394 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14395 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
14396 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
14397 X86ISD::LCMPXCHG8_DAG;
14398 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
14399 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
14400 Regs64bit ? X86::RAX : X86::EAX,
14401 HalfT, Result.getValue(1));
14402 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
14403 Regs64bit ? X86::RDX : X86::EDX,
14404 HalfT, cpOutL.getValue(2));
14405 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
14406 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
14407 Results.push_back(cpOutH.getValue(1));
14410 case ISD::ATOMIC_LOAD_ADD:
14411 case ISD::ATOMIC_LOAD_AND:
14412 case ISD::ATOMIC_LOAD_NAND:
14413 case ISD::ATOMIC_LOAD_OR:
14414 case ISD::ATOMIC_LOAD_SUB:
14415 case ISD::ATOMIC_LOAD_XOR:
14416 case ISD::ATOMIC_LOAD_MAX:
14417 case ISD::ATOMIC_LOAD_MIN:
14418 case ISD::ATOMIC_LOAD_UMAX:
14419 case ISD::ATOMIC_LOAD_UMIN:
14420 case ISD::ATOMIC_SWAP: {
14422 switch (N->getOpcode()) {
14423 default: llvm_unreachable("Unexpected opcode");
14424 case ISD::ATOMIC_LOAD_ADD:
14425 Opc = X86ISD::ATOMADD64_DAG;
14427 case ISD::ATOMIC_LOAD_AND:
14428 Opc = X86ISD::ATOMAND64_DAG;
14430 case ISD::ATOMIC_LOAD_NAND:
14431 Opc = X86ISD::ATOMNAND64_DAG;
14433 case ISD::ATOMIC_LOAD_OR:
14434 Opc = X86ISD::ATOMOR64_DAG;
14436 case ISD::ATOMIC_LOAD_SUB:
14437 Opc = X86ISD::ATOMSUB64_DAG;
14439 case ISD::ATOMIC_LOAD_XOR:
14440 Opc = X86ISD::ATOMXOR64_DAG;
14442 case ISD::ATOMIC_LOAD_MAX:
14443 Opc = X86ISD::ATOMMAX64_DAG;
14445 case ISD::ATOMIC_LOAD_MIN:
14446 Opc = X86ISD::ATOMMIN64_DAG;
14448 case ISD::ATOMIC_LOAD_UMAX:
14449 Opc = X86ISD::ATOMUMAX64_DAG;
14451 case ISD::ATOMIC_LOAD_UMIN:
14452 Opc = X86ISD::ATOMUMIN64_DAG;
14454 case ISD::ATOMIC_SWAP:
14455 Opc = X86ISD::ATOMSWAP64_DAG;
14458 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
14461 case ISD::ATOMIC_LOAD:
14462 ReplaceATOMIC_LOAD(N, Results, DAG);
14466 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
14468 default: return nullptr;
14469 case X86ISD::BSF: return "X86ISD::BSF";
14470 case X86ISD::BSR: return "X86ISD::BSR";
14471 case X86ISD::SHLD: return "X86ISD::SHLD";
14472 case X86ISD::SHRD: return "X86ISD::SHRD";
14473 case X86ISD::FAND: return "X86ISD::FAND";
14474 case X86ISD::FANDN: return "X86ISD::FANDN";
14475 case X86ISD::FOR: return "X86ISD::FOR";
14476 case X86ISD::FXOR: return "X86ISD::FXOR";
14477 case X86ISD::FSRL: return "X86ISD::FSRL";
14478 case X86ISD::FILD: return "X86ISD::FILD";
14479 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
14480 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
14481 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
14482 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
14483 case X86ISD::FLD: return "X86ISD::FLD";
14484 case X86ISD::FST: return "X86ISD::FST";
14485 case X86ISD::CALL: return "X86ISD::CALL";
14486 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
14487 case X86ISD::BT: return "X86ISD::BT";
14488 case X86ISD::CMP: return "X86ISD::CMP";
14489 case X86ISD::COMI: return "X86ISD::COMI";
14490 case X86ISD::UCOMI: return "X86ISD::UCOMI";
14491 case X86ISD::CMPM: return "X86ISD::CMPM";
14492 case X86ISD::CMPMU: return "X86ISD::CMPMU";
14493 case X86ISD::SETCC: return "X86ISD::SETCC";
14494 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
14495 case X86ISD::FSETCC: return "X86ISD::FSETCC";
14496 case X86ISD::CMOV: return "X86ISD::CMOV";
14497 case X86ISD::BRCOND: return "X86ISD::BRCOND";
14498 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
14499 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
14500 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
14501 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
14502 case X86ISD::Wrapper: return "X86ISD::Wrapper";
14503 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
14504 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
14505 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
14506 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
14507 case X86ISD::PINSRB: return "X86ISD::PINSRB";
14508 case X86ISD::PINSRW: return "X86ISD::PINSRW";
14509 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
14510 case X86ISD::ANDNP: return "X86ISD::ANDNP";
14511 case X86ISD::PSIGN: return "X86ISD::PSIGN";
14512 case X86ISD::BLENDV: return "X86ISD::BLENDV";
14513 case X86ISD::BLENDI: return "X86ISD::BLENDI";
14514 case X86ISD::SUBUS: return "X86ISD::SUBUS";
14515 case X86ISD::HADD: return "X86ISD::HADD";
14516 case X86ISD::HSUB: return "X86ISD::HSUB";
14517 case X86ISD::FHADD: return "X86ISD::FHADD";
14518 case X86ISD::FHSUB: return "X86ISD::FHSUB";
14519 case X86ISD::UMAX: return "X86ISD::UMAX";
14520 case X86ISD::UMIN: return "X86ISD::UMIN";
14521 case X86ISD::SMAX: return "X86ISD::SMAX";
14522 case X86ISD::SMIN: return "X86ISD::SMIN";
14523 case X86ISD::FMAX: return "X86ISD::FMAX";
14524 case X86ISD::FMIN: return "X86ISD::FMIN";
14525 case X86ISD::FMAXC: return "X86ISD::FMAXC";
14526 case X86ISD::FMINC: return "X86ISD::FMINC";
14527 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
14528 case X86ISD::FRCP: return "X86ISD::FRCP";
14529 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
14530 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
14531 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
14532 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
14533 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
14534 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
14535 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
14536 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
14537 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
14538 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
14539 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
14540 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
14541 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
14542 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
14543 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
14544 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
14545 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
14546 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
14547 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
14548 case X86ISD::VZEXT: return "X86ISD::VZEXT";
14549 case X86ISD::VSEXT: return "X86ISD::VSEXT";
14550 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
14551 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
14552 case X86ISD::VINSERT: return "X86ISD::VINSERT";
14553 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
14554 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
14555 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
14556 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
14557 case X86ISD::VSHL: return "X86ISD::VSHL";
14558 case X86ISD::VSRL: return "X86ISD::VSRL";
14559 case X86ISD::VSRA: return "X86ISD::VSRA";
14560 case X86ISD::VSHLI: return "X86ISD::VSHLI";
14561 case X86ISD::VSRLI: return "X86ISD::VSRLI";
14562 case X86ISD::VSRAI: return "X86ISD::VSRAI";
14563 case X86ISD::CMPP: return "X86ISD::CMPP";
14564 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
14565 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
14566 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
14567 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
14568 case X86ISD::ADD: return "X86ISD::ADD";
14569 case X86ISD::SUB: return "X86ISD::SUB";
14570 case X86ISD::ADC: return "X86ISD::ADC";
14571 case X86ISD::SBB: return "X86ISD::SBB";
14572 case X86ISD::SMUL: return "X86ISD::SMUL";
14573 case X86ISD::UMUL: return "X86ISD::UMUL";
14574 case X86ISD::INC: return "X86ISD::INC";
14575 case X86ISD::DEC: return "X86ISD::DEC";
14576 case X86ISD::OR: return "X86ISD::OR";
14577 case X86ISD::XOR: return "X86ISD::XOR";
14578 case X86ISD::AND: return "X86ISD::AND";
14579 case X86ISD::BEXTR: return "X86ISD::BEXTR";
14580 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
14581 case X86ISD::PTEST: return "X86ISD::PTEST";
14582 case X86ISD::TESTP: return "X86ISD::TESTP";
14583 case X86ISD::TESTM: return "X86ISD::TESTM";
14584 case X86ISD::TESTNM: return "X86ISD::TESTNM";
14585 case X86ISD::KORTEST: return "X86ISD::KORTEST";
14586 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
14587 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
14588 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
14589 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
14590 case X86ISD::SHUFP: return "X86ISD::SHUFP";
14591 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
14592 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
14593 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
14594 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
14595 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
14596 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
14597 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
14598 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
14599 case X86ISD::MOVSD: return "X86ISD::MOVSD";
14600 case X86ISD::MOVSS: return "X86ISD::MOVSS";
14601 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
14602 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
14603 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
14604 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
14605 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
14606 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
14607 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
14608 case X86ISD::VPERMV: return "X86ISD::VPERMV";
14609 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
14610 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
14611 case X86ISD::VPERMI: return "X86ISD::VPERMI";
14612 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
14613 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
14614 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
14615 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
14616 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
14617 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
14618 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
14619 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
14620 case X86ISD::SAHF: return "X86ISD::SAHF";
14621 case X86ISD::RDRAND: return "X86ISD::RDRAND";
14622 case X86ISD::RDSEED: return "X86ISD::RDSEED";
14623 case X86ISD::FMADD: return "X86ISD::FMADD";
14624 case X86ISD::FMSUB: return "X86ISD::FMSUB";
14625 case X86ISD::FNMADD: return "X86ISD::FNMADD";
14626 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
14627 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
14628 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
14629 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
14630 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
14631 case X86ISD::XTEST: return "X86ISD::XTEST";
14635 // isLegalAddressingMode - Return true if the addressing mode represented
14636 // by AM is legal for this target, for a load/store of the specified type.
14637 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
14639 // X86 supports extremely general addressing modes.
14640 CodeModel::Model M = getTargetMachine().getCodeModel();
14641 Reloc::Model R = getTargetMachine().getRelocationModel();
14643 // X86 allows a sign-extended 32-bit immediate field as a displacement.
14644 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
14649 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
14651 // If a reference to this global requires an extra load, we can't fold it.
14652 if (isGlobalStubReference(GVFlags))
14655 // If BaseGV requires a register for the PIC base, we cannot also have a
14656 // BaseReg specified.
14657 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
14660 // If lower 4G is not available, then we must use rip-relative addressing.
14661 if ((M != CodeModel::Small || R != Reloc::Static) &&
14662 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
14666 switch (AM.Scale) {
14672 // These scales always work.
14677 // These scales are formed with basereg+scalereg. Only accept if there is
14682 default: // Other stuff never works.
14689 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
14690 unsigned Bits = Ty->getScalarSizeInBits();
14692 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
14693 // particularly cheaper than those without.
14697 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
14698 // variable shifts just as cheap as scalar ones.
14699 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
14702 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
14703 // fully general vector.
14707 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
14708 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14710 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
14711 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
14712 return NumBits1 > NumBits2;
14715 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
14716 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14719 if (!isTypeLegal(EVT::getEVT(Ty1)))
14722 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
14724 // Assuming the caller doesn't have a zeroext or signext return parameter,
14725 // truncation all the way down to i1 is valid.
14729 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
14730 return isInt<32>(Imm);
14733 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
14734 // Can also use sub to handle negated immediates.
14735 return isInt<32>(Imm);
14738 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
14739 if (!VT1.isInteger() || !VT2.isInteger())
14741 unsigned NumBits1 = VT1.getSizeInBits();
14742 unsigned NumBits2 = VT2.getSizeInBits();
14743 return NumBits1 > NumBits2;
14746 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
14747 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14748 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
14751 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
14752 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14753 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
14756 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14757 EVT VT1 = Val.getValueType();
14758 if (isZExtFree(VT1, VT2))
14761 if (Val.getOpcode() != ISD::LOAD)
14764 if (!VT1.isSimple() || !VT1.isInteger() ||
14765 !VT2.isSimple() || !VT2.isInteger())
14768 switch (VT1.getSimpleVT().SimpleTy) {
14773 // X86 has 8, 16, and 32-bit zero-extending loads.
14781 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
14782 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
14785 VT = VT.getScalarType();
14787 if (!VT.isSimple())
14790 switch (VT.getSimpleVT().SimpleTy) {
14801 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
14802 // i16 instructions are longer (0x66 prefix) and potentially slower.
14803 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
14806 /// isShuffleMaskLegal - Targets can use this to indicate that they only
14807 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
14808 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
14809 /// are assumed to be legal.
14811 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
14813 if (!VT.isSimple())
14816 MVT SVT = VT.getSimpleVT();
14818 // Very little shuffling can be done for 64-bit vectors right now.
14819 if (VT.getSizeInBits() == 64)
14822 // FIXME: pshufb, blends, shifts.
14823 return (SVT.getVectorNumElements() == 2 ||
14824 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
14825 isMOVLMask(M, SVT) ||
14826 isSHUFPMask(M, SVT) ||
14827 isPSHUFDMask(M, SVT) ||
14828 isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
14829 isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
14830 isPALIGNRMask(M, SVT, Subtarget) ||
14831 isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
14832 isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
14833 isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
14834 isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()));
14838 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
14840 if (!VT.isSimple())
14843 MVT SVT = VT.getSimpleVT();
14844 unsigned NumElts = SVT.getVectorNumElements();
14845 // FIXME: This collection of masks seems suspect.
14848 if (NumElts == 4 && SVT.is128BitVector()) {
14849 return (isMOVLMask(Mask, SVT) ||
14850 isCommutedMOVLMask(Mask, SVT, true) ||
14851 isSHUFPMask(Mask, SVT) ||
14852 isSHUFPMask(Mask, SVT, /* Commuted */ true));
14857 //===----------------------------------------------------------------------===//
14858 // X86 Scheduler Hooks
14859 //===----------------------------------------------------------------------===//
14861 /// Utility function to emit xbegin specifying the start of an RTM region.
14862 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
14863 const TargetInstrInfo *TII) {
14864 DebugLoc DL = MI->getDebugLoc();
14866 const BasicBlock *BB = MBB->getBasicBlock();
14867 MachineFunction::iterator I = MBB;
14870 // For the v = xbegin(), we generate
14881 MachineBasicBlock *thisMBB = MBB;
14882 MachineFunction *MF = MBB->getParent();
14883 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14884 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14885 MF->insert(I, mainMBB);
14886 MF->insert(I, sinkMBB);
14888 // Transfer the remainder of BB and its successor edges to sinkMBB.
14889 sinkMBB->splice(sinkMBB->begin(), MBB,
14890 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
14891 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14895 // # fallthrough to mainMBB
14896 // # abortion to sinkMBB
14897 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
14898 thisMBB->addSuccessor(mainMBB);
14899 thisMBB->addSuccessor(sinkMBB);
14903 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
14904 mainMBB->addSuccessor(sinkMBB);
14907 // EAX is live into the sinkMBB
14908 sinkMBB->addLiveIn(X86::EAX);
14909 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14910 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14913 MI->eraseFromParent();
14917 // Get CMPXCHG opcode for the specified data type.
14918 static unsigned getCmpXChgOpcode(EVT VT) {
14919 switch (VT.getSimpleVT().SimpleTy) {
14920 case MVT::i8: return X86::LCMPXCHG8;
14921 case MVT::i16: return X86::LCMPXCHG16;
14922 case MVT::i32: return X86::LCMPXCHG32;
14923 case MVT::i64: return X86::LCMPXCHG64;
14927 llvm_unreachable("Invalid operand size!");
14930 // Get LOAD opcode for the specified data type.
14931 static unsigned getLoadOpcode(EVT VT) {
14932 switch (VT.getSimpleVT().SimpleTy) {
14933 case MVT::i8: return X86::MOV8rm;
14934 case MVT::i16: return X86::MOV16rm;
14935 case MVT::i32: return X86::MOV32rm;
14936 case MVT::i64: return X86::MOV64rm;
14940 llvm_unreachable("Invalid operand size!");
14943 // Get opcode of the non-atomic one from the specified atomic instruction.
14944 static unsigned getNonAtomicOpcode(unsigned Opc) {
14946 case X86::ATOMAND8: return X86::AND8rr;
14947 case X86::ATOMAND16: return X86::AND16rr;
14948 case X86::ATOMAND32: return X86::AND32rr;
14949 case X86::ATOMAND64: return X86::AND64rr;
14950 case X86::ATOMOR8: return X86::OR8rr;
14951 case X86::ATOMOR16: return X86::OR16rr;
14952 case X86::ATOMOR32: return X86::OR32rr;
14953 case X86::ATOMOR64: return X86::OR64rr;
14954 case X86::ATOMXOR8: return X86::XOR8rr;
14955 case X86::ATOMXOR16: return X86::XOR16rr;
14956 case X86::ATOMXOR32: return X86::XOR32rr;
14957 case X86::ATOMXOR64: return X86::XOR64rr;
14959 llvm_unreachable("Unhandled atomic-load-op opcode!");
14962 // Get opcode of the non-atomic one from the specified atomic instruction with
14964 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
14965 unsigned &ExtraOpc) {
14967 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr;
14968 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr;
14969 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr;
14970 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr;
14971 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr;
14972 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
14973 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
14974 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
14975 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr;
14976 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
14977 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
14978 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
14979 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr;
14980 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
14981 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
14982 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
14983 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr;
14984 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
14985 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
14986 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
14988 llvm_unreachable("Unhandled atomic-load-op opcode!");
14991 // Get opcode of the non-atomic one from the specified atomic instruction for
14992 // 64-bit data type on 32-bit target.
14993 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
14995 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr;
14996 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr;
14997 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr;
14998 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr;
14999 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr;
15000 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
15001 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr;
15002 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr;
15003 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr;
15004 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr;
15006 llvm_unreachable("Unhandled atomic-load-op opcode!");
15009 // Get opcode of the non-atomic one from the specified atomic instruction for
15010 // 64-bit data type on 32-bit target with extra opcode.
15011 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
15013 unsigned &ExtraOpc) {
15015 case X86::ATOMNAND6432:
15016 ExtraOpc = X86::NOT32r;
15017 HiOpc = X86::AND32rr;
15018 return X86::AND32rr;
15020 llvm_unreachable("Unhandled atomic-load-op opcode!");
15023 // Get pseudo CMOV opcode from the specified data type.
15024 static unsigned getPseudoCMOVOpc(EVT VT) {
15025 switch (VT.getSimpleVT().SimpleTy) {
15026 case MVT::i8: return X86::CMOV_GR8;
15027 case MVT::i16: return X86::CMOV_GR16;
15028 case MVT::i32: return X86::CMOV_GR32;
15032 llvm_unreachable("Unknown CMOV opcode!");
15035 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
15036 // They will be translated into a spin-loop or compare-exchange loop from
15039 // dst = atomic-fetch-op MI.addr, MI.val
15045 // t1 = LOAD MI.addr
15047 // t4 = phi(t1, t3 / loop)
15048 // t2 = OP MI.val, t4
15050 // LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
15056 MachineBasicBlock *
15057 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
15058 MachineBasicBlock *MBB) const {
15059 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15060 DebugLoc DL = MI->getDebugLoc();
15062 MachineFunction *MF = MBB->getParent();
15063 MachineRegisterInfo &MRI = MF->getRegInfo();
15065 const BasicBlock *BB = MBB->getBasicBlock();
15066 MachineFunction::iterator I = MBB;
15069 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
15070 "Unexpected number of operands");
15072 assert(MI->hasOneMemOperand() &&
15073 "Expected atomic-load-op to have one memoperand");
15075 // Memory Reference
15076 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15077 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15079 unsigned DstReg, SrcReg;
15080 unsigned MemOpndSlot;
15082 unsigned CurOp = 0;
15084 DstReg = MI->getOperand(CurOp++).getReg();
15085 MemOpndSlot = CurOp;
15086 CurOp += X86::AddrNumOperands;
15087 SrcReg = MI->getOperand(CurOp++).getReg();
15089 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15090 MVT::SimpleValueType VT = *RC->vt_begin();
15091 unsigned t1 = MRI.createVirtualRegister(RC);
15092 unsigned t2 = MRI.createVirtualRegister(RC);
15093 unsigned t3 = MRI.createVirtualRegister(RC);
15094 unsigned t4 = MRI.createVirtualRegister(RC);
15095 unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
15097 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
15098 unsigned LOADOpc = getLoadOpcode(VT);
15100 // For the atomic load-arith operator, we generate
15103 // t1 = LOAD [MI.addr]
15105 // t4 = phi(t1 / thisMBB, t3 / mainMBB)
15106 // t1 = OP MI.val, EAX
15108 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
15114 MachineBasicBlock *thisMBB = MBB;
15115 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15116 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15117 MF->insert(I, mainMBB);
15118 MF->insert(I, sinkMBB);
15120 MachineInstrBuilder MIB;
15122 // Transfer the remainder of BB and its successor edges to sinkMBB.
15123 sinkMBB->splice(sinkMBB->begin(), MBB,
15124 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15125 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15128 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
15129 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15130 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15132 NewMO.setIsKill(false);
15133 MIB.addOperand(NewMO);
15135 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15136 unsigned flags = (*MMOI)->getFlags();
15137 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15138 MachineMemOperand *MMO =
15139 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15140 (*MMOI)->getSize(),
15141 (*MMOI)->getBaseAlignment(),
15142 (*MMOI)->getTBAAInfo(),
15143 (*MMOI)->getRanges());
15144 MIB.addMemOperand(MMO);
15147 thisMBB->addSuccessor(mainMBB);
15150 MachineBasicBlock *origMainMBB = mainMBB;
15153 MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
15154 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15156 unsigned Opc = MI->getOpcode();
15159 llvm_unreachable("Unhandled atomic-load-op opcode!");
15160 case X86::ATOMAND8:
15161 case X86::ATOMAND16:
15162 case X86::ATOMAND32:
15163 case X86::ATOMAND64:
15165 case X86::ATOMOR16:
15166 case X86::ATOMOR32:
15167 case X86::ATOMOR64:
15168 case X86::ATOMXOR8:
15169 case X86::ATOMXOR16:
15170 case X86::ATOMXOR32:
15171 case X86::ATOMXOR64: {
15172 unsigned ARITHOpc = getNonAtomicOpcode(Opc);
15173 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
15177 case X86::ATOMNAND8:
15178 case X86::ATOMNAND16:
15179 case X86::ATOMNAND32:
15180 case X86::ATOMNAND64: {
15181 unsigned Tmp = MRI.createVirtualRegister(RC);
15183 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
15184 BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
15186 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
15189 case X86::ATOMMAX8:
15190 case X86::ATOMMAX16:
15191 case X86::ATOMMAX32:
15192 case X86::ATOMMAX64:
15193 case X86::ATOMMIN8:
15194 case X86::ATOMMIN16:
15195 case X86::ATOMMIN32:
15196 case X86::ATOMMIN64:
15197 case X86::ATOMUMAX8:
15198 case X86::ATOMUMAX16:
15199 case X86::ATOMUMAX32:
15200 case X86::ATOMUMAX64:
15201 case X86::ATOMUMIN8:
15202 case X86::ATOMUMIN16:
15203 case X86::ATOMUMIN32:
15204 case X86::ATOMUMIN64: {
15206 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
15208 BuildMI(mainMBB, DL, TII->get(CMPOpc))
15212 if (Subtarget->hasCMov()) {
15213 if (VT != MVT::i8) {
15215 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
15219 // Promote i8 to i32 to use CMOV32
15220 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15221 const TargetRegisterClass *RC32 =
15222 TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
15223 unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
15224 unsigned AccReg32 = MRI.createVirtualRegister(RC32);
15225 unsigned Tmp = MRI.createVirtualRegister(RC32);
15227 unsigned Undef = MRI.createVirtualRegister(RC32);
15228 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
15230 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
15233 .addImm(X86::sub_8bit);
15234 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
15237 .addImm(X86::sub_8bit);
15239 BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
15243 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
15244 .addReg(Tmp, 0, X86::sub_8bit);
15247 // Use pseudo select and lower them.
15248 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
15249 "Invalid atomic-load-op transformation!");
15250 unsigned SelOpc = getPseudoCMOVOpc(VT);
15251 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
15252 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
15253 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
15254 .addReg(SrcReg).addReg(t4)
15256 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15257 // Replace the original PHI node as mainMBB is changed after CMOV
15259 BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
15260 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15261 Phi->eraseFromParent();
15267 // Copy PhyReg back from virtual register.
15268 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
15271 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15272 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15273 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15275 NewMO.setIsKill(false);
15276 MIB.addOperand(NewMO);
15279 MIB.setMemRefs(MMOBegin, MMOEnd);
15281 // Copy PhyReg back to virtual register.
15282 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
15285 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15287 mainMBB->addSuccessor(origMainMBB);
15288 mainMBB->addSuccessor(sinkMBB);
15291 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15292 TII->get(TargetOpcode::COPY), DstReg)
15295 MI->eraseFromParent();
15299 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
15300 // instructions. They will be translated into a spin-loop or compare-exchange
15304 // dst = atomic-fetch-op MI.addr, MI.val
15310 // t1L = LOAD [MI.addr + 0]
15311 // t1H = LOAD [MI.addr + 4]
15313 // t4L = phi(t1L, t3L / loop)
15314 // t4H = phi(t1H, t3H / loop)
15315 // t2L = OP MI.val.lo, t4L
15316 // t2H = OP MI.val.hi, t4H
15321 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15329 MachineBasicBlock *
15330 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
15331 MachineBasicBlock *MBB) const {
15332 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15333 DebugLoc DL = MI->getDebugLoc();
15335 MachineFunction *MF = MBB->getParent();
15336 MachineRegisterInfo &MRI = MF->getRegInfo();
15338 const BasicBlock *BB = MBB->getBasicBlock();
15339 MachineFunction::iterator I = MBB;
15342 assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
15343 "Unexpected number of operands");
15345 assert(MI->hasOneMemOperand() &&
15346 "Expected atomic-load-op32 to have one memoperand");
15348 // Memory Reference
15349 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15350 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15352 unsigned DstLoReg, DstHiReg;
15353 unsigned SrcLoReg, SrcHiReg;
15354 unsigned MemOpndSlot;
15356 unsigned CurOp = 0;
15358 DstLoReg = MI->getOperand(CurOp++).getReg();
15359 DstHiReg = MI->getOperand(CurOp++).getReg();
15360 MemOpndSlot = CurOp;
15361 CurOp += X86::AddrNumOperands;
15362 SrcLoReg = MI->getOperand(CurOp++).getReg();
15363 SrcHiReg = MI->getOperand(CurOp++).getReg();
15365 const TargetRegisterClass *RC = &X86::GR32RegClass;
15366 const TargetRegisterClass *RC8 = &X86::GR8RegClass;
15368 unsigned t1L = MRI.createVirtualRegister(RC);
15369 unsigned t1H = MRI.createVirtualRegister(RC);
15370 unsigned t2L = MRI.createVirtualRegister(RC);
15371 unsigned t2H = MRI.createVirtualRegister(RC);
15372 unsigned t3L = MRI.createVirtualRegister(RC);
15373 unsigned t3H = MRI.createVirtualRegister(RC);
15374 unsigned t4L = MRI.createVirtualRegister(RC);
15375 unsigned t4H = MRI.createVirtualRegister(RC);
15377 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
15378 unsigned LOADOpc = X86::MOV32rm;
15380 // For the atomic load-arith operator, we generate
15383 // t1L = LOAD [MI.addr + 0]
15384 // t1H = LOAD [MI.addr + 4]
15386 // t4L = phi(t1L / thisMBB, t3L / mainMBB)
15387 // t4H = phi(t1H / thisMBB, t3H / mainMBB)
15388 // t2L = OP MI.val.lo, t4L
15389 // t2H = OP MI.val.hi, t4H
15392 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15400 MachineBasicBlock *thisMBB = MBB;
15401 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15402 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15403 MF->insert(I, mainMBB);
15404 MF->insert(I, sinkMBB);
15406 MachineInstrBuilder MIB;
15408 // Transfer the remainder of BB and its successor edges to sinkMBB.
15409 sinkMBB->splice(sinkMBB->begin(), MBB,
15410 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15411 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15415 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
15416 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15417 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15419 NewMO.setIsKill(false);
15420 MIB.addOperand(NewMO);
15422 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15423 unsigned flags = (*MMOI)->getFlags();
15424 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15425 MachineMemOperand *MMO =
15426 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15427 (*MMOI)->getSize(),
15428 (*MMOI)->getBaseAlignment(),
15429 (*MMOI)->getTBAAInfo(),
15430 (*MMOI)->getRanges());
15431 MIB.addMemOperand(MMO);
15433 MachineInstr *LowMI = MIB;
15436 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
15437 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15438 if (i == X86::AddrDisp) {
15439 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
15441 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15443 NewMO.setIsKill(false);
15444 MIB.addOperand(NewMO);
15447 MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
15449 thisMBB->addSuccessor(mainMBB);
15452 MachineBasicBlock *origMainMBB = mainMBB;
15455 MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
15456 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15457 MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
15458 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15460 unsigned Opc = MI->getOpcode();
15463 llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
15464 case X86::ATOMAND6432:
15465 case X86::ATOMOR6432:
15466 case X86::ATOMXOR6432:
15467 case X86::ATOMADD6432:
15468 case X86::ATOMSUB6432: {
15470 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15471 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
15473 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
15477 case X86::ATOMNAND6432: {
15478 unsigned HiOpc, NOTOpc;
15479 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
15480 unsigned TmpL = MRI.createVirtualRegister(RC);
15481 unsigned TmpH = MRI.createVirtualRegister(RC);
15482 BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
15484 BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
15486 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
15487 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
15490 case X86::ATOMMAX6432:
15491 case X86::ATOMMIN6432:
15492 case X86::ATOMUMAX6432:
15493 case X86::ATOMUMIN6432: {
15495 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15496 unsigned cL = MRI.createVirtualRegister(RC8);
15497 unsigned cH = MRI.createVirtualRegister(RC8);
15498 unsigned cL32 = MRI.createVirtualRegister(RC);
15499 unsigned cH32 = MRI.createVirtualRegister(RC);
15500 unsigned cc = MRI.createVirtualRegister(RC);
15501 // cl := cmp src_lo, lo
15502 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15503 .addReg(SrcLoReg).addReg(t4L);
15504 BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
15505 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
15506 // ch := cmp src_hi, hi
15507 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15508 .addReg(SrcHiReg).addReg(t4H);
15509 BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
15510 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
15511 // cc := if (src_hi == hi) ? cl : ch;
15512 if (Subtarget->hasCMov()) {
15513 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
15514 .addReg(cH32).addReg(cL32);
15516 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
15517 .addReg(cH32).addReg(cL32)
15518 .addImm(X86::COND_E);
15519 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15521 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
15522 if (Subtarget->hasCMov()) {
15523 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
15524 .addReg(SrcLoReg).addReg(t4L);
15525 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
15526 .addReg(SrcHiReg).addReg(t4H);
15528 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
15529 .addReg(SrcLoReg).addReg(t4L)
15530 .addImm(X86::COND_NE);
15531 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15532 // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
15533 // 2nd CMOV lowering.
15534 mainMBB->addLiveIn(X86::EFLAGS);
15535 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
15536 .addReg(SrcHiReg).addReg(t4H)
15537 .addImm(X86::COND_NE);
15538 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15539 // Replace the original PHI node as mainMBB is changed after CMOV
15541 BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
15542 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15543 BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
15544 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15545 PhiL->eraseFromParent();
15546 PhiH->eraseFromParent();
15550 case X86::ATOMSWAP6432: {
15552 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15553 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
15554 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
15559 // Copy EDX:EAX back from HiReg:LoReg
15560 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
15561 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
15562 // Copy ECX:EBX from t1H:t1L
15563 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
15564 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
15566 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15567 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15568 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15570 NewMO.setIsKill(false);
15571 MIB.addOperand(NewMO);
15573 MIB.setMemRefs(MMOBegin, MMOEnd);
15575 // Copy EDX:EAX back to t3H:t3L
15576 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
15577 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
15579 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15581 mainMBB->addSuccessor(origMainMBB);
15582 mainMBB->addSuccessor(sinkMBB);
15585 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15586 TII->get(TargetOpcode::COPY), DstLoReg)
15588 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15589 TII->get(TargetOpcode::COPY), DstHiReg)
15592 MI->eraseFromParent();
15596 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
15597 // or XMM0_V32I8 in AVX all of this code can be replaced with that
15598 // in the .td file.
15599 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
15600 const TargetInstrInfo *TII) {
15602 switch (MI->getOpcode()) {
15603 default: llvm_unreachable("illegal opcode!");
15604 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
15605 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
15606 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
15607 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
15608 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
15609 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
15610 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
15611 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
15614 DebugLoc dl = MI->getDebugLoc();
15615 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15617 unsigned NumArgs = MI->getNumOperands();
15618 for (unsigned i = 1; i < NumArgs; ++i) {
15619 MachineOperand &Op = MI->getOperand(i);
15620 if (!(Op.isReg() && Op.isImplicit()))
15621 MIB.addOperand(Op);
15623 if (MI->hasOneMemOperand())
15624 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15626 BuildMI(*BB, MI, dl,
15627 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15628 .addReg(X86::XMM0);
15630 MI->eraseFromParent();
15634 // FIXME: Custom handling because TableGen doesn't support multiple implicit
15635 // defs in an instruction pattern
15636 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
15637 const TargetInstrInfo *TII) {
15639 switch (MI->getOpcode()) {
15640 default: llvm_unreachable("illegal opcode!");
15641 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
15642 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
15643 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
15644 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
15645 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
15646 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
15647 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
15648 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
15651 DebugLoc dl = MI->getDebugLoc();
15652 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15654 unsigned NumArgs = MI->getNumOperands(); // remove the results
15655 for (unsigned i = 1; i < NumArgs; ++i) {
15656 MachineOperand &Op = MI->getOperand(i);
15657 if (!(Op.isReg() && Op.isImplicit()))
15658 MIB.addOperand(Op);
15660 if (MI->hasOneMemOperand())
15661 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15663 BuildMI(*BB, MI, dl,
15664 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15667 MI->eraseFromParent();
15671 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
15672 const TargetInstrInfo *TII,
15673 const X86Subtarget* Subtarget) {
15674 DebugLoc dl = MI->getDebugLoc();
15676 // Address into RAX/EAX, other two args into ECX, EDX.
15677 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
15678 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
15679 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
15680 for (int i = 0; i < X86::AddrNumOperands; ++i)
15681 MIB.addOperand(MI->getOperand(i));
15683 unsigned ValOps = X86::AddrNumOperands;
15684 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
15685 .addReg(MI->getOperand(ValOps).getReg());
15686 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
15687 .addReg(MI->getOperand(ValOps+1).getReg());
15689 // The instruction doesn't actually take any operands though.
15690 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
15692 MI->eraseFromParent(); // The pseudo is gone now.
15696 MachineBasicBlock *
15697 X86TargetLowering::EmitVAARG64WithCustomInserter(
15699 MachineBasicBlock *MBB) const {
15700 // Emit va_arg instruction on X86-64.
15702 // Operands to this pseudo-instruction:
15703 // 0 ) Output : destination address (reg)
15704 // 1-5) Input : va_list address (addr, i64mem)
15705 // 6 ) ArgSize : Size (in bytes) of vararg type
15706 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
15707 // 8 ) Align : Alignment of type
15708 // 9 ) EFLAGS (implicit-def)
15710 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
15711 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
15713 unsigned DestReg = MI->getOperand(0).getReg();
15714 MachineOperand &Base = MI->getOperand(1);
15715 MachineOperand &Scale = MI->getOperand(2);
15716 MachineOperand &Index = MI->getOperand(3);
15717 MachineOperand &Disp = MI->getOperand(4);
15718 MachineOperand &Segment = MI->getOperand(5);
15719 unsigned ArgSize = MI->getOperand(6).getImm();
15720 unsigned ArgMode = MI->getOperand(7).getImm();
15721 unsigned Align = MI->getOperand(8).getImm();
15723 // Memory Reference
15724 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
15725 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15726 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15728 // Machine Information
15729 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15730 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
15731 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
15732 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
15733 DebugLoc DL = MI->getDebugLoc();
15735 // struct va_list {
15738 // i64 overflow_area (address)
15739 // i64 reg_save_area (address)
15741 // sizeof(va_list) = 24
15742 // alignment(va_list) = 8
15744 unsigned TotalNumIntRegs = 6;
15745 unsigned TotalNumXMMRegs = 8;
15746 bool UseGPOffset = (ArgMode == 1);
15747 bool UseFPOffset = (ArgMode == 2);
15748 unsigned MaxOffset = TotalNumIntRegs * 8 +
15749 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
15751 /* Align ArgSize to a multiple of 8 */
15752 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
15753 bool NeedsAlign = (Align > 8);
15755 MachineBasicBlock *thisMBB = MBB;
15756 MachineBasicBlock *overflowMBB;
15757 MachineBasicBlock *offsetMBB;
15758 MachineBasicBlock *endMBB;
15760 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
15761 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
15762 unsigned OffsetReg = 0;
15764 if (!UseGPOffset && !UseFPOffset) {
15765 // If we only pull from the overflow region, we don't create a branch.
15766 // We don't need to alter control flow.
15767 OffsetDestReg = 0; // unused
15768 OverflowDestReg = DestReg;
15770 offsetMBB = nullptr;
15771 overflowMBB = thisMBB;
15774 // First emit code to check if gp_offset (or fp_offset) is below the bound.
15775 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
15776 // If not, pull from overflow_area. (branch to overflowMBB)
15781 // offsetMBB overflowMBB
15786 // Registers for the PHI in endMBB
15787 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
15788 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
15790 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15791 MachineFunction *MF = MBB->getParent();
15792 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15793 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15794 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15796 MachineFunction::iterator MBBIter = MBB;
15799 // Insert the new basic blocks
15800 MF->insert(MBBIter, offsetMBB);
15801 MF->insert(MBBIter, overflowMBB);
15802 MF->insert(MBBIter, endMBB);
15804 // Transfer the remainder of MBB and its successor edges to endMBB.
15805 endMBB->splice(endMBB->begin(), thisMBB,
15806 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
15807 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
15809 // Make offsetMBB and overflowMBB successors of thisMBB
15810 thisMBB->addSuccessor(offsetMBB);
15811 thisMBB->addSuccessor(overflowMBB);
15813 // endMBB is a successor of both offsetMBB and overflowMBB
15814 offsetMBB->addSuccessor(endMBB);
15815 overflowMBB->addSuccessor(endMBB);
15817 // Load the offset value into a register
15818 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15819 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
15823 .addDisp(Disp, UseFPOffset ? 4 : 0)
15824 .addOperand(Segment)
15825 .setMemRefs(MMOBegin, MMOEnd);
15827 // Check if there is enough room left to pull this argument.
15828 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
15830 .addImm(MaxOffset + 8 - ArgSizeA8);
15832 // Branch to "overflowMBB" if offset >= max
15833 // Fall through to "offsetMBB" otherwise
15834 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
15835 .addMBB(overflowMBB);
15838 // In offsetMBB, emit code to use the reg_save_area.
15840 assert(OffsetReg != 0);
15842 // Read the reg_save_area address.
15843 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
15844 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
15849 .addOperand(Segment)
15850 .setMemRefs(MMOBegin, MMOEnd);
15852 // Zero-extend the offset
15853 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
15854 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
15857 .addImm(X86::sub_32bit);
15859 // Add the offset to the reg_save_area to get the final address.
15860 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
15861 .addReg(OffsetReg64)
15862 .addReg(RegSaveReg);
15864 // Compute the offset for the next argument
15865 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15866 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
15868 .addImm(UseFPOffset ? 16 : 8);
15870 // Store it back into the va_list.
15871 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
15875 .addDisp(Disp, UseFPOffset ? 4 : 0)
15876 .addOperand(Segment)
15877 .addReg(NextOffsetReg)
15878 .setMemRefs(MMOBegin, MMOEnd);
15881 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
15886 // Emit code to use overflow area
15889 // Load the overflow_area address into a register.
15890 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
15891 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
15896 .addOperand(Segment)
15897 .setMemRefs(MMOBegin, MMOEnd);
15899 // If we need to align it, do so. Otherwise, just copy the address
15900 // to OverflowDestReg.
15902 // Align the overflow address
15903 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
15904 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
15906 // aligned_addr = (addr + (align-1)) & ~(align-1)
15907 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
15908 .addReg(OverflowAddrReg)
15911 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
15913 .addImm(~(uint64_t)(Align-1));
15915 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
15916 .addReg(OverflowAddrReg);
15919 // Compute the next overflow address after this argument.
15920 // (the overflow address should be kept 8-byte aligned)
15921 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
15922 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
15923 .addReg(OverflowDestReg)
15924 .addImm(ArgSizeA8);
15926 // Store the new overflow address.
15927 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
15932 .addOperand(Segment)
15933 .addReg(NextAddrReg)
15934 .setMemRefs(MMOBegin, MMOEnd);
15936 // If we branched, emit the PHI to the front of endMBB.
15938 BuildMI(*endMBB, endMBB->begin(), DL,
15939 TII->get(X86::PHI), DestReg)
15940 .addReg(OffsetDestReg).addMBB(offsetMBB)
15941 .addReg(OverflowDestReg).addMBB(overflowMBB);
15944 // Erase the pseudo instruction
15945 MI->eraseFromParent();
15950 MachineBasicBlock *
15951 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
15953 MachineBasicBlock *MBB) const {
15954 // Emit code to save XMM registers to the stack. The ABI says that the
15955 // number of registers to save is given in %al, so it's theoretically
15956 // possible to do an indirect jump trick to avoid saving all of them,
15957 // however this code takes a simpler approach and just executes all
15958 // of the stores if %al is non-zero. It's less code, and it's probably
15959 // easier on the hardware branch predictor, and stores aren't all that
15960 // expensive anyway.
15962 // Create the new basic blocks. One block contains all the XMM stores,
15963 // and one block is the final destination regardless of whether any
15964 // stores were performed.
15965 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15966 MachineFunction *F = MBB->getParent();
15967 MachineFunction::iterator MBBIter = MBB;
15969 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
15970 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
15971 F->insert(MBBIter, XMMSaveMBB);
15972 F->insert(MBBIter, EndMBB);
15974 // Transfer the remainder of MBB and its successor edges to EndMBB.
15975 EndMBB->splice(EndMBB->begin(), MBB,
15976 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15977 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
15979 // The original block will now fall through to the XMM save block.
15980 MBB->addSuccessor(XMMSaveMBB);
15981 // The XMMSaveMBB will fall through to the end block.
15982 XMMSaveMBB->addSuccessor(EndMBB);
15984 // Now add the instructions.
15985 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15986 DebugLoc DL = MI->getDebugLoc();
15988 unsigned CountReg = MI->getOperand(0).getReg();
15989 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
15990 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
15992 if (!Subtarget->isTargetWin64()) {
15993 // If %al is 0, branch around the XMM save block.
15994 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
15995 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
15996 MBB->addSuccessor(EndMBB);
15999 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
16000 // that was just emitted, but clearly shouldn't be "saved".
16001 assert((MI->getNumOperands() <= 3 ||
16002 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
16003 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
16004 && "Expected last argument to be EFLAGS");
16005 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
16006 // In the XMM save block, save all the XMM argument registers.
16007 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
16008 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
16009 MachineMemOperand *MMO =
16010 F->getMachineMemOperand(
16011 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
16012 MachineMemOperand::MOStore,
16013 /*Size=*/16, /*Align=*/16);
16014 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
16015 .addFrameIndex(RegSaveFrameIndex)
16016 .addImm(/*Scale=*/1)
16017 .addReg(/*IndexReg=*/0)
16018 .addImm(/*Disp=*/Offset)
16019 .addReg(/*Segment=*/0)
16020 .addReg(MI->getOperand(i).getReg())
16021 .addMemOperand(MMO);
16024 MI->eraseFromParent(); // The pseudo instruction is gone now.
16029 // The EFLAGS operand of SelectItr might be missing a kill marker
16030 // because there were multiple uses of EFLAGS, and ISel didn't know
16031 // which to mark. Figure out whether SelectItr should have had a
16032 // kill marker, and set it if it should. Returns the correct kill
16034 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
16035 MachineBasicBlock* BB,
16036 const TargetRegisterInfo* TRI) {
16037 // Scan forward through BB for a use/def of EFLAGS.
16038 MachineBasicBlock::iterator miI(std::next(SelectItr));
16039 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
16040 const MachineInstr& mi = *miI;
16041 if (mi.readsRegister(X86::EFLAGS))
16043 if (mi.definesRegister(X86::EFLAGS))
16044 break; // Should have kill-flag - update below.
16047 // If we hit the end of the block, check whether EFLAGS is live into a
16049 if (miI == BB->end()) {
16050 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
16051 sEnd = BB->succ_end();
16052 sItr != sEnd; ++sItr) {
16053 MachineBasicBlock* succ = *sItr;
16054 if (succ->isLiveIn(X86::EFLAGS))
16059 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
16060 // out. SelectMI should have a kill flag on EFLAGS.
16061 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
16065 MachineBasicBlock *
16066 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
16067 MachineBasicBlock *BB) const {
16068 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16069 DebugLoc DL = MI->getDebugLoc();
16071 // To "insert" a SELECT_CC instruction, we actually have to insert the
16072 // diamond control-flow pattern. The incoming instruction knows the
16073 // destination vreg to set, the condition code register to branch on, the
16074 // true/false values to select between, and a branch opcode to use.
16075 const BasicBlock *LLVM_BB = BB->getBasicBlock();
16076 MachineFunction::iterator It = BB;
16082 // cmpTY ccX, r1, r2
16084 // fallthrough --> copy0MBB
16085 MachineBasicBlock *thisMBB = BB;
16086 MachineFunction *F = BB->getParent();
16087 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
16088 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
16089 F->insert(It, copy0MBB);
16090 F->insert(It, sinkMBB);
16092 // If the EFLAGS register isn't dead in the terminator, then claim that it's
16093 // live into the sink and copy blocks.
16094 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
16095 if (!MI->killsRegister(X86::EFLAGS) &&
16096 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
16097 copy0MBB->addLiveIn(X86::EFLAGS);
16098 sinkMBB->addLiveIn(X86::EFLAGS);
16101 // Transfer the remainder of BB and its successor edges to sinkMBB.
16102 sinkMBB->splice(sinkMBB->begin(), BB,
16103 std::next(MachineBasicBlock::iterator(MI)), BB->end());
16104 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
16106 // Add the true and fallthrough blocks as its successors.
16107 BB->addSuccessor(copy0MBB);
16108 BB->addSuccessor(sinkMBB);
16110 // Create the conditional branch instruction.
16112 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
16113 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
16116 // %FalseValue = ...
16117 // # fallthrough to sinkMBB
16118 copy0MBB->addSuccessor(sinkMBB);
16121 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
16123 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16124 TII->get(X86::PHI), MI->getOperand(0).getReg())
16125 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
16126 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
16128 MI->eraseFromParent(); // The pseudo instruction is gone now.
16132 MachineBasicBlock *
16133 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
16134 bool Is64Bit) const {
16135 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16136 DebugLoc DL = MI->getDebugLoc();
16137 MachineFunction *MF = BB->getParent();
16138 const BasicBlock *LLVM_BB = BB->getBasicBlock();
16140 assert(MF->shouldSplitStack());
16142 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
16143 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
16146 // ... [Till the alloca]
16147 // If stacklet is not large enough, jump to mallocMBB
16150 // Allocate by subtracting from RSP
16151 // Jump to continueMBB
16154 // Allocate by call to runtime
16158 // [rest of original BB]
16161 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16162 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16163 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16165 MachineRegisterInfo &MRI = MF->getRegInfo();
16166 const TargetRegisterClass *AddrRegClass =
16167 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
16169 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16170 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16171 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
16172 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
16173 sizeVReg = MI->getOperand(1).getReg(),
16174 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
16176 MachineFunction::iterator MBBIter = BB;
16179 MF->insert(MBBIter, bumpMBB);
16180 MF->insert(MBBIter, mallocMBB);
16181 MF->insert(MBBIter, continueMBB);
16183 continueMBB->splice(continueMBB->begin(), BB,
16184 std::next(MachineBasicBlock::iterator(MI)), BB->end());
16185 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
16187 // Add code to the main basic block to check if the stack limit has been hit,
16188 // and if so, jump to mallocMBB otherwise to bumpMBB.
16189 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
16190 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
16191 .addReg(tmpSPVReg).addReg(sizeVReg);
16192 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
16193 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
16194 .addReg(SPLimitVReg);
16195 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
16197 // bumpMBB simply decreases the stack pointer, since we know the current
16198 // stacklet has enough space.
16199 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
16200 .addReg(SPLimitVReg);
16201 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
16202 .addReg(SPLimitVReg);
16203 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16205 // Calls into a routine in libgcc to allocate more space from the heap.
16206 const uint32_t *RegMask =
16207 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16209 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
16211 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
16212 .addExternalSymbol("__morestack_allocate_stack_space")
16213 .addRegMask(RegMask)
16214 .addReg(X86::RDI, RegState::Implicit)
16215 .addReg(X86::RAX, RegState::ImplicitDefine);
16217 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
16219 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
16220 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
16221 .addExternalSymbol("__morestack_allocate_stack_space")
16222 .addRegMask(RegMask)
16223 .addReg(X86::EAX, RegState::ImplicitDefine);
16227 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
16230 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
16231 .addReg(Is64Bit ? X86::RAX : X86::EAX);
16232 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16234 // Set up the CFG correctly.
16235 BB->addSuccessor(bumpMBB);
16236 BB->addSuccessor(mallocMBB);
16237 mallocMBB->addSuccessor(continueMBB);
16238 bumpMBB->addSuccessor(continueMBB);
16240 // Take care of the PHI nodes.
16241 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
16242 MI->getOperand(0).getReg())
16243 .addReg(mallocPtrVReg).addMBB(mallocMBB)
16244 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
16246 // Delete the original pseudo instruction.
16247 MI->eraseFromParent();
16250 return continueMBB;
16253 MachineBasicBlock *
16254 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
16255 MachineBasicBlock *BB) const {
16256 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16257 DebugLoc DL = MI->getDebugLoc();
16259 assert(!Subtarget->isTargetMacho());
16261 // The lowering is pretty easy: we're just emitting the call to _alloca. The
16262 // non-trivial part is impdef of ESP.
16264 if (Subtarget->isTargetWin64()) {
16265 if (Subtarget->isTargetCygMing()) {
16266 // ___chkstk(Mingw64):
16267 // Clobbers R10, R11, RAX and EFLAGS.
16269 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16270 .addExternalSymbol("___chkstk")
16271 .addReg(X86::RAX, RegState::Implicit)
16272 .addReg(X86::RSP, RegState::Implicit)
16273 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
16274 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
16275 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16277 // __chkstk(MSVCRT): does not update stack pointer.
16278 // Clobbers R10, R11 and EFLAGS.
16279 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16280 .addExternalSymbol("__chkstk")
16281 .addReg(X86::RAX, RegState::Implicit)
16282 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16283 // RAX has the offset to be subtracted from RSP.
16284 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
16289 const char *StackProbeSymbol =
16290 Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
16292 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
16293 .addExternalSymbol(StackProbeSymbol)
16294 .addReg(X86::EAX, RegState::Implicit)
16295 .addReg(X86::ESP, RegState::Implicit)
16296 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
16297 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
16298 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16301 MI->eraseFromParent(); // The pseudo instruction is gone now.
16305 MachineBasicBlock *
16306 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
16307 MachineBasicBlock *BB) const {
16308 // This is pretty easy. We're taking the value that we received from
16309 // our load from the relocation, sticking it in either RDI (x86-64)
16310 // or EAX and doing an indirect call. The return value will then
16311 // be in the normal return register.
16312 const X86InstrInfo *TII
16313 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
16314 DebugLoc DL = MI->getDebugLoc();
16315 MachineFunction *F = BB->getParent();
16317 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
16318 assert(MI->getOperand(3).isGlobal() && "This should be a global");
16320 // Get a register mask for the lowered call.
16321 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
16322 // proper register mask.
16323 const uint32_t *RegMask =
16324 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16325 if (Subtarget->is64Bit()) {
16326 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16327 TII->get(X86::MOV64rm), X86::RDI)
16329 .addImm(0).addReg(0)
16330 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16331 MI->getOperand(3).getTargetFlags())
16333 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
16334 addDirectMem(MIB, X86::RDI);
16335 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
16336 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
16337 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16338 TII->get(X86::MOV32rm), X86::EAX)
16340 .addImm(0).addReg(0)
16341 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16342 MI->getOperand(3).getTargetFlags())
16344 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16345 addDirectMem(MIB, X86::EAX);
16346 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16348 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16349 TII->get(X86::MOV32rm), X86::EAX)
16350 .addReg(TII->getGlobalBaseReg(F))
16351 .addImm(0).addReg(0)
16352 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16353 MI->getOperand(3).getTargetFlags())
16355 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16356 addDirectMem(MIB, X86::EAX);
16357 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16360 MI->eraseFromParent(); // The pseudo instruction is gone now.
16364 MachineBasicBlock *
16365 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
16366 MachineBasicBlock *MBB) const {
16367 DebugLoc DL = MI->getDebugLoc();
16368 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16370 MachineFunction *MF = MBB->getParent();
16371 MachineRegisterInfo &MRI = MF->getRegInfo();
16373 const BasicBlock *BB = MBB->getBasicBlock();
16374 MachineFunction::iterator I = MBB;
16377 // Memory Reference
16378 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16379 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16382 unsigned MemOpndSlot = 0;
16384 unsigned CurOp = 0;
16386 DstReg = MI->getOperand(CurOp++).getReg();
16387 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
16388 assert(RC->hasType(MVT::i32) && "Invalid destination!");
16389 unsigned mainDstReg = MRI.createVirtualRegister(RC);
16390 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
16392 MemOpndSlot = CurOp;
16394 MVT PVT = getPointerTy();
16395 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16396 "Invalid Pointer Size!");
16398 // For v = setjmp(buf), we generate
16401 // buf[LabelOffset] = restoreMBB
16402 // SjLjSetup restoreMBB
16408 // v = phi(main, restore)
16413 MachineBasicBlock *thisMBB = MBB;
16414 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16415 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16416 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
16417 MF->insert(I, mainMBB);
16418 MF->insert(I, sinkMBB);
16419 MF->push_back(restoreMBB);
16421 MachineInstrBuilder MIB;
16423 // Transfer the remainder of BB and its successor edges to sinkMBB.
16424 sinkMBB->splice(sinkMBB->begin(), MBB,
16425 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16426 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16429 unsigned PtrStoreOpc = 0;
16430 unsigned LabelReg = 0;
16431 const int64_t LabelOffset = 1 * PVT.getStoreSize();
16432 Reloc::Model RM = getTargetMachine().getRelocationModel();
16433 bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
16434 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
16436 // Prepare IP either in reg or imm.
16437 if (!UseImmLabel) {
16438 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
16439 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
16440 LabelReg = MRI.createVirtualRegister(PtrRC);
16441 if (Subtarget->is64Bit()) {
16442 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
16446 .addMBB(restoreMBB)
16449 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
16450 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
16451 .addReg(XII->getGlobalBaseReg(MF))
16454 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
16458 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
16460 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
16461 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16462 if (i == X86::AddrDisp)
16463 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
16465 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
16468 MIB.addReg(LabelReg);
16470 MIB.addMBB(restoreMBB);
16471 MIB.setMemRefs(MMOBegin, MMOEnd);
16473 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
16474 .addMBB(restoreMBB);
16476 const X86RegisterInfo *RegInfo =
16477 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16478 MIB.addRegMask(RegInfo->getNoPreservedMask());
16479 thisMBB->addSuccessor(mainMBB);
16480 thisMBB->addSuccessor(restoreMBB);
16484 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
16485 mainMBB->addSuccessor(sinkMBB);
16488 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16489 TII->get(X86::PHI), DstReg)
16490 .addReg(mainDstReg).addMBB(mainMBB)
16491 .addReg(restoreDstReg).addMBB(restoreMBB);
16494 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
16495 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
16496 restoreMBB->addSuccessor(sinkMBB);
16498 MI->eraseFromParent();
16502 MachineBasicBlock *
16503 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
16504 MachineBasicBlock *MBB) const {
16505 DebugLoc DL = MI->getDebugLoc();
16506 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16508 MachineFunction *MF = MBB->getParent();
16509 MachineRegisterInfo &MRI = MF->getRegInfo();
16511 // Memory Reference
16512 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16513 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16515 MVT PVT = getPointerTy();
16516 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16517 "Invalid Pointer Size!");
16519 const TargetRegisterClass *RC =
16520 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
16521 unsigned Tmp = MRI.createVirtualRegister(RC);
16522 // Since FP is only updated here but NOT referenced, it's treated as GPR.
16523 const X86RegisterInfo *RegInfo =
16524 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16525 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
16526 unsigned SP = RegInfo->getStackRegister();
16528 MachineInstrBuilder MIB;
16530 const int64_t LabelOffset = 1 * PVT.getStoreSize();
16531 const int64_t SPOffset = 2 * PVT.getStoreSize();
16533 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
16534 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
16537 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
16538 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
16539 MIB.addOperand(MI->getOperand(i));
16540 MIB.setMemRefs(MMOBegin, MMOEnd);
16542 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
16543 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16544 if (i == X86::AddrDisp)
16545 MIB.addDisp(MI->getOperand(i), LabelOffset);
16547 MIB.addOperand(MI->getOperand(i));
16549 MIB.setMemRefs(MMOBegin, MMOEnd);
16551 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
16552 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16553 if (i == X86::AddrDisp)
16554 MIB.addDisp(MI->getOperand(i), SPOffset);
16556 MIB.addOperand(MI->getOperand(i));
16558 MIB.setMemRefs(MMOBegin, MMOEnd);
16560 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
16562 MI->eraseFromParent();
16566 // Replace 213-type (isel default) FMA3 instructions with 231-type for
16567 // accumulator loops. Writing back to the accumulator allows the coalescer
16568 // to remove extra copies in the loop.
16569 MachineBasicBlock *
16570 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
16571 MachineBasicBlock *MBB) const {
16572 MachineOperand &AddendOp = MI->getOperand(3);
16574 // Bail out early if the addend isn't a register - we can't switch these.
16575 if (!AddendOp.isReg())
16578 MachineFunction &MF = *MBB->getParent();
16579 MachineRegisterInfo &MRI = MF.getRegInfo();
16581 // Check whether the addend is defined by a PHI:
16582 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
16583 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
16584 if (!AddendDef.isPHI())
16587 // Look for the following pattern:
16589 // %addend = phi [%entry, 0], [%loop, %result]
16591 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
16595 // %addend = phi [%entry, 0], [%loop, %result]
16597 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
16599 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
16600 assert(AddendDef.getOperand(i).isReg());
16601 MachineOperand PHISrcOp = AddendDef.getOperand(i);
16602 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
16603 if (&PHISrcInst == MI) {
16604 // Found a matching instruction.
16605 unsigned NewFMAOpc = 0;
16606 switch (MI->getOpcode()) {
16607 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
16608 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
16609 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
16610 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
16611 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
16612 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
16613 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
16614 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
16615 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
16616 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
16617 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
16618 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
16619 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
16620 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
16621 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
16622 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
16623 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
16624 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
16625 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
16626 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
16627 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
16628 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
16629 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
16630 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
16631 default: llvm_unreachable("Unrecognized FMA variant.");
16634 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
16635 MachineInstrBuilder MIB =
16636 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
16637 .addOperand(MI->getOperand(0))
16638 .addOperand(MI->getOperand(3))
16639 .addOperand(MI->getOperand(2))
16640 .addOperand(MI->getOperand(1));
16641 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
16642 MI->eraseFromParent();
16649 MachineBasicBlock *
16650 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
16651 MachineBasicBlock *BB) const {
16652 switch (MI->getOpcode()) {
16653 default: llvm_unreachable("Unexpected instr type to insert");
16654 case X86::TAILJMPd64:
16655 case X86::TAILJMPr64:
16656 case X86::TAILJMPm64:
16657 llvm_unreachable("TAILJMP64 would not be touched here.");
16658 case X86::TCRETURNdi64:
16659 case X86::TCRETURNri64:
16660 case X86::TCRETURNmi64:
16662 case X86::WIN_ALLOCA:
16663 return EmitLoweredWinAlloca(MI, BB);
16664 case X86::SEG_ALLOCA_32:
16665 return EmitLoweredSegAlloca(MI, BB, false);
16666 case X86::SEG_ALLOCA_64:
16667 return EmitLoweredSegAlloca(MI, BB, true);
16668 case X86::TLSCall_32:
16669 case X86::TLSCall_64:
16670 return EmitLoweredTLSCall(MI, BB);
16671 case X86::CMOV_GR8:
16672 case X86::CMOV_FR32:
16673 case X86::CMOV_FR64:
16674 case X86::CMOV_V4F32:
16675 case X86::CMOV_V2F64:
16676 case X86::CMOV_V2I64:
16677 case X86::CMOV_V8F32:
16678 case X86::CMOV_V4F64:
16679 case X86::CMOV_V4I64:
16680 case X86::CMOV_V16F32:
16681 case X86::CMOV_V8F64:
16682 case X86::CMOV_V8I64:
16683 case X86::CMOV_GR16:
16684 case X86::CMOV_GR32:
16685 case X86::CMOV_RFP32:
16686 case X86::CMOV_RFP64:
16687 case X86::CMOV_RFP80:
16688 return EmitLoweredSelect(MI, BB);
16690 case X86::FP32_TO_INT16_IN_MEM:
16691 case X86::FP32_TO_INT32_IN_MEM:
16692 case X86::FP32_TO_INT64_IN_MEM:
16693 case X86::FP64_TO_INT16_IN_MEM:
16694 case X86::FP64_TO_INT32_IN_MEM:
16695 case X86::FP64_TO_INT64_IN_MEM:
16696 case X86::FP80_TO_INT16_IN_MEM:
16697 case X86::FP80_TO_INT32_IN_MEM:
16698 case X86::FP80_TO_INT64_IN_MEM: {
16699 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16700 DebugLoc DL = MI->getDebugLoc();
16702 // Change the floating point control register to use "round towards zero"
16703 // mode when truncating to an integer value.
16704 MachineFunction *F = BB->getParent();
16705 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
16706 addFrameReference(BuildMI(*BB, MI, DL,
16707 TII->get(X86::FNSTCW16m)), CWFrameIdx);
16709 // Load the old value of the high byte of the control word...
16711 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
16712 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
16715 // Set the high part to be round to zero...
16716 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
16719 // Reload the modified control word now...
16720 addFrameReference(BuildMI(*BB, MI, DL,
16721 TII->get(X86::FLDCW16m)), CWFrameIdx);
16723 // Restore the memory image of control word to original value
16724 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
16727 // Get the X86 opcode to use.
16729 switch (MI->getOpcode()) {
16730 default: llvm_unreachable("illegal opcode!");
16731 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
16732 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
16733 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
16734 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
16735 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
16736 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
16737 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
16738 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
16739 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
16743 MachineOperand &Op = MI->getOperand(0);
16745 AM.BaseType = X86AddressMode::RegBase;
16746 AM.Base.Reg = Op.getReg();
16748 AM.BaseType = X86AddressMode::FrameIndexBase;
16749 AM.Base.FrameIndex = Op.getIndex();
16751 Op = MI->getOperand(1);
16753 AM.Scale = Op.getImm();
16754 Op = MI->getOperand(2);
16756 AM.IndexReg = Op.getImm();
16757 Op = MI->getOperand(3);
16758 if (Op.isGlobal()) {
16759 AM.GV = Op.getGlobal();
16761 AM.Disp = Op.getImm();
16763 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
16764 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
16766 // Reload the original control word now.
16767 addFrameReference(BuildMI(*BB, MI, DL,
16768 TII->get(X86::FLDCW16m)), CWFrameIdx);
16770 MI->eraseFromParent(); // The pseudo instruction is gone now.
16773 // String/text processing lowering.
16774 case X86::PCMPISTRM128REG:
16775 case X86::VPCMPISTRM128REG:
16776 case X86::PCMPISTRM128MEM:
16777 case X86::VPCMPISTRM128MEM:
16778 case X86::PCMPESTRM128REG:
16779 case X86::VPCMPESTRM128REG:
16780 case X86::PCMPESTRM128MEM:
16781 case X86::VPCMPESTRM128MEM:
16782 assert(Subtarget->hasSSE42() &&
16783 "Target must have SSE4.2 or AVX features enabled");
16784 return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
16786 // String/text processing lowering.
16787 case X86::PCMPISTRIREG:
16788 case X86::VPCMPISTRIREG:
16789 case X86::PCMPISTRIMEM:
16790 case X86::VPCMPISTRIMEM:
16791 case X86::PCMPESTRIREG:
16792 case X86::VPCMPESTRIREG:
16793 case X86::PCMPESTRIMEM:
16794 case X86::VPCMPESTRIMEM:
16795 assert(Subtarget->hasSSE42() &&
16796 "Target must have SSE4.2 or AVX features enabled");
16797 return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
16799 // Thread synchronization.
16801 return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
16805 return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
16807 // Atomic Lowering.
16808 case X86::ATOMAND8:
16809 case X86::ATOMAND16:
16810 case X86::ATOMAND32:
16811 case X86::ATOMAND64:
16814 case X86::ATOMOR16:
16815 case X86::ATOMOR32:
16816 case X86::ATOMOR64:
16818 case X86::ATOMXOR16:
16819 case X86::ATOMXOR8:
16820 case X86::ATOMXOR32:
16821 case X86::ATOMXOR64:
16823 case X86::ATOMNAND8:
16824 case X86::ATOMNAND16:
16825 case X86::ATOMNAND32:
16826 case X86::ATOMNAND64:
16828 case X86::ATOMMAX8:
16829 case X86::ATOMMAX16:
16830 case X86::ATOMMAX32:
16831 case X86::ATOMMAX64:
16833 case X86::ATOMMIN8:
16834 case X86::ATOMMIN16:
16835 case X86::ATOMMIN32:
16836 case X86::ATOMMIN64:
16838 case X86::ATOMUMAX8:
16839 case X86::ATOMUMAX16:
16840 case X86::ATOMUMAX32:
16841 case X86::ATOMUMAX64:
16843 case X86::ATOMUMIN8:
16844 case X86::ATOMUMIN16:
16845 case X86::ATOMUMIN32:
16846 case X86::ATOMUMIN64:
16847 return EmitAtomicLoadArith(MI, BB);
16849 // This group does 64-bit operations on a 32-bit host.
16850 case X86::ATOMAND6432:
16851 case X86::ATOMOR6432:
16852 case X86::ATOMXOR6432:
16853 case X86::ATOMNAND6432:
16854 case X86::ATOMADD6432:
16855 case X86::ATOMSUB6432:
16856 case X86::ATOMMAX6432:
16857 case X86::ATOMMIN6432:
16858 case X86::ATOMUMAX6432:
16859 case X86::ATOMUMIN6432:
16860 case X86::ATOMSWAP6432:
16861 return EmitAtomicLoadArith6432(MI, BB);
16863 case X86::VASTART_SAVE_XMM_REGS:
16864 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
16866 case X86::VAARG_64:
16867 return EmitVAARG64WithCustomInserter(MI, BB);
16869 case X86::EH_SjLj_SetJmp32:
16870 case X86::EH_SjLj_SetJmp64:
16871 return emitEHSjLjSetJmp(MI, BB);
16873 case X86::EH_SjLj_LongJmp32:
16874 case X86::EH_SjLj_LongJmp64:
16875 return emitEHSjLjLongJmp(MI, BB);
16877 case TargetOpcode::STACKMAP:
16878 case TargetOpcode::PATCHPOINT:
16879 return emitPatchPoint(MI, BB);
16881 case X86::VFMADDPDr213r:
16882 case X86::VFMADDPSr213r:
16883 case X86::VFMADDSDr213r:
16884 case X86::VFMADDSSr213r:
16885 case X86::VFMSUBPDr213r:
16886 case X86::VFMSUBPSr213r:
16887 case X86::VFMSUBSDr213r:
16888 case X86::VFMSUBSSr213r:
16889 case X86::VFNMADDPDr213r:
16890 case X86::VFNMADDPSr213r:
16891 case X86::VFNMADDSDr213r:
16892 case X86::VFNMADDSSr213r:
16893 case X86::VFNMSUBPDr213r:
16894 case X86::VFNMSUBPSr213r:
16895 case X86::VFNMSUBSDr213r:
16896 case X86::VFNMSUBSSr213r:
16897 case X86::VFMADDPDr213rY:
16898 case X86::VFMADDPSr213rY:
16899 case X86::VFMSUBPDr213rY:
16900 case X86::VFMSUBPSr213rY:
16901 case X86::VFNMADDPDr213rY:
16902 case X86::VFNMADDPSr213rY:
16903 case X86::VFNMSUBPDr213rY:
16904 case X86::VFNMSUBPSr213rY:
16905 return emitFMA3Instr(MI, BB);
16909 //===----------------------------------------------------------------------===//
16910 // X86 Optimization Hooks
16911 //===----------------------------------------------------------------------===//
16913 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
16916 const SelectionDAG &DAG,
16917 unsigned Depth) const {
16918 unsigned BitWidth = KnownZero.getBitWidth();
16919 unsigned Opc = Op.getOpcode();
16920 assert((Opc >= ISD::BUILTIN_OP_END ||
16921 Opc == ISD::INTRINSIC_WO_CHAIN ||
16922 Opc == ISD::INTRINSIC_W_CHAIN ||
16923 Opc == ISD::INTRINSIC_VOID) &&
16924 "Should use MaskedValueIsZero if you don't know whether Op"
16925 " is a target node!");
16927 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
16941 // These nodes' second result is a boolean.
16942 if (Op.getResNo() == 0)
16945 case X86ISD::SETCC:
16946 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
16948 case ISD::INTRINSIC_WO_CHAIN: {
16949 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16950 unsigned NumLoBits = 0;
16953 case Intrinsic::x86_sse_movmsk_ps:
16954 case Intrinsic::x86_avx_movmsk_ps_256:
16955 case Intrinsic::x86_sse2_movmsk_pd:
16956 case Intrinsic::x86_avx_movmsk_pd_256:
16957 case Intrinsic::x86_mmx_pmovmskb:
16958 case Intrinsic::x86_sse2_pmovmskb_128:
16959 case Intrinsic::x86_avx2_pmovmskb: {
16960 // High bits of movmskp{s|d}, pmovmskb are known zero.
16962 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
16963 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
16964 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
16965 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
16966 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
16967 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
16968 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
16969 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
16971 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
16980 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
16982 const SelectionDAG &,
16983 unsigned Depth) const {
16984 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
16985 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
16986 return Op.getValueType().getScalarType().getSizeInBits();
16992 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
16993 /// node is a GlobalAddress + offset.
16994 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
16995 const GlobalValue* &GA,
16996 int64_t &Offset) const {
16997 if (N->getOpcode() == X86ISD::Wrapper) {
16998 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
16999 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
17000 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
17004 return TargetLowering::isGAPlusOffset(N, GA, Offset);
17007 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
17008 /// same as extracting the high 128-bit part of 256-bit vector and then
17009 /// inserting the result into the low part of a new 256-bit vector
17010 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
17011 EVT VT = SVOp->getValueType(0);
17012 unsigned NumElems = VT.getVectorNumElements();
17014 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17015 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
17016 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17017 SVOp->getMaskElt(j) >= 0)
17023 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
17024 /// same as extracting the low 128-bit part of 256-bit vector and then
17025 /// inserting the result into the high part of a new 256-bit vector
17026 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
17027 EVT VT = SVOp->getValueType(0);
17028 unsigned NumElems = VT.getVectorNumElements();
17030 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17031 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
17032 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17033 SVOp->getMaskElt(j) >= 0)
17039 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
17040 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
17041 TargetLowering::DAGCombinerInfo &DCI,
17042 const X86Subtarget* Subtarget) {
17044 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17045 SDValue V1 = SVOp->getOperand(0);
17046 SDValue V2 = SVOp->getOperand(1);
17047 EVT VT = SVOp->getValueType(0);
17048 unsigned NumElems = VT.getVectorNumElements();
17050 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
17051 V2.getOpcode() == ISD::CONCAT_VECTORS) {
17055 // V UNDEF BUILD_VECTOR UNDEF
17057 // CONCAT_VECTOR CONCAT_VECTOR
17060 // RESULT: V + zero extended
17062 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
17063 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
17064 V1.getOperand(1).getOpcode() != ISD::UNDEF)
17067 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
17070 // To match the shuffle mask, the first half of the mask should
17071 // be exactly the first vector, and all the rest a splat with the
17072 // first element of the second one.
17073 for (unsigned i = 0; i != NumElems/2; ++i)
17074 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
17075 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
17078 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
17079 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
17080 if (Ld->hasNUsesOfValue(1, 0)) {
17081 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
17082 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
17084 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
17086 Ld->getPointerInfo(),
17087 Ld->getAlignment(),
17088 false/*isVolatile*/, true/*ReadMem*/,
17089 false/*WriteMem*/);
17091 // Make sure the newly-created LOAD is in the same position as Ld in
17092 // terms of dependency. We create a TokenFactor for Ld and ResNode,
17093 // and update uses of Ld's output chain to use the TokenFactor.
17094 if (Ld->hasAnyUseOfValue(1)) {
17095 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17096 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
17097 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
17098 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
17099 SDValue(ResNode.getNode(), 1));
17102 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
17106 // Emit a zeroed vector and insert the desired subvector on its
17108 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17109 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
17110 return DCI.CombineTo(N, InsV);
17113 //===--------------------------------------------------------------------===//
17114 // Combine some shuffles into subvector extracts and inserts:
17117 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17118 if (isShuffleHigh128VectorInsertLow(SVOp)) {
17119 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
17120 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
17121 return DCI.CombineTo(N, InsV);
17124 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17125 if (isShuffleLow128VectorInsertHigh(SVOp)) {
17126 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
17127 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
17128 return DCI.CombineTo(N, InsV);
17134 /// PerformShuffleCombine - Performs several different shuffle combines.
17135 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
17136 TargetLowering::DAGCombinerInfo &DCI,
17137 const X86Subtarget *Subtarget) {
17139 EVT VT = N->getValueType(0);
17141 // Don't create instructions with illegal types after legalize types has run.
17142 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17143 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
17146 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
17147 if (Subtarget->hasFp256() && VT.is256BitVector() &&
17148 N->getOpcode() == ISD::VECTOR_SHUFFLE)
17149 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
17151 // Only handle 128 wide vector from here on.
17152 if (!VT.is128BitVector())
17155 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
17156 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
17157 // consecutive, non-overlapping, and in the right order.
17158 SmallVector<SDValue, 16> Elts;
17159 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
17160 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
17162 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
17165 /// PerformTruncateCombine - Converts truncate operation to
17166 /// a sequence of vector shuffle operations.
17167 /// It is possible when we truncate 256-bit vector to 128-bit vector
17168 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
17169 TargetLowering::DAGCombinerInfo &DCI,
17170 const X86Subtarget *Subtarget) {
17174 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
17175 /// specific shuffle of a load can be folded into a single element load.
17176 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
17177 /// shuffles have been customed lowered so we need to handle those here.
17178 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
17179 TargetLowering::DAGCombinerInfo &DCI) {
17180 if (DCI.isBeforeLegalizeOps())
17183 SDValue InVec = N->getOperand(0);
17184 SDValue EltNo = N->getOperand(1);
17186 if (!isa<ConstantSDNode>(EltNo))
17189 EVT VT = InVec.getValueType();
17191 bool HasShuffleIntoBitcast = false;
17192 if (InVec.getOpcode() == ISD::BITCAST) {
17193 // Don't duplicate a load with other uses.
17194 if (!InVec.hasOneUse())
17196 EVT BCVT = InVec.getOperand(0).getValueType();
17197 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
17199 InVec = InVec.getOperand(0);
17200 HasShuffleIntoBitcast = true;
17203 if (!isTargetShuffle(InVec.getOpcode()))
17206 // Don't duplicate a load with other uses.
17207 if (!InVec.hasOneUse())
17210 SmallVector<int, 16> ShuffleMask;
17212 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
17216 // Select the input vector, guarding against out of range extract vector.
17217 unsigned NumElems = VT.getVectorNumElements();
17218 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
17219 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
17220 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
17221 : InVec.getOperand(1);
17223 // If inputs to shuffle are the same for both ops, then allow 2 uses
17224 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
17226 if (LdNode.getOpcode() == ISD::BITCAST) {
17227 // Don't duplicate a load with other uses.
17228 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
17231 AllowedUses = 1; // only allow 1 load use if we have a bitcast
17232 LdNode = LdNode.getOperand(0);
17235 if (!ISD::isNormalLoad(LdNode.getNode()))
17238 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
17240 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
17243 if (HasShuffleIntoBitcast) {
17244 // If there's a bitcast before the shuffle, check if the load type and
17245 // alignment is valid.
17246 unsigned Align = LN0->getAlignment();
17247 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17248 unsigned NewAlign = TLI.getDataLayout()->
17249 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
17251 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
17255 // All checks match so transform back to vector_shuffle so that DAG combiner
17256 // can finish the job
17259 // Create shuffle node taking into account the case that its a unary shuffle
17260 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
17261 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
17262 InVec.getOperand(0), Shuffle,
17264 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
17265 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
17269 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
17270 /// generation and convert it from being a bunch of shuffles and extracts
17271 /// to a simple store and scalar loads to extract the elements.
17272 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
17273 TargetLowering::DAGCombinerInfo &DCI) {
17274 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
17275 if (NewOp.getNode())
17278 SDValue InputVector = N->getOperand(0);
17280 // Detect whether we are trying to convert from mmx to i32 and the bitcast
17281 // from mmx to v2i32 has a single usage.
17282 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
17283 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
17284 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
17285 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
17286 N->getValueType(0),
17287 InputVector.getNode()->getOperand(0));
17289 // Only operate on vectors of 4 elements, where the alternative shuffling
17290 // gets to be more expensive.
17291 if (InputVector.getValueType() != MVT::v4i32)
17294 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
17295 // single use which is a sign-extend or zero-extend, and all elements are
17297 SmallVector<SDNode *, 4> Uses;
17298 unsigned ExtractedElements = 0;
17299 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
17300 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
17301 if (UI.getUse().getResNo() != InputVector.getResNo())
17304 SDNode *Extract = *UI;
17305 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
17308 if (Extract->getValueType(0) != MVT::i32)
17310 if (!Extract->hasOneUse())
17312 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
17313 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
17315 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
17318 // Record which element was extracted.
17319 ExtractedElements |=
17320 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
17322 Uses.push_back(Extract);
17325 // If not all the elements were used, this may not be worthwhile.
17326 if (ExtractedElements != 15)
17329 // Ok, we've now decided to do the transformation.
17330 SDLoc dl(InputVector);
17332 // Store the value to a temporary stack slot.
17333 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
17334 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
17335 MachinePointerInfo(), false, false, 0);
17337 // Replace each use (extract) with a load of the appropriate element.
17338 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
17339 UE = Uses.end(); UI != UE; ++UI) {
17340 SDNode *Extract = *UI;
17342 // cOMpute the element's address.
17343 SDValue Idx = Extract->getOperand(1);
17345 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
17346 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
17347 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17348 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
17350 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
17351 StackPtr, OffsetVal);
17353 // Load the scalar.
17354 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
17355 ScalarAddr, MachinePointerInfo(),
17356 false, false, false, 0);
17358 // Replace the exact with the load.
17359 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
17362 // The replacement was made in place; don't return anything.
17366 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
17367 static std::pair<unsigned, bool>
17368 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
17369 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
17370 if (!VT.isVector())
17371 return std::make_pair(0, false);
17373 bool NeedSplit = false;
17374 switch (VT.getSimpleVT().SimpleTy) {
17375 default: return std::make_pair(0, false);
17379 if (!Subtarget->hasAVX2())
17381 if (!Subtarget->hasAVX())
17382 return std::make_pair(0, false);
17387 if (!Subtarget->hasSSE2())
17388 return std::make_pair(0, false);
17391 // SSE2 has only a small subset of the operations.
17392 bool hasUnsigned = Subtarget->hasSSE41() ||
17393 (Subtarget->hasSSE2() && VT == MVT::v16i8);
17394 bool hasSigned = Subtarget->hasSSE41() ||
17395 (Subtarget->hasSSE2() && VT == MVT::v8i16);
17397 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17400 // Check for x CC y ? x : y.
17401 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17402 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17407 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17410 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17413 Opc = hasSigned ? X86ISD::SMIN : 0; break;
17416 Opc = hasSigned ? X86ISD::SMAX : 0; break;
17418 // Check for x CC y ? y : x -- a min/max with reversed arms.
17419 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17420 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17425 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17428 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17431 Opc = hasSigned ? X86ISD::SMAX : 0; break;
17434 Opc = hasSigned ? X86ISD::SMIN : 0; break;
17438 return std::make_pair(Opc, NeedSplit);
17441 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
17443 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
17444 TargetLowering::DAGCombinerInfo &DCI,
17445 const X86Subtarget *Subtarget) {
17447 SDValue Cond = N->getOperand(0);
17448 // Get the LHS/RHS of the select.
17449 SDValue LHS = N->getOperand(1);
17450 SDValue RHS = N->getOperand(2);
17451 EVT VT = LHS.getValueType();
17452 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17454 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
17455 // instructions match the semantics of the common C idiom x<y?x:y but not
17456 // x<=y?x:y, because of how they handle negative zero (which can be
17457 // ignored in unsafe-math mode).
17458 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
17459 VT != MVT::f80 && TLI.isTypeLegal(VT) &&
17460 (Subtarget->hasSSE2() ||
17461 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
17462 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17464 unsigned Opcode = 0;
17465 // Check for x CC y ? x : y.
17466 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17467 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17471 // Converting this to a min would handle NaNs incorrectly, and swapping
17472 // the operands would cause it to handle comparisons between positive
17473 // and negative zero incorrectly.
17474 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17475 if (!DAG.getTarget().Options.UnsafeFPMath &&
17476 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17478 std::swap(LHS, RHS);
17480 Opcode = X86ISD::FMIN;
17483 // Converting this to a min would handle comparisons between positive
17484 // and negative zero incorrectly.
17485 if (!DAG.getTarget().Options.UnsafeFPMath &&
17486 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17488 Opcode = X86ISD::FMIN;
17491 // Converting this to a min would handle both negative zeros and NaNs
17492 // incorrectly, but we can swap the operands to fix both.
17493 std::swap(LHS, RHS);
17497 Opcode = X86ISD::FMIN;
17501 // Converting this to a max would handle comparisons between positive
17502 // and negative zero incorrectly.
17503 if (!DAG.getTarget().Options.UnsafeFPMath &&
17504 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17506 Opcode = X86ISD::FMAX;
17509 // Converting this to a max would handle NaNs incorrectly, and swapping
17510 // the operands would cause it to handle comparisons between positive
17511 // and negative zero incorrectly.
17512 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17513 if (!DAG.getTarget().Options.UnsafeFPMath &&
17514 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17516 std::swap(LHS, RHS);
17518 Opcode = X86ISD::FMAX;
17521 // Converting this to a max would handle both negative zeros and NaNs
17522 // incorrectly, but we can swap the operands to fix both.
17523 std::swap(LHS, RHS);
17527 Opcode = X86ISD::FMAX;
17530 // Check for x CC y ? y : x -- a min/max with reversed arms.
17531 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17532 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17536 // Converting this to a min would handle comparisons between positive
17537 // and negative zero incorrectly, and swapping the operands would
17538 // cause it to handle NaNs incorrectly.
17539 if (!DAG.getTarget().Options.UnsafeFPMath &&
17540 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
17541 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17543 std::swap(LHS, RHS);
17545 Opcode = X86ISD::FMIN;
17548 // Converting this to a min would handle NaNs incorrectly.
17549 if (!DAG.getTarget().Options.UnsafeFPMath &&
17550 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
17552 Opcode = X86ISD::FMIN;
17555 // Converting this to a min would handle both negative zeros and NaNs
17556 // incorrectly, but we can swap the operands to fix both.
17557 std::swap(LHS, RHS);
17561 Opcode = X86ISD::FMIN;
17565 // Converting this to a max would handle NaNs incorrectly.
17566 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17568 Opcode = X86ISD::FMAX;
17571 // Converting this to a max would handle comparisons between positive
17572 // and negative zero incorrectly, and swapping the operands would
17573 // cause it to handle NaNs incorrectly.
17574 if (!DAG.getTarget().Options.UnsafeFPMath &&
17575 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
17576 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17578 std::swap(LHS, RHS);
17580 Opcode = X86ISD::FMAX;
17583 // Converting this to a max would handle both negative zeros and NaNs
17584 // incorrectly, but we can swap the operands to fix both.
17585 std::swap(LHS, RHS);
17589 Opcode = X86ISD::FMAX;
17595 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
17598 EVT CondVT = Cond.getValueType();
17599 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
17600 CondVT.getVectorElementType() == MVT::i1) {
17601 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
17602 // lowering on AVX-512. In this case we convert it to
17603 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
17604 // The same situation for all 128 and 256-bit vectors of i8 and i16
17605 EVT OpVT = LHS.getValueType();
17606 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
17607 (OpVT.getVectorElementType() == MVT::i8 ||
17608 OpVT.getVectorElementType() == MVT::i16)) {
17609 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
17610 DCI.AddToWorklist(Cond.getNode());
17611 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
17614 // If this is a select between two integer constants, try to do some
17616 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
17617 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
17618 // Don't do this for crazy integer types.
17619 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
17620 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
17621 // so that TrueC (the true value) is larger than FalseC.
17622 bool NeedsCondInvert = false;
17624 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
17625 // Efficiently invertible.
17626 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
17627 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
17628 isa<ConstantSDNode>(Cond.getOperand(1))))) {
17629 NeedsCondInvert = true;
17630 std::swap(TrueC, FalseC);
17633 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
17634 if (FalseC->getAPIntValue() == 0 &&
17635 TrueC->getAPIntValue().isPowerOf2()) {
17636 if (NeedsCondInvert) // Invert the condition if needed.
17637 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17638 DAG.getConstant(1, Cond.getValueType()));
17640 // Zero extend the condition if needed.
17641 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
17643 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17644 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
17645 DAG.getConstant(ShAmt, MVT::i8));
17648 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
17649 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17650 if (NeedsCondInvert) // Invert the condition if needed.
17651 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17652 DAG.getConstant(1, Cond.getValueType()));
17654 // Zero extend the condition if needed.
17655 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17656 FalseC->getValueType(0), Cond);
17657 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17658 SDValue(FalseC, 0));
17661 // Optimize cases that will turn into an LEA instruction. This requires
17662 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17663 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17664 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17665 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17667 bool isFastMultiplier = false;
17669 switch ((unsigned char)Diff) {
17671 case 1: // result = add base, cond
17672 case 2: // result = lea base( , cond*2)
17673 case 3: // result = lea base(cond, cond*2)
17674 case 4: // result = lea base( , cond*4)
17675 case 5: // result = lea base(cond, cond*4)
17676 case 8: // result = lea base( , cond*8)
17677 case 9: // result = lea base(cond, cond*8)
17678 isFastMultiplier = true;
17683 if (isFastMultiplier) {
17684 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
17685 if (NeedsCondInvert) // Invert the condition if needed.
17686 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17687 DAG.getConstant(1, Cond.getValueType()));
17689 // Zero extend the condition if needed.
17690 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
17692 // Scale the condition by the difference.
17694 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
17695 DAG.getConstant(Diff, Cond.getValueType()));
17697 // Add the base if non-zero.
17698 if (FalseC->getAPIntValue() != 0)
17699 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17700 SDValue(FalseC, 0));
17707 // Canonicalize max and min:
17708 // (x > y) ? x : y -> (x >= y) ? x : y
17709 // (x < y) ? x : y -> (x <= y) ? x : y
17710 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
17711 // the need for an extra compare
17712 // against zero. e.g.
17713 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
17715 // testl %edi, %edi
17717 // cmovgl %edi, %eax
17721 // cmovsl %eax, %edi
17722 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
17723 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17724 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17725 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17730 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
17731 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
17732 Cond.getOperand(0), Cond.getOperand(1), NewCC);
17733 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
17738 // Early exit check
17739 if (!TLI.isTypeLegal(VT))
17742 // Match VSELECTs into subs with unsigned saturation.
17743 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17744 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
17745 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
17746 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
17747 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17749 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
17750 // left side invert the predicate to simplify logic below.
17752 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
17754 CC = ISD::getSetCCInverse(CC, true);
17755 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
17759 if (Other.getNode() && Other->getNumOperands() == 2 &&
17760 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
17761 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
17762 SDValue CondRHS = Cond->getOperand(1);
17764 // Look for a general sub with unsigned saturation first.
17765 // x >= y ? x-y : 0 --> subus x, y
17766 // x > y ? x-y : 0 --> subus x, y
17767 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
17768 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
17769 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17771 // If the RHS is a constant we have to reverse the const canonicalization.
17772 // x > C-1 ? x+-C : 0 --> subus x, C
17773 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
17774 isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
17775 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17776 if (CondRHS.getConstantOperandVal(0) == -A-1)
17777 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
17778 DAG.getConstant(-A, VT));
17781 // Another special case: If C was a sign bit, the sub has been
17782 // canonicalized into a xor.
17783 // FIXME: Would it be better to use ComputeMaskedBits to determine whether
17784 // it's safe to decanonicalize the xor?
17785 // x s< 0 ? x^C : 0 --> subus x, C
17786 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
17787 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
17788 isSplatVector(OpRHS.getNode())) {
17789 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17791 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17796 // Try to match a min/max vector operation.
17797 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
17798 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
17799 unsigned Opc = ret.first;
17800 bool NeedSplit = ret.second;
17802 if (Opc && NeedSplit) {
17803 unsigned NumElems = VT.getVectorNumElements();
17804 // Extract the LHS vectors
17805 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
17806 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
17808 // Extract the RHS vectors
17809 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
17810 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
17812 // Create min/max for each subvector
17813 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
17814 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
17816 // Merge the result
17817 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
17819 return DAG.getNode(Opc, DL, VT, LHS, RHS);
17822 // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
17823 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17824 // Check if SETCC has already been promoted
17825 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
17826 // Check that condition value type matches vselect operand type
17829 assert(Cond.getValueType().isVector() &&
17830 "vector select expects a vector selector!");
17832 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
17833 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
17835 if (!TValIsAllOnes && !FValIsAllZeros) {
17836 // Try invert the condition if true value is not all 1s and false value
17838 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
17839 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
17841 if (TValIsAllZeros || FValIsAllOnes) {
17842 SDValue CC = Cond.getOperand(2);
17843 ISD::CondCode NewCC =
17844 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
17845 Cond.getOperand(0).getValueType().isInteger());
17846 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
17847 std::swap(LHS, RHS);
17848 TValIsAllOnes = FValIsAllOnes;
17849 FValIsAllZeros = TValIsAllZeros;
17853 if (TValIsAllOnes || FValIsAllZeros) {
17856 if (TValIsAllOnes && FValIsAllZeros)
17858 else if (TValIsAllOnes)
17859 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
17860 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
17861 else if (FValIsAllZeros)
17862 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
17863 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
17865 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
17869 // Try to fold this VSELECT into a MOVSS/MOVSD
17870 if (N->getOpcode() == ISD::VSELECT &&
17871 Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
17872 if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
17873 (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
17874 bool CanFold = false;
17875 unsigned NumElems = Cond.getNumOperands();
17879 if (isZero(Cond.getOperand(0))) {
17882 // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
17883 // fold (vselect <0,-1> -> (movsd A, B)
17884 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17885 CanFold = isAllOnes(Cond.getOperand(i));
17886 } else if (isAllOnes(Cond.getOperand(0))) {
17890 // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
17891 // fold (vselect <-1,0> -> (movsd B, A)
17892 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17893 CanFold = isZero(Cond.getOperand(i));
17897 if (VT == MVT::v4i32 || VT == MVT::v4f32)
17898 return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
17899 return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
17902 if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
17903 // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
17904 // (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
17905 // (v2i64 (bitcast B)))))
17907 // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
17908 // (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
17909 // (v2f64 (bitcast B)))))
17911 // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
17912 // (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
17913 // (v2i64 (bitcast A)))))
17915 // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
17916 // (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
17917 // (v2f64 (bitcast A)))))
17919 CanFold = (isZero(Cond.getOperand(0)) &&
17920 isZero(Cond.getOperand(1)) &&
17921 isAllOnes(Cond.getOperand(2)) &&
17922 isAllOnes(Cond.getOperand(3)));
17924 if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
17925 isAllOnes(Cond.getOperand(1)) &&
17926 isZero(Cond.getOperand(2)) &&
17927 isZero(Cond.getOperand(3))) {
17929 std::swap(LHS, RHS);
17933 EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
17934 SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
17935 SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
17936 SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
17938 return DAG.getNode(ISD::BITCAST, DL, VT, Select);
17944 // If we know that this node is legal then we know that it is going to be
17945 // matched by one of the SSE/AVX BLEND instructions. These instructions only
17946 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
17947 // to simplify previous instructions.
17948 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
17949 !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
17950 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
17952 // Don't optimize vector selects that map to mask-registers.
17956 // Check all uses of that condition operand to check whether it will be
17957 // consumed by non-BLEND instructions, which may depend on all bits are set
17959 for (SDNode::use_iterator I = Cond->use_begin(),
17960 E = Cond->use_end(); I != E; ++I)
17961 if (I->getOpcode() != ISD::VSELECT)
17962 // TODO: Add other opcodes eventually lowered into BLEND.
17965 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
17966 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
17968 APInt KnownZero, KnownOne;
17969 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
17970 DCI.isBeforeLegalizeOps());
17971 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
17972 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
17973 DCI.CommitTargetLoweringOpt(TLO);
17979 // Check whether a boolean test is testing a boolean value generated by
17980 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
17983 // Simplify the following patterns:
17984 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
17985 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
17986 // to (Op EFLAGS Cond)
17988 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
17989 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
17990 // to (Op EFLAGS !Cond)
17992 // where Op could be BRCOND or CMOV.
17994 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
17995 // Quit if not CMP and SUB with its value result used.
17996 if (Cmp.getOpcode() != X86ISD::CMP &&
17997 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
18000 // Quit if not used as a boolean value.
18001 if (CC != X86::COND_E && CC != X86::COND_NE)
18004 // Check CMP operands. One of them should be 0 or 1 and the other should be
18005 // an SetCC or extended from it.
18006 SDValue Op1 = Cmp.getOperand(0);
18007 SDValue Op2 = Cmp.getOperand(1);
18010 const ConstantSDNode* C = nullptr;
18011 bool needOppositeCond = (CC == X86::COND_E);
18012 bool checkAgainstTrue = false; // Is it a comparison against 1?
18014 if ((C = dyn_cast<ConstantSDNode>(Op1)))
18016 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
18018 else // Quit if all operands are not constants.
18021 if (C->getZExtValue() == 1) {
18022 needOppositeCond = !needOppositeCond;
18023 checkAgainstTrue = true;
18024 } else if (C->getZExtValue() != 0)
18025 // Quit if the constant is neither 0 or 1.
18028 bool truncatedToBoolWithAnd = false;
18029 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
18030 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
18031 SetCC.getOpcode() == ISD::TRUNCATE ||
18032 SetCC.getOpcode() == ISD::AND) {
18033 if (SetCC.getOpcode() == ISD::AND) {
18035 ConstantSDNode *CS;
18036 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
18037 CS->getZExtValue() == 1)
18039 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
18040 CS->getZExtValue() == 1)
18044 SetCC = SetCC.getOperand(OpIdx);
18045 truncatedToBoolWithAnd = true;
18047 SetCC = SetCC.getOperand(0);
18050 switch (SetCC.getOpcode()) {
18051 case X86ISD::SETCC_CARRY:
18052 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
18053 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
18054 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
18055 // truncated to i1 using 'and'.
18056 if (checkAgainstTrue && !truncatedToBoolWithAnd)
18058 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
18059 "Invalid use of SETCC_CARRY!");
18061 case X86ISD::SETCC:
18062 // Set the condition code or opposite one if necessary.
18063 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
18064 if (needOppositeCond)
18065 CC = X86::GetOppositeBranchCondition(CC);
18066 return SetCC.getOperand(1);
18067 case X86ISD::CMOV: {
18068 // Check whether false/true value has canonical one, i.e. 0 or 1.
18069 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
18070 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
18071 // Quit if true value is not a constant.
18074 // Quit if false value is not a constant.
18076 SDValue Op = SetCC.getOperand(0);
18077 // Skip 'zext' or 'trunc' node.
18078 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
18079 Op.getOpcode() == ISD::TRUNCATE)
18080 Op = Op.getOperand(0);
18081 // A special case for rdrand/rdseed, where 0 is set if false cond is
18083 if ((Op.getOpcode() != X86ISD::RDRAND &&
18084 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
18087 // Quit if false value is not the constant 0 or 1.
18088 bool FValIsFalse = true;
18089 if (FVal && FVal->getZExtValue() != 0) {
18090 if (FVal->getZExtValue() != 1)
18092 // If FVal is 1, opposite cond is needed.
18093 needOppositeCond = !needOppositeCond;
18094 FValIsFalse = false;
18096 // Quit if TVal is not the constant opposite of FVal.
18097 if (FValIsFalse && TVal->getZExtValue() != 1)
18099 if (!FValIsFalse && TVal->getZExtValue() != 0)
18101 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
18102 if (needOppositeCond)
18103 CC = X86::GetOppositeBranchCondition(CC);
18104 return SetCC.getOperand(3);
18111 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
18112 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
18113 TargetLowering::DAGCombinerInfo &DCI,
18114 const X86Subtarget *Subtarget) {
18117 // If the flag operand isn't dead, don't touch this CMOV.
18118 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
18121 SDValue FalseOp = N->getOperand(0);
18122 SDValue TrueOp = N->getOperand(1);
18123 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
18124 SDValue Cond = N->getOperand(3);
18126 if (CC == X86::COND_E || CC == X86::COND_NE) {
18127 switch (Cond.getOpcode()) {
18131 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
18132 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
18133 return (CC == X86::COND_E) ? FalseOp : TrueOp;
18139 Flags = checkBoolTestSetCCCombine(Cond, CC);
18140 if (Flags.getNode() &&
18141 // Extra check as FCMOV only supports a subset of X86 cond.
18142 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
18143 SDValue Ops[] = { FalseOp, TrueOp,
18144 DAG.getConstant(CC, MVT::i8), Flags };
18145 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
18148 // If this is a select between two integer constants, try to do some
18149 // optimizations. Note that the operands are ordered the opposite of SELECT
18151 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
18152 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
18153 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
18154 // larger than FalseC (the false value).
18155 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
18156 CC = X86::GetOppositeBranchCondition(CC);
18157 std::swap(TrueC, FalseC);
18158 std::swap(TrueOp, FalseOp);
18161 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
18162 // This is efficient for any integer data type (including i8/i16) and
18164 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
18165 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18166 DAG.getConstant(CC, MVT::i8), Cond);
18168 // Zero extend the condition if needed.
18169 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
18171 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18172 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
18173 DAG.getConstant(ShAmt, MVT::i8));
18174 if (N->getNumValues() == 2) // Dead flag value?
18175 return DCI.CombineTo(N, Cond, SDValue());
18179 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
18180 // for any integer data type, including i8/i16.
18181 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18182 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18183 DAG.getConstant(CC, MVT::i8), Cond);
18185 // Zero extend the condition if needed.
18186 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18187 FalseC->getValueType(0), Cond);
18188 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18189 SDValue(FalseC, 0));
18191 if (N->getNumValues() == 2) // Dead flag value?
18192 return DCI.CombineTo(N, Cond, SDValue());
18196 // Optimize cases that will turn into an LEA instruction. This requires
18197 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18198 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18199 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18200 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18202 bool isFastMultiplier = false;
18204 switch ((unsigned char)Diff) {
18206 case 1: // result = add base, cond
18207 case 2: // result = lea base( , cond*2)
18208 case 3: // result = lea base(cond, cond*2)
18209 case 4: // result = lea base( , cond*4)
18210 case 5: // result = lea base(cond, cond*4)
18211 case 8: // result = lea base( , cond*8)
18212 case 9: // result = lea base(cond, cond*8)
18213 isFastMultiplier = true;
18218 if (isFastMultiplier) {
18219 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18220 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18221 DAG.getConstant(CC, MVT::i8), Cond);
18222 // Zero extend the condition if needed.
18223 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18225 // Scale the condition by the difference.
18227 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18228 DAG.getConstant(Diff, Cond.getValueType()));
18230 // Add the base if non-zero.
18231 if (FalseC->getAPIntValue() != 0)
18232 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18233 SDValue(FalseC, 0));
18234 if (N->getNumValues() == 2) // Dead flag value?
18235 return DCI.CombineTo(N, Cond, SDValue());
18242 // Handle these cases:
18243 // (select (x != c), e, c) -> select (x != c), e, x),
18244 // (select (x == c), c, e) -> select (x == c), x, e)
18245 // where the c is an integer constant, and the "select" is the combination
18246 // of CMOV and CMP.
18248 // The rationale for this change is that the conditional-move from a constant
18249 // needs two instructions, however, conditional-move from a register needs
18250 // only one instruction.
18252 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
18253 // some instruction-combining opportunities. This opt needs to be
18254 // postponed as late as possible.
18256 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
18257 // the DCI.xxxx conditions are provided to postpone the optimization as
18258 // late as possible.
18260 ConstantSDNode *CmpAgainst = nullptr;
18261 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
18262 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
18263 !isa<ConstantSDNode>(Cond.getOperand(0))) {
18265 if (CC == X86::COND_NE &&
18266 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
18267 CC = X86::GetOppositeBranchCondition(CC);
18268 std::swap(TrueOp, FalseOp);
18271 if (CC == X86::COND_E &&
18272 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
18273 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
18274 DAG.getConstant(CC, MVT::i8), Cond };
18275 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
18283 /// PerformMulCombine - Optimize a single multiply with constant into two
18284 /// in order to implement it with two cheaper instructions, e.g.
18285 /// LEA + SHL, LEA + LEA.
18286 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
18287 TargetLowering::DAGCombinerInfo &DCI) {
18288 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
18291 EVT VT = N->getValueType(0);
18292 if (VT != MVT::i64)
18295 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
18298 uint64_t MulAmt = C->getZExtValue();
18299 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
18302 uint64_t MulAmt1 = 0;
18303 uint64_t MulAmt2 = 0;
18304 if ((MulAmt % 9) == 0) {
18306 MulAmt2 = MulAmt / 9;
18307 } else if ((MulAmt % 5) == 0) {
18309 MulAmt2 = MulAmt / 5;
18310 } else if ((MulAmt % 3) == 0) {
18312 MulAmt2 = MulAmt / 3;
18315 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
18318 if (isPowerOf2_64(MulAmt2) &&
18319 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
18320 // If second multiplifer is pow2, issue it first. We want the multiply by
18321 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
18323 std::swap(MulAmt1, MulAmt2);
18326 if (isPowerOf2_64(MulAmt1))
18327 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
18328 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
18330 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
18331 DAG.getConstant(MulAmt1, VT));
18333 if (isPowerOf2_64(MulAmt2))
18334 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
18335 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
18337 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
18338 DAG.getConstant(MulAmt2, VT));
18340 // Do not add new nodes to DAG combiner worklist.
18341 DCI.CombineTo(N, NewMul, false);
18346 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
18347 SDValue N0 = N->getOperand(0);
18348 SDValue N1 = N->getOperand(1);
18349 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
18350 EVT VT = N0.getValueType();
18352 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
18353 // since the result of setcc_c is all zero's or all ones.
18354 if (VT.isInteger() && !VT.isVector() &&
18355 N1C && N0.getOpcode() == ISD::AND &&
18356 N0.getOperand(1).getOpcode() == ISD::Constant) {
18357 SDValue N00 = N0.getOperand(0);
18358 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
18359 ((N00.getOpcode() == ISD::ANY_EXTEND ||
18360 N00.getOpcode() == ISD::ZERO_EXTEND) &&
18361 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
18362 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
18363 APInt ShAmt = N1C->getAPIntValue();
18364 Mask = Mask.shl(ShAmt);
18366 return DAG.getNode(ISD::AND, SDLoc(N), VT,
18367 N00, DAG.getConstant(Mask, VT));
18371 // Hardware support for vector shifts is sparse which makes us scalarize the
18372 // vector operations in many cases. Also, on sandybridge ADD is faster than
18374 // (shl V, 1) -> add V,V
18375 if (isSplatVector(N1.getNode())) {
18376 assert(N0.getValueType().isVector() && "Invalid vector shift type");
18377 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
18378 // We shift all of the values by one. In many cases we do not have
18379 // hardware support for this operation. This is better expressed as an ADD
18381 if (N1C && (1 == N1C->getZExtValue())) {
18382 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
18389 /// \brief Returns a vector of 0s if the node in input is a vector logical
18390 /// shift by a constant amount which is known to be bigger than or equal
18391 /// to the vector element size in bits.
18392 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
18393 const X86Subtarget *Subtarget) {
18394 EVT VT = N->getValueType(0);
18396 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
18397 (!Subtarget->hasInt256() ||
18398 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
18401 SDValue Amt = N->getOperand(1);
18403 if (isSplatVector(Amt.getNode())) {
18404 SDValue SclrAmt = Amt->getOperand(0);
18405 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
18406 APInt ShiftAmt = C->getAPIntValue();
18407 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
18409 // SSE2/AVX2 logical shifts always return a vector of 0s
18410 // if the shift amount is bigger than or equal to
18411 // the element size. The constant shift amount will be
18412 // encoded as a 8-bit immediate.
18413 if (ShiftAmt.trunc(8).uge(MaxAmount))
18414 return getZeroVector(VT, Subtarget, DAG, DL);
18421 /// PerformShiftCombine - Combine shifts.
18422 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
18423 TargetLowering::DAGCombinerInfo &DCI,
18424 const X86Subtarget *Subtarget) {
18425 if (N->getOpcode() == ISD::SHL) {
18426 SDValue V = PerformSHLCombine(N, DAG);
18427 if (V.getNode()) return V;
18430 if (N->getOpcode() != ISD::SRA) {
18431 // Try to fold this logical shift into a zero vector.
18432 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
18433 if (V.getNode()) return V;
18439 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
18440 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
18441 // and friends. Likewise for OR -> CMPNEQSS.
18442 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
18443 TargetLowering::DAGCombinerInfo &DCI,
18444 const X86Subtarget *Subtarget) {
18447 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
18448 // we're requiring SSE2 for both.
18449 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
18450 SDValue N0 = N->getOperand(0);
18451 SDValue N1 = N->getOperand(1);
18452 SDValue CMP0 = N0->getOperand(1);
18453 SDValue CMP1 = N1->getOperand(1);
18456 // The SETCCs should both refer to the same CMP.
18457 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
18460 SDValue CMP00 = CMP0->getOperand(0);
18461 SDValue CMP01 = CMP0->getOperand(1);
18462 EVT VT = CMP00.getValueType();
18464 if (VT == MVT::f32 || VT == MVT::f64) {
18465 bool ExpectingFlags = false;
18466 // Check for any users that want flags:
18467 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
18468 !ExpectingFlags && UI != UE; ++UI)
18469 switch (UI->getOpcode()) {
18474 ExpectingFlags = true;
18476 case ISD::CopyToReg:
18477 case ISD::SIGN_EXTEND:
18478 case ISD::ZERO_EXTEND:
18479 case ISD::ANY_EXTEND:
18483 if (!ExpectingFlags) {
18484 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
18485 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
18487 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
18488 X86::CondCode tmp = cc0;
18493 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
18494 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
18495 // FIXME: need symbolic constants for these magic numbers.
18496 // See X86ATTInstPrinter.cpp:printSSECC().
18497 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
18498 if (Subtarget->hasAVX512()) {
18499 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
18500 CMP01, DAG.getConstant(x86cc, MVT::i8));
18501 if (N->getValueType(0) != MVT::i1)
18502 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
18506 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
18507 CMP00.getValueType(), CMP00, CMP01,
18508 DAG.getConstant(x86cc, MVT::i8));
18510 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
18511 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
18513 if (is64BitFP && !Subtarget->is64Bit()) {
18514 // On a 32-bit target, we cannot bitcast the 64-bit float to a
18515 // 64-bit integer, since that's not a legal type. Since
18516 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
18517 // bits, but can do this little dance to extract the lowest 32 bits
18518 // and work with those going forward.
18519 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
18521 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
18523 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
18524 Vector32, DAG.getIntPtrConstant(0));
18528 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
18529 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
18530 DAG.getConstant(1, IntVT));
18531 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
18532 return OneBitOfTruth;
18540 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
18541 /// so it can be folded inside ANDNP.
18542 static bool CanFoldXORWithAllOnes(const SDNode *N) {
18543 EVT VT = N->getValueType(0);
18545 // Match direct AllOnes for 128 and 256-bit vectors
18546 if (ISD::isBuildVectorAllOnes(N))
18549 // Look through a bit convert.
18550 if (N->getOpcode() == ISD::BITCAST)
18551 N = N->getOperand(0).getNode();
18553 // Sometimes the operand may come from a insert_subvector building a 256-bit
18555 if (VT.is256BitVector() &&
18556 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
18557 SDValue V1 = N->getOperand(0);
18558 SDValue V2 = N->getOperand(1);
18560 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
18561 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
18562 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
18563 ISD::isBuildVectorAllOnes(V2.getNode()))
18570 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
18571 // register. In most cases we actually compare or select YMM-sized registers
18572 // and mixing the two types creates horrible code. This method optimizes
18573 // some of the transition sequences.
18574 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
18575 TargetLowering::DAGCombinerInfo &DCI,
18576 const X86Subtarget *Subtarget) {
18577 EVT VT = N->getValueType(0);
18578 if (!VT.is256BitVector())
18581 assert((N->getOpcode() == ISD::ANY_EXTEND ||
18582 N->getOpcode() == ISD::ZERO_EXTEND ||
18583 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
18585 SDValue Narrow = N->getOperand(0);
18586 EVT NarrowVT = Narrow->getValueType(0);
18587 if (!NarrowVT.is128BitVector())
18590 if (Narrow->getOpcode() != ISD::XOR &&
18591 Narrow->getOpcode() != ISD::AND &&
18592 Narrow->getOpcode() != ISD::OR)
18595 SDValue N0 = Narrow->getOperand(0);
18596 SDValue N1 = Narrow->getOperand(1);
18599 // The Left side has to be a trunc.
18600 if (N0.getOpcode() != ISD::TRUNCATE)
18603 // The type of the truncated inputs.
18604 EVT WideVT = N0->getOperand(0)->getValueType(0);
18608 // The right side has to be a 'trunc' or a constant vector.
18609 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
18610 bool RHSConst = (isSplatVector(N1.getNode()) &&
18611 isa<ConstantSDNode>(N1->getOperand(0)));
18612 if (!RHSTrunc && !RHSConst)
18615 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18617 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
18620 // Set N0 and N1 to hold the inputs to the new wide operation.
18621 N0 = N0->getOperand(0);
18623 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
18624 N1->getOperand(0));
18625 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
18626 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
18627 } else if (RHSTrunc) {
18628 N1 = N1->getOperand(0);
18631 // Generate the wide operation.
18632 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
18633 unsigned Opcode = N->getOpcode();
18635 case ISD::ANY_EXTEND:
18637 case ISD::ZERO_EXTEND: {
18638 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
18639 APInt Mask = APInt::getAllOnesValue(InBits);
18640 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
18641 return DAG.getNode(ISD::AND, DL, VT,
18642 Op, DAG.getConstant(Mask, VT));
18644 case ISD::SIGN_EXTEND:
18645 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
18646 Op, DAG.getValueType(NarrowVT));
18648 llvm_unreachable("Unexpected opcode");
18652 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
18653 TargetLowering::DAGCombinerInfo &DCI,
18654 const X86Subtarget *Subtarget) {
18655 EVT VT = N->getValueType(0);
18656 if (DCI.isBeforeLegalizeOps())
18659 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18663 // Create BEXTR instructions
18664 // BEXTR is ((X >> imm) & (2**size-1))
18665 if (VT == MVT::i32 || VT == MVT::i64) {
18666 SDValue N0 = N->getOperand(0);
18667 SDValue N1 = N->getOperand(1);
18670 // Check for BEXTR.
18671 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
18672 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
18673 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
18674 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
18675 if (MaskNode && ShiftNode) {
18676 uint64_t Mask = MaskNode->getZExtValue();
18677 uint64_t Shift = ShiftNode->getZExtValue();
18678 if (isMask_64(Mask)) {
18679 uint64_t MaskSize = CountPopulation_64(Mask);
18680 if (Shift + MaskSize <= VT.getSizeInBits())
18681 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
18682 DAG.getConstant(Shift | (MaskSize << 8), VT));
18690 // Want to form ANDNP nodes:
18691 // 1) In the hopes of then easily combining them with OR and AND nodes
18692 // to form PBLEND/PSIGN.
18693 // 2) To match ANDN packed intrinsics
18694 if (VT != MVT::v2i64 && VT != MVT::v4i64)
18697 SDValue N0 = N->getOperand(0);
18698 SDValue N1 = N->getOperand(1);
18701 // Check LHS for vnot
18702 if (N0.getOpcode() == ISD::XOR &&
18703 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
18704 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
18705 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
18707 // Check RHS for vnot
18708 if (N1.getOpcode() == ISD::XOR &&
18709 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
18710 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
18711 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
18716 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
18717 TargetLowering::DAGCombinerInfo &DCI,
18718 const X86Subtarget *Subtarget) {
18719 if (DCI.isBeforeLegalizeOps())
18722 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18726 SDValue N0 = N->getOperand(0);
18727 SDValue N1 = N->getOperand(1);
18728 EVT VT = N->getValueType(0);
18730 // look for psign/blend
18731 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
18732 if (!Subtarget->hasSSSE3() ||
18733 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
18736 // Canonicalize pandn to RHS
18737 if (N0.getOpcode() == X86ISD::ANDNP)
18739 // or (and (m, y), (pandn m, x))
18740 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
18741 SDValue Mask = N1.getOperand(0);
18742 SDValue X = N1.getOperand(1);
18744 if (N0.getOperand(0) == Mask)
18745 Y = N0.getOperand(1);
18746 if (N0.getOperand(1) == Mask)
18747 Y = N0.getOperand(0);
18749 // Check to see if the mask appeared in both the AND and ANDNP and
18753 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
18754 // Look through mask bitcast.
18755 if (Mask.getOpcode() == ISD::BITCAST)
18756 Mask = Mask.getOperand(0);
18757 if (X.getOpcode() == ISD::BITCAST)
18758 X = X.getOperand(0);
18759 if (Y.getOpcode() == ISD::BITCAST)
18760 Y = Y.getOperand(0);
18762 EVT MaskVT = Mask.getValueType();
18764 // Validate that the Mask operand is a vector sra node.
18765 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
18766 // there is no psrai.b
18767 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
18768 unsigned SraAmt = ~0;
18769 if (Mask.getOpcode() == ISD::SRA) {
18770 SDValue Amt = Mask.getOperand(1);
18771 if (isSplatVector(Amt.getNode())) {
18772 SDValue SclrAmt = Amt->getOperand(0);
18773 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
18774 SraAmt = C->getZExtValue();
18776 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
18777 SDValue SraC = Mask.getOperand(1);
18778 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
18780 if ((SraAmt + 1) != EltBits)
18785 // Now we know we at least have a plendvb with the mask val. See if
18786 // we can form a psignb/w/d.
18787 // psign = x.type == y.type == mask.type && y = sub(0, x);
18788 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
18789 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
18790 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
18791 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
18792 "Unsupported VT for PSIGN");
18793 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
18794 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18796 // PBLENDVB only available on SSE 4.1
18797 if (!Subtarget->hasSSE41())
18800 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
18802 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
18803 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
18804 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
18805 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
18806 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18810 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
18813 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
18814 MachineFunction &MF = DAG.getMachineFunction();
18815 bool OptForSize = MF.getFunction()->getAttributes().
18816 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
18818 // SHLD/SHRD instructions have lower register pressure, but on some
18819 // platforms they have higher latency than the equivalent
18820 // series of shifts/or that would otherwise be generated.
18821 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
18822 // have higher latencies and we are not optimizing for size.
18823 if (!OptForSize && Subtarget->isSHLDSlow())
18826 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
18828 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
18830 if (!N0.hasOneUse() || !N1.hasOneUse())
18833 SDValue ShAmt0 = N0.getOperand(1);
18834 if (ShAmt0.getValueType() != MVT::i8)
18836 SDValue ShAmt1 = N1.getOperand(1);
18837 if (ShAmt1.getValueType() != MVT::i8)
18839 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
18840 ShAmt0 = ShAmt0.getOperand(0);
18841 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
18842 ShAmt1 = ShAmt1.getOperand(0);
18845 unsigned Opc = X86ISD::SHLD;
18846 SDValue Op0 = N0.getOperand(0);
18847 SDValue Op1 = N1.getOperand(0);
18848 if (ShAmt0.getOpcode() == ISD::SUB) {
18849 Opc = X86ISD::SHRD;
18850 std::swap(Op0, Op1);
18851 std::swap(ShAmt0, ShAmt1);
18854 unsigned Bits = VT.getSizeInBits();
18855 if (ShAmt1.getOpcode() == ISD::SUB) {
18856 SDValue Sum = ShAmt1.getOperand(0);
18857 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
18858 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
18859 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
18860 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
18861 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
18862 return DAG.getNode(Opc, DL, VT,
18864 DAG.getNode(ISD::TRUNCATE, DL,
18867 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
18868 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
18870 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
18871 return DAG.getNode(Opc, DL, VT,
18872 N0.getOperand(0), N1.getOperand(0),
18873 DAG.getNode(ISD::TRUNCATE, DL,
18880 // Generate NEG and CMOV for integer abs.
18881 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
18882 EVT VT = N->getValueType(0);
18884 // Since X86 does not have CMOV for 8-bit integer, we don't convert
18885 // 8-bit integer abs to NEG and CMOV.
18886 if (VT.isInteger() && VT.getSizeInBits() == 8)
18889 SDValue N0 = N->getOperand(0);
18890 SDValue N1 = N->getOperand(1);
18893 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
18894 // and change it to SUB and CMOV.
18895 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
18896 N0.getOpcode() == ISD::ADD &&
18897 N0.getOperand(1) == N1 &&
18898 N1.getOpcode() == ISD::SRA &&
18899 N1.getOperand(0) == N0.getOperand(0))
18900 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
18901 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
18902 // Generate SUB & CMOV.
18903 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
18904 DAG.getConstant(0, VT), N0.getOperand(0));
18906 SDValue Ops[] = { N0.getOperand(0), Neg,
18907 DAG.getConstant(X86::COND_GE, MVT::i8),
18908 SDValue(Neg.getNode(), 1) };
18909 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
18914 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
18915 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
18916 TargetLowering::DAGCombinerInfo &DCI,
18917 const X86Subtarget *Subtarget) {
18918 if (DCI.isBeforeLegalizeOps())
18921 if (Subtarget->hasCMov()) {
18922 SDValue RV = performIntegerAbsCombine(N, DAG);
18930 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
18931 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
18932 TargetLowering::DAGCombinerInfo &DCI,
18933 const X86Subtarget *Subtarget) {
18934 LoadSDNode *Ld = cast<LoadSDNode>(N);
18935 EVT RegVT = Ld->getValueType(0);
18936 EVT MemVT = Ld->getMemoryVT();
18938 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18939 unsigned RegSz = RegVT.getSizeInBits();
18941 // On Sandybridge unaligned 256bit loads are inefficient.
18942 ISD::LoadExtType Ext = Ld->getExtensionType();
18943 unsigned Alignment = Ld->getAlignment();
18944 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
18945 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
18946 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
18947 unsigned NumElems = RegVT.getVectorNumElements();
18951 SDValue Ptr = Ld->getBasePtr();
18952 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
18954 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18956 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18957 Ld->getPointerInfo(), Ld->isVolatile(),
18958 Ld->isNonTemporal(), Ld->isInvariant(),
18960 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18961 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18962 Ld->getPointerInfo(), Ld->isVolatile(),
18963 Ld->isNonTemporal(), Ld->isInvariant(),
18964 std::min(16U, Alignment));
18965 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18967 Load2.getValue(1));
18969 SDValue NewVec = DAG.getUNDEF(RegVT);
18970 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
18971 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
18972 return DCI.CombineTo(N, NewVec, TF, true);
18975 // If this is a vector EXT Load then attempt to optimize it using a
18976 // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
18977 // expansion is still better than scalar code.
18978 // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
18979 // emit a shuffle and a arithmetic shift.
18980 // TODO: It is possible to support ZExt by zeroing the undef values
18981 // during the shuffle phase or after the shuffle.
18982 if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
18983 (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
18984 assert(MemVT != RegVT && "Cannot extend to the same type");
18985 assert(MemVT.isVector() && "Must load a vector from memory");
18987 unsigned NumElems = RegVT.getVectorNumElements();
18988 unsigned MemSz = MemVT.getSizeInBits();
18989 assert(RegSz > MemSz && "Register size must be greater than the mem size");
18991 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
18994 // All sizes must be a power of two.
18995 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
18998 // Attempt to load the original value using scalar loads.
18999 // Find the largest scalar type that divides the total loaded size.
19000 MVT SclrLoadTy = MVT::i8;
19001 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19002 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19003 MVT Tp = (MVT::SimpleValueType)tp;
19004 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
19009 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19010 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
19012 SclrLoadTy = MVT::f64;
19014 // Calculate the number of scalar loads that we need to perform
19015 // in order to load our vector from memory.
19016 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
19017 if (Ext == ISD::SEXTLOAD && NumLoads > 1)
19020 unsigned loadRegZize = RegSz;
19021 if (Ext == ISD::SEXTLOAD && RegSz == 256)
19024 // Represent our vector as a sequence of elements which are the
19025 // largest scalar that we can load.
19026 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
19027 loadRegZize/SclrLoadTy.getSizeInBits());
19029 // Represent the data using the same element type that is stored in
19030 // memory. In practice, we ''widen'' MemVT.
19032 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19033 loadRegZize/MemVT.getScalarType().getSizeInBits());
19035 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
19036 "Invalid vector type");
19038 // We can't shuffle using an illegal type.
19039 if (!TLI.isTypeLegal(WideVecVT))
19042 SmallVector<SDValue, 8> Chains;
19043 SDValue Ptr = Ld->getBasePtr();
19044 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
19045 TLI.getPointerTy());
19046 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
19048 for (unsigned i = 0; i < NumLoads; ++i) {
19049 // Perform a single load.
19050 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
19051 Ptr, Ld->getPointerInfo(),
19052 Ld->isVolatile(), Ld->isNonTemporal(),
19053 Ld->isInvariant(), Ld->getAlignment());
19054 Chains.push_back(ScalarLoad.getValue(1));
19055 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
19056 // another round of DAGCombining.
19058 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
19060 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
19061 ScalarLoad, DAG.getIntPtrConstant(i));
19063 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19066 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19068 // Bitcast the loaded value to a vector of the original element type, in
19069 // the size of the target vector type.
19070 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
19071 unsigned SizeRatio = RegSz/MemSz;
19073 if (Ext == ISD::SEXTLOAD) {
19074 // If we have SSE4.1 we can directly emit a VSEXT node.
19075 if (Subtarget->hasSSE41()) {
19076 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
19077 return DCI.CombineTo(N, Sext, TF, true);
19080 // Otherwise we'll shuffle the small elements in the high bits of the
19081 // larger type and perform an arithmetic shift. If the shift is not legal
19082 // it's better to scalarize.
19083 if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
19086 // Redistribute the loaded elements into the different locations.
19087 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19088 for (unsigned i = 0; i != NumElems; ++i)
19089 ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
19091 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19092 DAG.getUNDEF(WideVecVT),
19095 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19097 // Build the arithmetic shift.
19098 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
19099 MemVT.getVectorElementType().getSizeInBits();
19100 Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
19101 DAG.getConstant(Amt, RegVT));
19103 return DCI.CombineTo(N, Shuff, TF, true);
19106 // Redistribute the loaded elements into the different locations.
19107 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19108 for (unsigned i = 0; i != NumElems; ++i)
19109 ShuffleVec[i*SizeRatio] = i;
19111 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19112 DAG.getUNDEF(WideVecVT),
19115 // Bitcast to the requested type.
19116 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19117 // Replace the original load with the new sequence
19118 // and return the new chain.
19119 return DCI.CombineTo(N, Shuff, TF, true);
19125 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
19126 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
19127 const X86Subtarget *Subtarget) {
19128 StoreSDNode *St = cast<StoreSDNode>(N);
19129 EVT VT = St->getValue().getValueType();
19130 EVT StVT = St->getMemoryVT();
19132 SDValue StoredVal = St->getOperand(1);
19133 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19135 // If we are saving a concatenation of two XMM registers, perform two stores.
19136 // On Sandy Bridge, 256-bit memory operations are executed by two
19137 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
19138 // memory operation.
19139 unsigned Alignment = St->getAlignment();
19140 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
19141 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
19142 StVT == VT && !IsAligned) {
19143 unsigned NumElems = VT.getVectorNumElements();
19147 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
19148 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
19150 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
19151 SDValue Ptr0 = St->getBasePtr();
19152 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
19154 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
19155 St->getPointerInfo(), St->isVolatile(),
19156 St->isNonTemporal(), Alignment);
19157 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
19158 St->getPointerInfo(), St->isVolatile(),
19159 St->isNonTemporal(),
19160 std::min(16U, Alignment));
19161 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
19164 // Optimize trunc store (of multiple scalars) to shuffle and store.
19165 // First, pack all of the elements in one place. Next, store to memory
19166 // in fewer chunks.
19167 if (St->isTruncatingStore() && VT.isVector()) {
19168 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19169 unsigned NumElems = VT.getVectorNumElements();
19170 assert(StVT != VT && "Cannot truncate to the same type");
19171 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
19172 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
19174 // From, To sizes and ElemCount must be pow of two
19175 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
19176 // We are going to use the original vector elt for storing.
19177 // Accumulated smaller vector elements must be a multiple of the store size.
19178 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
19180 unsigned SizeRatio = FromSz / ToSz;
19182 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
19184 // Create a type on which we perform the shuffle
19185 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
19186 StVT.getScalarType(), NumElems*SizeRatio);
19188 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
19190 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
19191 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19192 for (unsigned i = 0; i != NumElems; ++i)
19193 ShuffleVec[i] = i * SizeRatio;
19195 // Can't shuffle using an illegal type.
19196 if (!TLI.isTypeLegal(WideVecVT))
19199 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
19200 DAG.getUNDEF(WideVecVT),
19202 // At this point all of the data is stored at the bottom of the
19203 // register. We now need to save it to mem.
19205 // Find the largest store unit
19206 MVT StoreType = MVT::i8;
19207 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19208 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19209 MVT Tp = (MVT::SimpleValueType)tp;
19210 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
19214 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19215 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
19216 (64 <= NumElems * ToSz))
19217 StoreType = MVT::f64;
19219 // Bitcast the original vector into a vector of store-size units
19220 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
19221 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
19222 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
19223 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
19224 SmallVector<SDValue, 8> Chains;
19225 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
19226 TLI.getPointerTy());
19227 SDValue Ptr = St->getBasePtr();
19229 // Perform one or more big stores into memory.
19230 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
19231 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
19232 StoreType, ShuffWide,
19233 DAG.getIntPtrConstant(i));
19234 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
19235 St->getPointerInfo(), St->isVolatile(),
19236 St->isNonTemporal(), St->getAlignment());
19237 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19238 Chains.push_back(Ch);
19241 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19244 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
19245 // the FP state in cases where an emms may be missing.
19246 // A preferable solution to the general problem is to figure out the right
19247 // places to insert EMMS. This qualifies as a quick hack.
19249 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
19250 if (VT.getSizeInBits() != 64)
19253 const Function *F = DAG.getMachineFunction().getFunction();
19254 bool NoImplicitFloatOps = F->getAttributes().
19255 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
19256 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
19257 && Subtarget->hasSSE2();
19258 if ((VT.isVector() ||
19259 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
19260 isa<LoadSDNode>(St->getValue()) &&
19261 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
19262 St->getChain().hasOneUse() && !St->isVolatile()) {
19263 SDNode* LdVal = St->getValue().getNode();
19264 LoadSDNode *Ld = nullptr;
19265 int TokenFactorIndex = -1;
19266 SmallVector<SDValue, 8> Ops;
19267 SDNode* ChainVal = St->getChain().getNode();
19268 // Must be a store of a load. We currently handle two cases: the load
19269 // is a direct child, and it's under an intervening TokenFactor. It is
19270 // possible to dig deeper under nested TokenFactors.
19271 if (ChainVal == LdVal)
19272 Ld = cast<LoadSDNode>(St->getChain());
19273 else if (St->getValue().hasOneUse() &&
19274 ChainVal->getOpcode() == ISD::TokenFactor) {
19275 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
19276 if (ChainVal->getOperand(i).getNode() == LdVal) {
19277 TokenFactorIndex = i;
19278 Ld = cast<LoadSDNode>(St->getValue());
19280 Ops.push_back(ChainVal->getOperand(i));
19284 if (!Ld || !ISD::isNormalLoad(Ld))
19287 // If this is not the MMX case, i.e. we are just turning i64 load/store
19288 // into f64 load/store, avoid the transformation if there are multiple
19289 // uses of the loaded value.
19290 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
19295 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
19296 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
19298 if (Subtarget->is64Bit() || F64IsLegal) {
19299 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
19300 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
19301 Ld->getPointerInfo(), Ld->isVolatile(),
19302 Ld->isNonTemporal(), Ld->isInvariant(),
19303 Ld->getAlignment());
19304 SDValue NewChain = NewLd.getValue(1);
19305 if (TokenFactorIndex != -1) {
19306 Ops.push_back(NewChain);
19307 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
19309 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
19310 St->getPointerInfo(),
19311 St->isVolatile(), St->isNonTemporal(),
19312 St->getAlignment());
19315 // Otherwise, lower to two pairs of 32-bit loads / stores.
19316 SDValue LoAddr = Ld->getBasePtr();
19317 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
19318 DAG.getConstant(4, MVT::i32));
19320 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
19321 Ld->getPointerInfo(),
19322 Ld->isVolatile(), Ld->isNonTemporal(),
19323 Ld->isInvariant(), Ld->getAlignment());
19324 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
19325 Ld->getPointerInfo().getWithOffset(4),
19326 Ld->isVolatile(), Ld->isNonTemporal(),
19328 MinAlign(Ld->getAlignment(), 4));
19330 SDValue NewChain = LoLd.getValue(1);
19331 if (TokenFactorIndex != -1) {
19332 Ops.push_back(LoLd);
19333 Ops.push_back(HiLd);
19334 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
19337 LoAddr = St->getBasePtr();
19338 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
19339 DAG.getConstant(4, MVT::i32));
19341 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
19342 St->getPointerInfo(),
19343 St->isVolatile(), St->isNonTemporal(),
19344 St->getAlignment());
19345 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
19346 St->getPointerInfo().getWithOffset(4),
19348 St->isNonTemporal(),
19349 MinAlign(St->getAlignment(), 4));
19350 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
19355 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
19356 /// and return the operands for the horizontal operation in LHS and RHS. A
19357 /// horizontal operation performs the binary operation on successive elements
19358 /// of its first operand, then on successive elements of its second operand,
19359 /// returning the resulting values in a vector. For example, if
19360 /// A = < float a0, float a1, float a2, float a3 >
19362 /// B = < float b0, float b1, float b2, float b3 >
19363 /// then the result of doing a horizontal operation on A and B is
19364 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
19365 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
19366 /// A horizontal-op B, for some already available A and B, and if so then LHS is
19367 /// set to A, RHS to B, and the routine returns 'true'.
19368 /// Note that the binary operation should have the property that if one of the
19369 /// operands is UNDEF then the result is UNDEF.
19370 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
19371 // Look for the following pattern: if
19372 // A = < float a0, float a1, float a2, float a3 >
19373 // B = < float b0, float b1, float b2, float b3 >
19375 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
19376 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
19377 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
19378 // which is A horizontal-op B.
19380 // At least one of the operands should be a vector shuffle.
19381 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
19382 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
19385 MVT VT = LHS.getSimpleValueType();
19387 assert((VT.is128BitVector() || VT.is256BitVector()) &&
19388 "Unsupported vector type for horizontal add/sub");
19390 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
19391 // operate independently on 128-bit lanes.
19392 unsigned NumElts = VT.getVectorNumElements();
19393 unsigned NumLanes = VT.getSizeInBits()/128;
19394 unsigned NumLaneElts = NumElts / NumLanes;
19395 assert((NumLaneElts % 2 == 0) &&
19396 "Vector type should have an even number of elements in each lane");
19397 unsigned HalfLaneElts = NumLaneElts/2;
19399 // View LHS in the form
19400 // LHS = VECTOR_SHUFFLE A, B, LMask
19401 // If LHS is not a shuffle then pretend it is the shuffle
19402 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
19403 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
19406 SmallVector<int, 16> LMask(NumElts);
19407 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19408 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
19409 A = LHS.getOperand(0);
19410 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
19411 B = LHS.getOperand(1);
19412 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
19413 std::copy(Mask.begin(), Mask.end(), LMask.begin());
19415 if (LHS.getOpcode() != ISD::UNDEF)
19417 for (unsigned i = 0; i != NumElts; ++i)
19421 // Likewise, view RHS in the form
19422 // RHS = VECTOR_SHUFFLE C, D, RMask
19424 SmallVector<int, 16> RMask(NumElts);
19425 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19426 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
19427 C = RHS.getOperand(0);
19428 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
19429 D = RHS.getOperand(1);
19430 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
19431 std::copy(Mask.begin(), Mask.end(), RMask.begin());
19433 if (RHS.getOpcode() != ISD::UNDEF)
19435 for (unsigned i = 0; i != NumElts; ++i)
19439 // Check that the shuffles are both shuffling the same vectors.
19440 if (!(A == C && B == D) && !(A == D && B == C))
19443 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
19444 if (!A.getNode() && !B.getNode())
19447 // If A and B occur in reverse order in RHS, then "swap" them (which means
19448 // rewriting the mask).
19450 CommuteVectorShuffleMask(RMask, NumElts);
19452 // At this point LHS and RHS are equivalent to
19453 // LHS = VECTOR_SHUFFLE A, B, LMask
19454 // RHS = VECTOR_SHUFFLE A, B, RMask
19455 // Check that the masks correspond to performing a horizontal operation.
19456 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
19457 for (unsigned i = 0; i != NumLaneElts; ++i) {
19458 int LIdx = LMask[i+l], RIdx = RMask[i+l];
19460 // Ignore any UNDEF components.
19461 if (LIdx < 0 || RIdx < 0 ||
19462 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
19463 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
19466 // Check that successive elements are being operated on. If not, this is
19467 // not a horizontal operation.
19468 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
19469 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
19470 if (!(LIdx == Index && RIdx == Index + 1) &&
19471 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
19476 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
19477 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
19481 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
19482 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
19483 const X86Subtarget *Subtarget) {
19484 EVT VT = N->getValueType(0);
19485 SDValue LHS = N->getOperand(0);
19486 SDValue RHS = N->getOperand(1);
19488 // Try to synthesize horizontal adds from adds of shuffles.
19489 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19490 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19491 isHorizontalBinOp(LHS, RHS, true))
19492 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
19496 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
19497 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
19498 const X86Subtarget *Subtarget) {
19499 EVT VT = N->getValueType(0);
19500 SDValue LHS = N->getOperand(0);
19501 SDValue RHS = N->getOperand(1);
19503 // Try to synthesize horizontal subs from subs of shuffles.
19504 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19505 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19506 isHorizontalBinOp(LHS, RHS, false))
19507 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
19511 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
19512 /// X86ISD::FXOR nodes.
19513 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
19514 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
19515 // F[X]OR(0.0, x) -> x
19516 // F[X]OR(x, 0.0) -> x
19517 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19518 if (C->getValueAPF().isPosZero())
19519 return N->getOperand(1);
19520 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19521 if (C->getValueAPF().isPosZero())
19522 return N->getOperand(0);
19526 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
19527 /// X86ISD::FMAX nodes.
19528 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
19529 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
19531 // Only perform optimizations if UnsafeMath is used.
19532 if (!DAG.getTarget().Options.UnsafeFPMath)
19535 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
19536 // into FMINC and FMAXC, which are Commutative operations.
19537 unsigned NewOp = 0;
19538 switch (N->getOpcode()) {
19539 default: llvm_unreachable("unknown opcode");
19540 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
19541 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
19544 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
19545 N->getOperand(0), N->getOperand(1));
19548 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
19549 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
19550 // FAND(0.0, x) -> 0.0
19551 // FAND(x, 0.0) -> 0.0
19552 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19553 if (C->getValueAPF().isPosZero())
19554 return N->getOperand(0);
19555 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19556 if (C->getValueAPF().isPosZero())
19557 return N->getOperand(1);
19561 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
19562 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
19563 // FANDN(x, 0.0) -> 0.0
19564 // FANDN(0.0, x) -> x
19565 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19566 if (C->getValueAPF().isPosZero())
19567 return N->getOperand(1);
19568 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19569 if (C->getValueAPF().isPosZero())
19570 return N->getOperand(1);
19574 static SDValue PerformBTCombine(SDNode *N,
19576 TargetLowering::DAGCombinerInfo &DCI) {
19577 // BT ignores high bits in the bit index operand.
19578 SDValue Op1 = N->getOperand(1);
19579 if (Op1.hasOneUse()) {
19580 unsigned BitWidth = Op1.getValueSizeInBits();
19581 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
19582 APInt KnownZero, KnownOne;
19583 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
19584 !DCI.isBeforeLegalizeOps());
19585 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19586 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
19587 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
19588 DCI.CommitTargetLoweringOpt(TLO);
19593 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
19594 SDValue Op = N->getOperand(0);
19595 if (Op.getOpcode() == ISD::BITCAST)
19596 Op = Op.getOperand(0);
19597 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
19598 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
19599 VT.getVectorElementType().getSizeInBits() ==
19600 OpVT.getVectorElementType().getSizeInBits()) {
19601 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
19606 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
19607 const X86Subtarget *Subtarget) {
19608 EVT VT = N->getValueType(0);
19609 if (!VT.isVector())
19612 SDValue N0 = N->getOperand(0);
19613 SDValue N1 = N->getOperand(1);
19614 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
19617 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
19618 // both SSE and AVX2 since there is no sign-extended shift right
19619 // operation on a vector with 64-bit elements.
19620 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
19621 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
19622 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
19623 N0.getOpcode() == ISD::SIGN_EXTEND)) {
19624 SDValue N00 = N0.getOperand(0);
19626 // EXTLOAD has a better solution on AVX2,
19627 // it may be replaced with X86ISD::VSEXT node.
19628 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
19629 if (!ISD::isNormalLoad(N00.getNode()))
19632 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
19633 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
19635 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
19641 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
19642 TargetLowering::DAGCombinerInfo &DCI,
19643 const X86Subtarget *Subtarget) {
19644 if (!DCI.isBeforeLegalizeOps())
19647 if (!Subtarget->hasFp256())
19650 EVT VT = N->getValueType(0);
19651 if (VT.isVector() && VT.getSizeInBits() == 256) {
19652 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19660 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
19661 const X86Subtarget* Subtarget) {
19663 EVT VT = N->getValueType(0);
19665 // Let legalize expand this if it isn't a legal type yet.
19666 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19669 EVT ScalarVT = VT.getScalarType();
19670 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
19671 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
19674 SDValue A = N->getOperand(0);
19675 SDValue B = N->getOperand(1);
19676 SDValue C = N->getOperand(2);
19678 bool NegA = (A.getOpcode() == ISD::FNEG);
19679 bool NegB = (B.getOpcode() == ISD::FNEG);
19680 bool NegC = (C.getOpcode() == ISD::FNEG);
19682 // Negative multiplication when NegA xor NegB
19683 bool NegMul = (NegA != NegB);
19685 A = A.getOperand(0);
19687 B = B.getOperand(0);
19689 C = C.getOperand(0);
19693 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
19695 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
19697 return DAG.getNode(Opcode, dl, VT, A, B, C);
19700 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
19701 TargetLowering::DAGCombinerInfo &DCI,
19702 const X86Subtarget *Subtarget) {
19703 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
19704 // (and (i32 x86isd::setcc_carry), 1)
19705 // This eliminates the zext. This transformation is necessary because
19706 // ISD::SETCC is always legalized to i8.
19708 SDValue N0 = N->getOperand(0);
19709 EVT VT = N->getValueType(0);
19711 if (N0.getOpcode() == ISD::AND &&
19713 N0.getOperand(0).hasOneUse()) {
19714 SDValue N00 = N0.getOperand(0);
19715 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19716 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19717 if (!C || C->getZExtValue() != 1)
19719 return DAG.getNode(ISD::AND, dl, VT,
19720 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19721 N00.getOperand(0), N00.getOperand(1)),
19722 DAG.getConstant(1, VT));
19726 if (N0.getOpcode() == ISD::TRUNCATE &&
19728 N0.getOperand(0).hasOneUse()) {
19729 SDValue N00 = N0.getOperand(0);
19730 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19731 return DAG.getNode(ISD::AND, dl, VT,
19732 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19733 N00.getOperand(0), N00.getOperand(1)),
19734 DAG.getConstant(1, VT));
19737 if (VT.is256BitVector()) {
19738 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19746 // Optimize x == -y --> x+y == 0
19747 // x != -y --> x+y != 0
19748 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
19749 const X86Subtarget* Subtarget) {
19750 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
19751 SDValue LHS = N->getOperand(0);
19752 SDValue RHS = N->getOperand(1);
19753 EVT VT = N->getValueType(0);
19756 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
19757 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
19758 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
19759 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19760 LHS.getValueType(), RHS, LHS.getOperand(1));
19761 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19762 addV, DAG.getConstant(0, addV.getValueType()), CC);
19764 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
19765 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
19766 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
19767 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19768 RHS.getValueType(), LHS, RHS.getOperand(1));
19769 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19770 addV, DAG.getConstant(0, addV.getValueType()), CC);
19773 if (VT.getScalarType() == MVT::i1) {
19774 bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
19775 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
19776 bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
19777 if (!IsSEXT0 && !IsVZero0)
19779 bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
19780 (RHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
19781 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
19783 if (!IsSEXT1 && !IsVZero1)
19786 if (IsSEXT0 && IsVZero1) {
19787 assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
19788 if (CC == ISD::SETEQ)
19789 return DAG.getNOT(DL, LHS.getOperand(0), VT);
19790 return LHS.getOperand(0);
19792 if (IsSEXT1 && IsVZero0) {
19793 assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
19794 if (CC == ISD::SETEQ)
19795 return DAG.getNOT(DL, RHS.getOperand(0), VT);
19796 return RHS.getOperand(0);
19803 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
19804 // as "sbb reg,reg", since it can be extended without zext and produces
19805 // an all-ones bit which is more useful than 0/1 in some cases.
19806 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
19809 return DAG.getNode(ISD::AND, DL, VT,
19810 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19811 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
19812 DAG.getConstant(1, VT));
19813 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
19814 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
19815 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19816 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
19819 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
19820 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
19821 TargetLowering::DAGCombinerInfo &DCI,
19822 const X86Subtarget *Subtarget) {
19824 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
19825 SDValue EFLAGS = N->getOperand(1);
19827 if (CC == X86::COND_A) {
19828 // Try to convert COND_A into COND_B in an attempt to facilitate
19829 // materializing "setb reg".
19831 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
19832 // cannot take an immediate as its first operand.
19834 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
19835 EFLAGS.getValueType().isInteger() &&
19836 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
19837 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
19838 EFLAGS.getNode()->getVTList(),
19839 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
19840 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
19841 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
19845 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
19846 // a zext and produces an all-ones bit which is more useful than 0/1 in some
19848 if (CC == X86::COND_B)
19849 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
19853 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19854 if (Flags.getNode()) {
19855 SDValue Cond = DAG.getConstant(CC, MVT::i8);
19856 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
19862 // Optimize branch condition evaluation.
19864 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
19865 TargetLowering::DAGCombinerInfo &DCI,
19866 const X86Subtarget *Subtarget) {
19868 SDValue Chain = N->getOperand(0);
19869 SDValue Dest = N->getOperand(1);
19870 SDValue EFLAGS = N->getOperand(3);
19871 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
19875 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19876 if (Flags.getNode()) {
19877 SDValue Cond = DAG.getConstant(CC, MVT::i8);
19878 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
19885 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
19886 const X86TargetLowering *XTLI) {
19887 SDValue Op0 = N->getOperand(0);
19888 EVT InVT = Op0->getValueType(0);
19890 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
19891 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
19893 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
19894 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
19895 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
19898 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
19899 // a 32-bit target where SSE doesn't support i64->FP operations.
19900 if (Op0.getOpcode() == ISD::LOAD) {
19901 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
19902 EVT VT = Ld->getValueType(0);
19903 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
19904 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
19905 !XTLI->getSubtarget()->is64Bit() &&
19907 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
19908 Ld->getChain(), Op0, DAG);
19909 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
19916 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
19917 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
19918 X86TargetLowering::DAGCombinerInfo &DCI) {
19919 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
19920 // the result is either zero or one (depending on the input carry bit).
19921 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
19922 if (X86::isZeroNode(N->getOperand(0)) &&
19923 X86::isZeroNode(N->getOperand(1)) &&
19924 // We don't have a good way to replace an EFLAGS use, so only do this when
19926 SDValue(N, 1).use_empty()) {
19928 EVT VT = N->getValueType(0);
19929 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
19930 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
19931 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
19932 DAG.getConstant(X86::COND_B,MVT::i8),
19934 DAG.getConstant(1, VT));
19935 return DCI.CombineTo(N, Res1, CarryOut);
19941 // fold (add Y, (sete X, 0)) -> adc 0, Y
19942 // (add Y, (setne X, 0)) -> sbb -1, Y
19943 // (sub (sete X, 0), Y) -> sbb 0, Y
19944 // (sub (setne X, 0), Y) -> adc -1, Y
19945 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
19948 // Look through ZExts.
19949 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
19950 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
19953 SDValue SetCC = Ext.getOperand(0);
19954 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
19957 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
19958 if (CC != X86::COND_E && CC != X86::COND_NE)
19961 SDValue Cmp = SetCC.getOperand(1);
19962 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
19963 !X86::isZeroNode(Cmp.getOperand(1)) ||
19964 !Cmp.getOperand(0).getValueType().isInteger())
19967 SDValue CmpOp0 = Cmp.getOperand(0);
19968 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
19969 DAG.getConstant(1, CmpOp0.getValueType()));
19971 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
19972 if (CC == X86::COND_NE)
19973 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
19974 DL, OtherVal.getValueType(), OtherVal,
19975 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
19976 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
19977 DL, OtherVal.getValueType(), OtherVal,
19978 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
19981 /// PerformADDCombine - Do target-specific dag combines on integer adds.
19982 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
19983 const X86Subtarget *Subtarget) {
19984 EVT VT = N->getValueType(0);
19985 SDValue Op0 = N->getOperand(0);
19986 SDValue Op1 = N->getOperand(1);
19988 // Try to synthesize horizontal adds from adds of shuffles.
19989 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19990 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19991 isHorizontalBinOp(Op0, Op1, true))
19992 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
19994 return OptimizeConditionalInDecrement(N, DAG);
19997 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
19998 const X86Subtarget *Subtarget) {
19999 SDValue Op0 = N->getOperand(0);
20000 SDValue Op1 = N->getOperand(1);
20002 // X86 can't encode an immediate LHS of a sub. See if we can push the
20003 // negation into a preceding instruction.
20004 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
20005 // If the RHS of the sub is a XOR with one use and a constant, invert the
20006 // immediate. Then add one to the LHS of the sub so we can turn
20007 // X-Y -> X+~Y+1, saving one register.
20008 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
20009 isa<ConstantSDNode>(Op1.getOperand(1))) {
20010 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
20011 EVT VT = Op0.getValueType();
20012 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
20014 DAG.getConstant(~XorC, VT));
20015 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
20016 DAG.getConstant(C->getAPIntValue()+1, VT));
20020 // Try to synthesize horizontal adds from adds of shuffles.
20021 EVT VT = N->getValueType(0);
20022 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20023 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20024 isHorizontalBinOp(Op0, Op1, true))
20025 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
20027 return OptimizeConditionalInDecrement(N, DAG);
20030 /// performVZEXTCombine - Performs build vector combines
20031 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
20032 TargetLowering::DAGCombinerInfo &DCI,
20033 const X86Subtarget *Subtarget) {
20034 // (vzext (bitcast (vzext (x)) -> (vzext x)
20035 SDValue In = N->getOperand(0);
20036 while (In.getOpcode() == ISD::BITCAST)
20037 In = In.getOperand(0);
20039 if (In.getOpcode() != X86ISD::VZEXT)
20042 return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
20046 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
20047 DAGCombinerInfo &DCI) const {
20048 SelectionDAG &DAG = DCI.DAG;
20049 switch (N->getOpcode()) {
20051 case ISD::EXTRACT_VECTOR_ELT:
20052 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
20054 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
20055 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
20056 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
20057 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
20058 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
20059 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
20062 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
20063 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
20064 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
20065 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
20066 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
20067 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
20068 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
20069 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
20070 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
20072 case X86ISD::FOR: return PerformFORCombine(N, DAG);
20074 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
20075 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
20076 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
20077 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
20078 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
20079 case ISD::ANY_EXTEND:
20080 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
20081 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
20082 case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
20083 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
20084 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
20085 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
20086 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
20087 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
20088 case X86ISD::SHUFP: // Handle all target specific shuffles
20089 case X86ISD::PALIGNR:
20090 case X86ISD::UNPCKH:
20091 case X86ISD::UNPCKL:
20092 case X86ISD::MOVHLPS:
20093 case X86ISD::MOVLHPS:
20094 case X86ISD::PSHUFD:
20095 case X86ISD::PSHUFHW:
20096 case X86ISD::PSHUFLW:
20097 case X86ISD::MOVSS:
20098 case X86ISD::MOVSD:
20099 case X86ISD::VPERMILP:
20100 case X86ISD::VPERM2X128:
20101 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
20102 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
20108 /// isTypeDesirableForOp - Return true if the target has native support for
20109 /// the specified value type and it is 'desirable' to use the type for the
20110 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
20111 /// instruction encodings are longer and some i16 instructions are slow.
20112 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
20113 if (!isTypeLegal(VT))
20115 if (VT != MVT::i16)
20122 case ISD::SIGN_EXTEND:
20123 case ISD::ZERO_EXTEND:
20124 case ISD::ANY_EXTEND:
20137 /// IsDesirableToPromoteOp - This method query the target whether it is
20138 /// beneficial for dag combiner to promote the specified node. If true, it
20139 /// should return the desired promotion type by reference.
20140 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
20141 EVT VT = Op.getValueType();
20142 if (VT != MVT::i16)
20145 bool Promote = false;
20146 bool Commute = false;
20147 switch (Op.getOpcode()) {
20150 LoadSDNode *LD = cast<LoadSDNode>(Op);
20151 // If the non-extending load has a single use and it's not live out, then it
20152 // might be folded.
20153 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
20154 Op.hasOneUse()*/) {
20155 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
20156 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
20157 // The only case where we'd want to promote LOAD (rather then it being
20158 // promoted as an operand is when it's only use is liveout.
20159 if (UI->getOpcode() != ISD::CopyToReg)
20166 case ISD::SIGN_EXTEND:
20167 case ISD::ZERO_EXTEND:
20168 case ISD::ANY_EXTEND:
20173 SDValue N0 = Op.getOperand(0);
20174 // Look out for (store (shl (load), x)).
20175 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
20188 SDValue N0 = Op.getOperand(0);
20189 SDValue N1 = Op.getOperand(1);
20190 if (!Commute && MayFoldLoad(N1))
20192 // Avoid disabling potential load folding opportunities.
20193 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
20195 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
20205 //===----------------------------------------------------------------------===//
20206 // X86 Inline Assembly Support
20207 //===----------------------------------------------------------------------===//
20210 // Helper to match a string separated by whitespace.
20211 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
20212 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
20214 for (unsigned i = 0, e = args.size(); i != e; ++i) {
20215 StringRef piece(*args[i]);
20216 if (!s.startswith(piece)) // Check if the piece matches.
20219 s = s.substr(piece.size());
20220 StringRef::size_type pos = s.find_first_not_of(" \t");
20221 if (pos == 0) // We matched a prefix.
20229 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
20232 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
20234 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
20235 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
20236 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
20237 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
20239 if (AsmPieces.size() == 3)
20241 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
20248 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
20249 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
20251 std::string AsmStr = IA->getAsmString();
20253 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
20254 if (!Ty || Ty->getBitWidth() % 16 != 0)
20257 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
20258 SmallVector<StringRef, 4> AsmPieces;
20259 SplitString(AsmStr, AsmPieces, ";\n");
20261 switch (AsmPieces.size()) {
20262 default: return false;
20264 // FIXME: this should verify that we are targeting a 486 or better. If not,
20265 // we will turn this bswap into something that will be lowered to logical
20266 // ops instead of emitting the bswap asm. For now, we don't support 486 or
20267 // lower so don't worry about this.
20269 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
20270 matchAsm(AsmPieces[0], "bswapl", "$0") ||
20271 matchAsm(AsmPieces[0], "bswapq", "$0") ||
20272 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
20273 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
20274 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
20275 // No need to check constraints, nothing other than the equivalent of
20276 // "=r,0" would be valid here.
20277 return IntrinsicLowering::LowerToByteSwap(CI);
20280 // rorw $$8, ${0:w} --> llvm.bswap.i16
20281 if (CI->getType()->isIntegerTy(16) &&
20282 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20283 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
20284 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
20286 const std::string &ConstraintsStr = IA->getConstraintString();
20287 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20288 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20289 if (clobbersFlagRegisters(AsmPieces))
20290 return IntrinsicLowering::LowerToByteSwap(CI);
20294 if (CI->getType()->isIntegerTy(32) &&
20295 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20296 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
20297 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
20298 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
20300 const std::string &ConstraintsStr = IA->getConstraintString();
20301 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20302 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20303 if (clobbersFlagRegisters(AsmPieces))
20304 return IntrinsicLowering::LowerToByteSwap(CI);
20307 if (CI->getType()->isIntegerTy(64)) {
20308 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
20309 if (Constraints.size() >= 2 &&
20310 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
20311 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
20312 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
20313 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
20314 matchAsm(AsmPieces[1], "bswap", "%edx") &&
20315 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
20316 return IntrinsicLowering::LowerToByteSwap(CI);
20324 /// getConstraintType - Given a constraint letter, return the type of
20325 /// constraint it is for this target.
20326 X86TargetLowering::ConstraintType
20327 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
20328 if (Constraint.size() == 1) {
20329 switch (Constraint[0]) {
20340 return C_RegisterClass;
20364 return TargetLowering::getConstraintType(Constraint);
20367 /// Examine constraint type and operand type and determine a weight value.
20368 /// This object must already have been set up with the operand type
20369 /// and the current alternative constraint selected.
20370 TargetLowering::ConstraintWeight
20371 X86TargetLowering::getSingleConstraintMatchWeight(
20372 AsmOperandInfo &info, const char *constraint) const {
20373 ConstraintWeight weight = CW_Invalid;
20374 Value *CallOperandVal = info.CallOperandVal;
20375 // If we don't have a value, we can't do a match,
20376 // but allow it at the lowest weight.
20377 if (!CallOperandVal)
20379 Type *type = CallOperandVal->getType();
20380 // Look at the constraint type.
20381 switch (*constraint) {
20383 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
20394 if (CallOperandVal->getType()->isIntegerTy())
20395 weight = CW_SpecificReg;
20400 if (type->isFloatingPointTy())
20401 weight = CW_SpecificReg;
20404 if (type->isX86_MMXTy() && Subtarget->hasMMX())
20405 weight = CW_SpecificReg;
20409 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
20410 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
20411 weight = CW_Register;
20414 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
20415 if (C->getZExtValue() <= 31)
20416 weight = CW_Constant;
20420 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20421 if (C->getZExtValue() <= 63)
20422 weight = CW_Constant;
20426 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20427 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
20428 weight = CW_Constant;
20432 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20433 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
20434 weight = CW_Constant;
20438 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20439 if (C->getZExtValue() <= 3)
20440 weight = CW_Constant;
20444 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20445 if (C->getZExtValue() <= 0xff)
20446 weight = CW_Constant;
20451 if (dyn_cast<ConstantFP>(CallOperandVal)) {
20452 weight = CW_Constant;
20456 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20457 if ((C->getSExtValue() >= -0x80000000LL) &&
20458 (C->getSExtValue() <= 0x7fffffffLL))
20459 weight = CW_Constant;
20463 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20464 if (C->getZExtValue() <= 0xffffffff)
20465 weight = CW_Constant;
20472 /// LowerXConstraint - try to replace an X constraint, which matches anything,
20473 /// with another that has more specific requirements based on the type of the
20474 /// corresponding operand.
20475 const char *X86TargetLowering::
20476 LowerXConstraint(EVT ConstraintVT) const {
20477 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
20478 // 'f' like normal targets.
20479 if (ConstraintVT.isFloatingPoint()) {
20480 if (Subtarget->hasSSE2())
20482 if (Subtarget->hasSSE1())
20486 return TargetLowering::LowerXConstraint(ConstraintVT);
20489 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
20490 /// vector. If it is invalid, don't add anything to Ops.
20491 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
20492 std::string &Constraint,
20493 std::vector<SDValue>&Ops,
20494 SelectionDAG &DAG) const {
20497 // Only support length 1 constraints for now.
20498 if (Constraint.length() > 1) return;
20500 char ConstraintLetter = Constraint[0];
20501 switch (ConstraintLetter) {
20504 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20505 if (C->getZExtValue() <= 31) {
20506 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20512 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20513 if (C->getZExtValue() <= 63) {
20514 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20520 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20521 if (isInt<8>(C->getSExtValue())) {
20522 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20528 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20529 if (C->getZExtValue() <= 255) {
20530 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20536 // 32-bit signed value
20537 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20538 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20539 C->getSExtValue())) {
20540 // Widen to 64 bits here to get it sign extended.
20541 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
20544 // FIXME gcc accepts some relocatable values here too, but only in certain
20545 // memory models; it's complicated.
20550 // 32-bit unsigned value
20551 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20552 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20553 C->getZExtValue())) {
20554 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20558 // FIXME gcc accepts some relocatable values here too, but only in certain
20559 // memory models; it's complicated.
20563 // Literal immediates are always ok.
20564 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
20565 // Widen to 64 bits here to get it sign extended.
20566 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
20570 // In any sort of PIC mode addresses need to be computed at runtime by
20571 // adding in a register or some sort of table lookup. These can't
20572 // be used as immediates.
20573 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
20576 // If we are in non-pic codegen mode, we allow the address of a global (with
20577 // an optional displacement) to be used with 'i'.
20578 GlobalAddressSDNode *GA = nullptr;
20579 int64_t Offset = 0;
20581 // Match either (GA), (GA+C), (GA+C1+C2), etc.
20583 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
20584 Offset += GA->getOffset();
20586 } else if (Op.getOpcode() == ISD::ADD) {
20587 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20588 Offset += C->getZExtValue();
20589 Op = Op.getOperand(0);
20592 } else if (Op.getOpcode() == ISD::SUB) {
20593 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20594 Offset += -C->getZExtValue();
20595 Op = Op.getOperand(0);
20600 // Otherwise, this isn't something we can handle, reject it.
20604 const GlobalValue *GV = GA->getGlobal();
20605 // If we require an extra load to get this address, as in PIC mode, we
20606 // can't accept it.
20607 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
20608 getTargetMachine())))
20611 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
20612 GA->getValueType(0), Offset);
20617 if (Result.getNode()) {
20618 Ops.push_back(Result);
20621 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
20624 std::pair<unsigned, const TargetRegisterClass*>
20625 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
20627 // First, see if this is a constraint that directly corresponds to an LLVM
20629 if (Constraint.size() == 1) {
20630 // GCC Constraint Letters
20631 switch (Constraint[0]) {
20633 // TODO: Slight differences here in allocation order and leaving
20634 // RIP in the class. Do they matter any more here than they do
20635 // in the normal allocation?
20636 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
20637 if (Subtarget->is64Bit()) {
20638 if (VT == MVT::i32 || VT == MVT::f32)
20639 return std::make_pair(0U, &X86::GR32RegClass);
20640 if (VT == MVT::i16)
20641 return std::make_pair(0U, &X86::GR16RegClass);
20642 if (VT == MVT::i8 || VT == MVT::i1)
20643 return std::make_pair(0U, &X86::GR8RegClass);
20644 if (VT == MVT::i64 || VT == MVT::f64)
20645 return std::make_pair(0U, &X86::GR64RegClass);
20648 // 32-bit fallthrough
20649 case 'Q': // Q_REGS
20650 if (VT == MVT::i32 || VT == MVT::f32)
20651 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
20652 if (VT == MVT::i16)
20653 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
20654 if (VT == MVT::i8 || VT == MVT::i1)
20655 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
20656 if (VT == MVT::i64)
20657 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
20659 case 'r': // GENERAL_REGS
20660 case 'l': // INDEX_REGS
20661 if (VT == MVT::i8 || VT == MVT::i1)
20662 return std::make_pair(0U, &X86::GR8RegClass);
20663 if (VT == MVT::i16)
20664 return std::make_pair(0U, &X86::GR16RegClass);
20665 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
20666 return std::make_pair(0U, &X86::GR32RegClass);
20667 return std::make_pair(0U, &X86::GR64RegClass);
20668 case 'R': // LEGACY_REGS
20669 if (VT == MVT::i8 || VT == MVT::i1)
20670 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
20671 if (VT == MVT::i16)
20672 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
20673 if (VT == MVT::i32 || !Subtarget->is64Bit())
20674 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
20675 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
20676 case 'f': // FP Stack registers.
20677 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
20678 // value to the correct fpstack register class.
20679 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
20680 return std::make_pair(0U, &X86::RFP32RegClass);
20681 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
20682 return std::make_pair(0U, &X86::RFP64RegClass);
20683 return std::make_pair(0U, &X86::RFP80RegClass);
20684 case 'y': // MMX_REGS if MMX allowed.
20685 if (!Subtarget->hasMMX()) break;
20686 return std::make_pair(0U, &X86::VR64RegClass);
20687 case 'Y': // SSE_REGS if SSE2 allowed
20688 if (!Subtarget->hasSSE2()) break;
20690 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
20691 if (!Subtarget->hasSSE1()) break;
20693 switch (VT.SimpleTy) {
20695 // Scalar SSE types.
20698 return std::make_pair(0U, &X86::FR32RegClass);
20701 return std::make_pair(0U, &X86::FR64RegClass);
20709 return std::make_pair(0U, &X86::VR128RegClass);
20717 return std::make_pair(0U, &X86::VR256RegClass);
20722 return std::make_pair(0U, &X86::VR512RegClass);
20728 // Use the default implementation in TargetLowering to convert the register
20729 // constraint into a member of a register class.
20730 std::pair<unsigned, const TargetRegisterClass*> Res;
20731 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
20733 // Not found as a standard register?
20735 // Map st(0) -> st(7) -> ST0
20736 if (Constraint.size() == 7 && Constraint[0] == '{' &&
20737 tolower(Constraint[1]) == 's' &&
20738 tolower(Constraint[2]) == 't' &&
20739 Constraint[3] == '(' &&
20740 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
20741 Constraint[5] == ')' &&
20742 Constraint[6] == '}') {
20744 Res.first = X86::ST0+Constraint[4]-'0';
20745 Res.second = &X86::RFP80RegClass;
20749 // GCC allows "st(0)" to be called just plain "st".
20750 if (StringRef("{st}").equals_lower(Constraint)) {
20751 Res.first = X86::ST0;
20752 Res.second = &X86::RFP80RegClass;
20757 if (StringRef("{flags}").equals_lower(Constraint)) {
20758 Res.first = X86::EFLAGS;
20759 Res.second = &X86::CCRRegClass;
20763 // 'A' means EAX + EDX.
20764 if (Constraint == "A") {
20765 Res.first = X86::EAX;
20766 Res.second = &X86::GR32_ADRegClass;
20772 // Otherwise, check to see if this is a register class of the wrong value
20773 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
20774 // turn into {ax},{dx}.
20775 if (Res.second->hasType(VT))
20776 return Res; // Correct type already, nothing to do.
20778 // All of the single-register GCC register classes map their values onto
20779 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
20780 // really want an 8-bit or 32-bit register, map to the appropriate register
20781 // class and return the appropriate register.
20782 if (Res.second == &X86::GR16RegClass) {
20783 if (VT == MVT::i8 || VT == MVT::i1) {
20784 unsigned DestReg = 0;
20785 switch (Res.first) {
20787 case X86::AX: DestReg = X86::AL; break;
20788 case X86::DX: DestReg = X86::DL; break;
20789 case X86::CX: DestReg = X86::CL; break;
20790 case X86::BX: DestReg = X86::BL; break;
20793 Res.first = DestReg;
20794 Res.second = &X86::GR8RegClass;
20796 } else if (VT == MVT::i32 || VT == MVT::f32) {
20797 unsigned DestReg = 0;
20798 switch (Res.first) {
20800 case X86::AX: DestReg = X86::EAX; break;
20801 case X86::DX: DestReg = X86::EDX; break;
20802 case X86::CX: DestReg = X86::ECX; break;
20803 case X86::BX: DestReg = X86::EBX; break;
20804 case X86::SI: DestReg = X86::ESI; break;
20805 case X86::DI: DestReg = X86::EDI; break;
20806 case X86::BP: DestReg = X86::EBP; break;
20807 case X86::SP: DestReg = X86::ESP; break;
20810 Res.first = DestReg;
20811 Res.second = &X86::GR32RegClass;
20813 } else if (VT == MVT::i64 || VT == MVT::f64) {
20814 unsigned DestReg = 0;
20815 switch (Res.first) {
20817 case X86::AX: DestReg = X86::RAX; break;
20818 case X86::DX: DestReg = X86::RDX; break;
20819 case X86::CX: DestReg = X86::RCX; break;
20820 case X86::BX: DestReg = X86::RBX; break;
20821 case X86::SI: DestReg = X86::RSI; break;
20822 case X86::DI: DestReg = X86::RDI; break;
20823 case X86::BP: DestReg = X86::RBP; break;
20824 case X86::SP: DestReg = X86::RSP; break;
20827 Res.first = DestReg;
20828 Res.second = &X86::GR64RegClass;
20831 } else if (Res.second == &X86::FR32RegClass ||
20832 Res.second == &X86::FR64RegClass ||
20833 Res.second == &X86::VR128RegClass ||
20834 Res.second == &X86::VR256RegClass ||
20835 Res.second == &X86::FR32XRegClass ||
20836 Res.second == &X86::FR64XRegClass ||
20837 Res.second == &X86::VR128XRegClass ||
20838 Res.second == &X86::VR256XRegClass ||
20839 Res.second == &X86::VR512RegClass) {
20840 // Handle references to XMM physical registers that got mapped into the
20841 // wrong class. This can happen with constraints like {xmm0} where the
20842 // target independent register mapper will just pick the first match it can
20843 // find, ignoring the required type.
20845 if (VT == MVT::f32 || VT == MVT::i32)
20846 Res.second = &X86::FR32RegClass;
20847 else if (VT == MVT::f64 || VT == MVT::i64)
20848 Res.second = &X86::FR64RegClass;
20849 else if (X86::VR128RegClass.hasType(VT))
20850 Res.second = &X86::VR128RegClass;
20851 else if (X86::VR256RegClass.hasType(VT))
20852 Res.second = &X86::VR256RegClass;
20853 else if (X86::VR512RegClass.hasType(VT))
20854 Res.second = &X86::VR512RegClass;
20860 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
20862 // Scaling factors are not free at all.
20863 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
20864 // will take 2 allocations in the out of order engine instead of 1
20865 // for plain addressing mode, i.e. inst (reg1).
20867 // vaddps (%rsi,%drx), %ymm0, %ymm1
20868 // Requires two allocations (one for the load, one for the computation)
20870 // vaddps (%rsi), %ymm0, %ymm1
20871 // Requires just 1 allocation, i.e., freeing allocations for other operations
20872 // and having less micro operations to execute.
20874 // For some X86 architectures, this is even worse because for instance for
20875 // stores, the complex addressing mode forces the instruction to use the
20876 // "load" ports instead of the dedicated "store" port.
20877 // E.g., on Haswell:
20878 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
20879 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
20880 if (isLegalAddressingMode(AM, Ty))
20881 // Scale represents reg2 * scale, thus account for 1
20882 // as soon as we use a second register.
20883 return AM.Scale != 0;