1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86InstrBuilder.h"
19 #include "X86MachineFunctionInfo.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/StringSwitch.h"
26 #include "llvm/ADT/VariadicFunction.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineJumpTableInfo.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/IR/CallSite.h"
35 #include "llvm/IR/CallingConv.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/DerivedTypes.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/GlobalAlias.h"
40 #include "llvm/IR/GlobalVariable.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/Intrinsics.h"
43 #include "llvm/MC/MCAsmInfo.h"
44 #include "llvm/MC/MCContext.h"
45 #include "llvm/MC/MCExpr.h"
46 #include "llvm/MC/MCSymbol.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Target/TargetOptions.h"
55 #define DEBUG_TYPE "x86-isel"
57 STATISTIC(NumTailCalls, "Number of tail calls");
59 // Forward declarations.
60 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
63 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
64 SelectionDAG &DAG, SDLoc dl,
65 unsigned vectorWidth) {
66 assert((vectorWidth == 128 || vectorWidth == 256) &&
67 "Unsupported vector width");
68 EVT VT = Vec.getValueType();
69 EVT ElVT = VT.getVectorElementType();
70 unsigned Factor = VT.getSizeInBits()/vectorWidth;
71 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
72 VT.getVectorNumElements()/Factor);
74 // Extract from UNDEF is UNDEF.
75 if (Vec.getOpcode() == ISD::UNDEF)
76 return DAG.getUNDEF(ResultVT);
78 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
79 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
81 // This is the index of the first element of the vectorWidth-bit chunk
83 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
86 // If the input is a buildvector just emit a smaller one.
87 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
88 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
89 makeArrayRef(Vec->op_begin()+NormalizedIdxVal,
92 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
93 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
99 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
100 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
101 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
102 /// instructions or a simple subregister reference. Idx is an index in the
103 /// 128 bits we want. It need not be aligned to a 128-bit bounday. That makes
104 /// lowering EXTRACT_VECTOR_ELT operations easier.
105 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
106 SelectionDAG &DAG, SDLoc dl) {
107 assert((Vec.getValueType().is256BitVector() ||
108 Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
109 return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
112 /// Generate a DAG to grab 256-bits from a 512-bit vector.
113 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
114 SelectionDAG &DAG, SDLoc dl) {
115 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
116 return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
119 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
120 unsigned IdxVal, SelectionDAG &DAG,
121 SDLoc dl, unsigned vectorWidth) {
122 assert((vectorWidth == 128 || vectorWidth == 256) &&
123 "Unsupported vector width");
124 // Inserting UNDEF is Result
125 if (Vec.getOpcode() == ISD::UNDEF)
127 EVT VT = Vec.getValueType();
128 EVT ElVT = VT.getVectorElementType();
129 EVT ResultVT = Result.getValueType();
131 // Insert the relevant vectorWidth bits.
132 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
134 // This is the index of the first element of the vectorWidth-bit chunk
136 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
139 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
140 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
143 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
144 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
145 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
146 /// simple superregister reference. Idx is an index in the 128 bits
147 /// we want. It need not be aligned to a 128-bit bounday. That makes
148 /// lowering INSERT_VECTOR_ELT operations easier.
149 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
150 unsigned IdxVal, SelectionDAG &DAG,
152 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
153 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
156 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
157 unsigned IdxVal, SelectionDAG &DAG,
159 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
160 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
163 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
164 /// instructions. This is used because creating CONCAT_VECTOR nodes of
165 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
166 /// large BUILD_VECTORS.
167 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
168 unsigned NumElems, SelectionDAG &DAG,
170 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
171 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
174 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
175 unsigned NumElems, SelectionDAG &DAG,
177 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
178 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
181 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
182 const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
183 bool is64Bit = Subtarget->is64Bit();
185 if (Subtarget->isTargetMacho()) {
187 return new X86_64MachoTargetObjectFile();
188 return new TargetLoweringObjectFileMachO();
191 if (Subtarget->isTargetLinux())
192 return new X86LinuxTargetObjectFile();
193 if (Subtarget->isTargetELF())
194 return new TargetLoweringObjectFileELF();
195 if (Subtarget->isTargetKnownWindowsMSVC())
196 return new X86WindowsTargetObjectFile();
197 if (Subtarget->isTargetCOFF())
198 return new TargetLoweringObjectFileCOFF();
199 llvm_unreachable("unknown subtarget type");
202 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
203 : TargetLowering(TM, createTLOF(TM)) {
204 Subtarget = &TM.getSubtarget<X86Subtarget>();
205 X86ScalarSSEf64 = Subtarget->hasSSE2();
206 X86ScalarSSEf32 = Subtarget->hasSSE1();
207 TD = getDataLayout();
209 resetOperationActions();
212 void X86TargetLowering::resetOperationActions() {
213 const TargetMachine &TM = getTargetMachine();
214 static bool FirstTimeThrough = true;
216 // If none of the target options have changed, then we don't need to reset the
217 // operation actions.
218 if (!FirstTimeThrough && TO == TM.Options) return;
220 if (!FirstTimeThrough) {
221 // Reinitialize the actions.
223 FirstTimeThrough = false;
228 // Set up the TargetLowering object.
229 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
231 // X86 is weird, it always uses i8 for shift amounts and setcc results.
232 setBooleanContents(ZeroOrOneBooleanContent);
233 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
234 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
236 // For 64-bit since we have so many registers use the ILP scheduler, for
237 // 32-bit code use the register pressure specific scheduling.
238 // For Atom, always use ILP scheduling.
239 if (Subtarget->isAtom())
240 setSchedulingPreference(Sched::ILP);
241 else if (Subtarget->is64Bit())
242 setSchedulingPreference(Sched::ILP);
244 setSchedulingPreference(Sched::RegPressure);
245 const X86RegisterInfo *RegInfo =
246 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
247 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
249 // Bypass expensive divides on Atom when compiling with O2
250 if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
251 addBypassSlowDiv(32, 8);
252 if (Subtarget->is64Bit())
253 addBypassSlowDiv(64, 16);
256 if (Subtarget->isTargetKnownWindowsMSVC()) {
257 // Setup Windows compiler runtime calls.
258 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
259 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
260 setLibcallName(RTLIB::SREM_I64, "_allrem");
261 setLibcallName(RTLIB::UREM_I64, "_aullrem");
262 setLibcallName(RTLIB::MUL_I64, "_allmul");
263 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
264 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
265 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
266 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
267 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
269 // The _ftol2 runtime function has an unusual calling conv, which
270 // is modeled by a special pseudo-instruction.
271 setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
272 setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
273 setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
274 setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
277 if (Subtarget->isTargetDarwin()) {
278 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
279 setUseUnderscoreSetJmp(false);
280 setUseUnderscoreLongJmp(false);
281 } else if (Subtarget->isTargetWindowsGNU()) {
282 // MS runtime is weird: it exports _setjmp, but longjmp!
283 setUseUnderscoreSetJmp(true);
284 setUseUnderscoreLongJmp(false);
286 setUseUnderscoreSetJmp(true);
287 setUseUnderscoreLongJmp(true);
290 // Set up the register classes.
291 addRegisterClass(MVT::i8, &X86::GR8RegClass);
292 addRegisterClass(MVT::i16, &X86::GR16RegClass);
293 addRegisterClass(MVT::i32, &X86::GR32RegClass);
294 if (Subtarget->is64Bit())
295 addRegisterClass(MVT::i64, &X86::GR64RegClass);
297 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
299 // We don't accept any truncstore of integer registers.
300 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
301 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
302 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
303 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
304 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
305 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
307 // SETOEQ and SETUNE require checking two conditions.
308 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
309 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
310 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
311 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
312 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
313 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
315 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
317 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
318 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
319 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
321 if (Subtarget->is64Bit()) {
322 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
323 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
324 } else if (!TM.Options.UseSoftFloat) {
325 // We have an algorithm for SSE2->double, and we turn this into a
326 // 64-bit FILD followed by conditional FADD for other targets.
327 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
328 // We have an algorithm for SSE2, and we turn this into a 64-bit
329 // FILD for other targets.
330 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
333 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
335 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
336 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
338 if (!TM.Options.UseSoftFloat) {
339 // SSE has no i16 to fp conversion, only i32
340 if (X86ScalarSSEf32) {
341 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
342 // f32 and f64 cases are Legal, f80 case is not
343 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
345 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
346 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
349 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
350 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
353 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
354 // are Legal, f80 is custom lowered.
355 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
356 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
358 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
360 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
361 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
363 if (X86ScalarSSEf32) {
364 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
365 // f32 and f64 cases are Legal, f80 case is not
366 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
368 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
369 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
372 // Handle FP_TO_UINT by promoting the destination to a larger signed
374 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
375 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
376 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
378 if (Subtarget->is64Bit()) {
379 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
380 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
381 } else if (!TM.Options.UseSoftFloat) {
382 // Since AVX is a superset of SSE3, only check for SSE here.
383 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
384 // Expand FP_TO_UINT into a select.
385 // FIXME: We would like to use a Custom expander here eventually to do
386 // the optimal thing for SSE vs. the default expansion in the legalizer.
387 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
389 // With SSE3 we can use fisttpll to convert to a signed i64; without
390 // SSE, we're stuck with a fistpll.
391 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
394 if (isTargetFTOL()) {
395 // Use the _ftol2 runtime function, which has a pseudo-instruction
396 // to handle its weird calling convention.
397 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
400 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
401 if (!X86ScalarSSEf64) {
402 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
403 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
404 if (Subtarget->is64Bit()) {
405 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
406 // Without SSE, i64->f64 goes through memory.
407 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
411 // Scalar integer divide and remainder are lowered to use operations that
412 // produce two results, to match the available instructions. This exposes
413 // the two-result form to trivial CSE, which is able to combine x/y and x%y
414 // into a single instruction.
416 // Scalar integer multiply-high is also lowered to use two-result
417 // operations, to match the available instructions. However, plain multiply
418 // (low) operations are left as Legal, as there are single-result
419 // instructions for this in x86. Using the two-result multiply instructions
420 // when both high and low results are needed must be arranged by dagcombine.
421 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
423 setOperationAction(ISD::MULHS, VT, Expand);
424 setOperationAction(ISD::MULHU, VT, Expand);
425 setOperationAction(ISD::SDIV, VT, Expand);
426 setOperationAction(ISD::UDIV, VT, Expand);
427 setOperationAction(ISD::SREM, VT, Expand);
428 setOperationAction(ISD::UREM, VT, Expand);
430 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
431 setOperationAction(ISD::ADDC, VT, Custom);
432 setOperationAction(ISD::ADDE, VT, Custom);
433 setOperationAction(ISD::SUBC, VT, Custom);
434 setOperationAction(ISD::SUBE, VT, Custom);
437 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
438 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
439 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
440 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
441 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
442 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
443 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
444 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
445 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
446 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
447 if (Subtarget->is64Bit())
448 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
449 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
450 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
451 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
452 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
453 setOperationAction(ISD::FREM , MVT::f32 , Expand);
454 setOperationAction(ISD::FREM , MVT::f64 , Expand);
455 setOperationAction(ISD::FREM , MVT::f80 , Expand);
456 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
458 // Promote the i8 variants and force them on up to i32 which has a shorter
460 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
461 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
462 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
463 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
464 if (Subtarget->hasBMI()) {
465 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
466 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
467 if (Subtarget->is64Bit())
468 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
470 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
471 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
472 if (Subtarget->is64Bit())
473 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
476 if (Subtarget->hasLZCNT()) {
477 // When promoting the i8 variants, force them to i32 for a shorter
479 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
480 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
481 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
482 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
483 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
484 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
485 if (Subtarget->is64Bit())
486 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
488 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
489 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
490 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
491 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
492 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
493 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
494 if (Subtarget->is64Bit()) {
495 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
496 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
500 if (Subtarget->hasPOPCNT()) {
501 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
503 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
504 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
505 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
506 if (Subtarget->is64Bit())
507 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
510 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
512 if (!Subtarget->hasMOVBE())
513 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
515 // These should be promoted to a larger select which is supported.
516 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
517 // X86 wants to expand cmov itself.
518 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
519 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
520 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
521 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
522 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
523 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
524 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
525 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
526 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
527 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
528 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
529 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
530 if (Subtarget->is64Bit()) {
531 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
532 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
534 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
535 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
536 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
537 // support continuation, user-level threading, and etc.. As a result, no
538 // other SjLj exception interfaces are implemented and please don't build
539 // your own exception handling based on them.
540 // LLVM/Clang supports zero-cost DWARF exception handling.
541 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
542 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
545 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
546 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
547 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
548 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
549 if (Subtarget->is64Bit())
550 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
551 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
552 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
553 if (Subtarget->is64Bit()) {
554 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
555 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
556 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
557 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
558 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
560 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
561 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
562 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
563 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
564 if (Subtarget->is64Bit()) {
565 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
566 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
567 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
570 if (Subtarget->hasSSE1())
571 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
573 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
575 // Expand certain atomics
576 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
578 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
579 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
580 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
583 if (!Subtarget->is64Bit()) {
584 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
585 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
586 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
587 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
588 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
589 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
590 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
591 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
592 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
593 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
594 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
595 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
598 if (Subtarget->hasCmpxchg16b()) {
599 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
602 // FIXME - use subtarget debug flags
603 if (!Subtarget->isTargetDarwin() &&
604 !Subtarget->isTargetELF() &&
605 !Subtarget->isTargetCygMing()) {
606 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
609 if (Subtarget->is64Bit()) {
610 setExceptionPointerRegister(X86::RAX);
611 setExceptionSelectorRegister(X86::RDX);
613 setExceptionPointerRegister(X86::EAX);
614 setExceptionSelectorRegister(X86::EDX);
616 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
617 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
619 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
620 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
622 setOperationAction(ISD::TRAP, MVT::Other, Legal);
623 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
625 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
626 setOperationAction(ISD::VASTART , MVT::Other, Custom);
627 setOperationAction(ISD::VAEND , MVT::Other, Expand);
628 if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
629 // TargetInfo::X86_64ABIBuiltinVaList
630 setOperationAction(ISD::VAARG , MVT::Other, Custom);
631 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
633 // TargetInfo::CharPtrBuiltinVaList
634 setOperationAction(ISD::VAARG , MVT::Other, Expand);
635 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
638 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
639 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
641 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
642 MVT::i64 : MVT::i32, Custom);
644 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
645 // f32 and f64 use SSE.
646 // Set up the FP register classes.
647 addRegisterClass(MVT::f32, &X86::FR32RegClass);
648 addRegisterClass(MVT::f64, &X86::FR64RegClass);
650 // Use ANDPD to simulate FABS.
651 setOperationAction(ISD::FABS , MVT::f64, Custom);
652 setOperationAction(ISD::FABS , MVT::f32, Custom);
654 // Use XORP to simulate FNEG.
655 setOperationAction(ISD::FNEG , MVT::f64, Custom);
656 setOperationAction(ISD::FNEG , MVT::f32, Custom);
658 // Use ANDPD and ORPD to simulate FCOPYSIGN.
659 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
660 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
662 // Lower this to FGETSIGNx86 plus an AND.
663 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
664 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
666 // We don't support sin/cos/fmod
667 setOperationAction(ISD::FSIN , MVT::f64, Expand);
668 setOperationAction(ISD::FCOS , MVT::f64, Expand);
669 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
670 setOperationAction(ISD::FSIN , MVT::f32, Expand);
671 setOperationAction(ISD::FCOS , MVT::f32, Expand);
672 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
674 // Expand FP immediates into loads from the stack, except for the special
676 addLegalFPImmediate(APFloat(+0.0)); // xorpd
677 addLegalFPImmediate(APFloat(+0.0f)); // xorps
678 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
679 // Use SSE for f32, x87 for f64.
680 // Set up the FP register classes.
681 addRegisterClass(MVT::f32, &X86::FR32RegClass);
682 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
684 // Use ANDPS to simulate FABS.
685 setOperationAction(ISD::FABS , MVT::f32, Custom);
687 // Use XORP to simulate FNEG.
688 setOperationAction(ISD::FNEG , MVT::f32, Custom);
690 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
692 // Use ANDPS and ORPS to simulate FCOPYSIGN.
693 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
694 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
696 // We don't support sin/cos/fmod
697 setOperationAction(ISD::FSIN , MVT::f32, Expand);
698 setOperationAction(ISD::FCOS , MVT::f32, Expand);
699 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
701 // Special cases we handle for FP constants.
702 addLegalFPImmediate(APFloat(+0.0f)); // xorps
703 addLegalFPImmediate(APFloat(+0.0)); // FLD0
704 addLegalFPImmediate(APFloat(+1.0)); // FLD1
705 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
706 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
708 if (!TM.Options.UnsafeFPMath) {
709 setOperationAction(ISD::FSIN , MVT::f64, Expand);
710 setOperationAction(ISD::FCOS , MVT::f64, Expand);
711 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
713 } else if (!TM.Options.UseSoftFloat) {
714 // f32 and f64 in x87.
715 // Set up the FP register classes.
716 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
717 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
719 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
720 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
721 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
722 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
724 if (!TM.Options.UnsafeFPMath) {
725 setOperationAction(ISD::FSIN , MVT::f64, Expand);
726 setOperationAction(ISD::FSIN , MVT::f32, Expand);
727 setOperationAction(ISD::FCOS , MVT::f64, Expand);
728 setOperationAction(ISD::FCOS , MVT::f32, Expand);
729 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
730 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
732 addLegalFPImmediate(APFloat(+0.0)); // FLD0
733 addLegalFPImmediate(APFloat(+1.0)); // FLD1
734 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
735 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
736 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
737 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
738 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
739 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
742 // We don't support FMA.
743 setOperationAction(ISD::FMA, MVT::f64, Expand);
744 setOperationAction(ISD::FMA, MVT::f32, Expand);
746 // Long double always uses X87.
747 if (!TM.Options.UseSoftFloat) {
748 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
749 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
750 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
752 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
753 addLegalFPImmediate(TmpFlt); // FLD0
755 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
758 APFloat TmpFlt2(+1.0);
759 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
761 addLegalFPImmediate(TmpFlt2); // FLD1
762 TmpFlt2.changeSign();
763 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
766 if (!TM.Options.UnsafeFPMath) {
767 setOperationAction(ISD::FSIN , MVT::f80, Expand);
768 setOperationAction(ISD::FCOS , MVT::f80, Expand);
769 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
772 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
773 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
774 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
775 setOperationAction(ISD::FRINT, MVT::f80, Expand);
776 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
777 setOperationAction(ISD::FMA, MVT::f80, Expand);
780 // Always use a library call for pow.
781 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
782 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
783 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
785 setOperationAction(ISD::FLOG, MVT::f80, Expand);
786 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
787 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
788 setOperationAction(ISD::FEXP, MVT::f80, Expand);
789 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
791 // First set operation action for all vector types to either promote
792 // (for widening) or expand (for scalarization). Then we will selectively
793 // turn on ones that can be effectively codegen'd.
794 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
795 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
796 MVT VT = (MVT::SimpleValueType)i;
797 setOperationAction(ISD::ADD , VT, Expand);
798 setOperationAction(ISD::SUB , VT, Expand);
799 setOperationAction(ISD::FADD, VT, Expand);
800 setOperationAction(ISD::FNEG, VT, Expand);
801 setOperationAction(ISD::FSUB, VT, Expand);
802 setOperationAction(ISD::MUL , VT, Expand);
803 setOperationAction(ISD::FMUL, VT, Expand);
804 setOperationAction(ISD::SDIV, VT, Expand);
805 setOperationAction(ISD::UDIV, VT, Expand);
806 setOperationAction(ISD::FDIV, VT, Expand);
807 setOperationAction(ISD::SREM, VT, Expand);
808 setOperationAction(ISD::UREM, VT, Expand);
809 setOperationAction(ISD::LOAD, VT, Expand);
810 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
811 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
812 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
813 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
814 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
815 setOperationAction(ISD::FABS, VT, Expand);
816 setOperationAction(ISD::FSIN, VT, Expand);
817 setOperationAction(ISD::FSINCOS, VT, Expand);
818 setOperationAction(ISD::FCOS, VT, Expand);
819 setOperationAction(ISD::FSINCOS, VT, Expand);
820 setOperationAction(ISD::FREM, VT, Expand);
821 setOperationAction(ISD::FMA, VT, Expand);
822 setOperationAction(ISD::FPOWI, VT, Expand);
823 setOperationAction(ISD::FSQRT, VT, Expand);
824 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
825 setOperationAction(ISD::FFLOOR, VT, Expand);
826 setOperationAction(ISD::FCEIL, VT, Expand);
827 setOperationAction(ISD::FTRUNC, VT, Expand);
828 setOperationAction(ISD::FRINT, VT, Expand);
829 setOperationAction(ISD::FNEARBYINT, VT, Expand);
830 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
831 setOperationAction(ISD::MULHS, VT, Expand);
832 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
833 setOperationAction(ISD::MULHU, VT, Expand);
834 setOperationAction(ISD::SDIVREM, VT, Expand);
835 setOperationAction(ISD::UDIVREM, VT, Expand);
836 setOperationAction(ISD::FPOW, VT, Expand);
837 setOperationAction(ISD::CTPOP, VT, Expand);
838 setOperationAction(ISD::CTTZ, VT, Expand);
839 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
840 setOperationAction(ISD::CTLZ, VT, Expand);
841 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
842 setOperationAction(ISD::SHL, VT, Expand);
843 setOperationAction(ISD::SRA, VT, Expand);
844 setOperationAction(ISD::SRL, VT, Expand);
845 setOperationAction(ISD::ROTL, VT, Expand);
846 setOperationAction(ISD::ROTR, VT, Expand);
847 setOperationAction(ISD::BSWAP, VT, Expand);
848 setOperationAction(ISD::SETCC, VT, Expand);
849 setOperationAction(ISD::FLOG, VT, Expand);
850 setOperationAction(ISD::FLOG2, VT, Expand);
851 setOperationAction(ISD::FLOG10, VT, Expand);
852 setOperationAction(ISD::FEXP, VT, Expand);
853 setOperationAction(ISD::FEXP2, VT, Expand);
854 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
855 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
856 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
857 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
858 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
859 setOperationAction(ISD::TRUNCATE, VT, Expand);
860 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
861 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
862 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
863 setOperationAction(ISD::VSELECT, VT, Expand);
864 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
865 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
866 setTruncStoreAction(VT,
867 (MVT::SimpleValueType)InnerVT, Expand);
868 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
869 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
870 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
873 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
874 // with -msoft-float, disable use of MMX as well.
875 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
876 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
877 // No operations on x86mmx supported, everything uses intrinsics.
880 // MMX-sized vectors (other than x86mmx) are expected to be expanded
881 // into smaller operations.
882 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
883 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
884 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
885 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
886 setOperationAction(ISD::AND, MVT::v8i8, Expand);
887 setOperationAction(ISD::AND, MVT::v4i16, Expand);
888 setOperationAction(ISD::AND, MVT::v2i32, Expand);
889 setOperationAction(ISD::AND, MVT::v1i64, Expand);
890 setOperationAction(ISD::OR, MVT::v8i8, Expand);
891 setOperationAction(ISD::OR, MVT::v4i16, Expand);
892 setOperationAction(ISD::OR, MVT::v2i32, Expand);
893 setOperationAction(ISD::OR, MVT::v1i64, Expand);
894 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
895 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
896 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
897 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
898 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
899 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
900 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
901 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
902 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
903 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
904 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
905 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
906 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
907 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
908 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
909 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
910 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
912 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
913 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
915 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
916 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
917 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
918 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
919 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
920 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
921 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
922 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
923 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
924 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
925 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
926 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
929 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
930 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
932 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
933 // registers cannot be used even for integer operations.
934 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
935 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
936 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
937 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
939 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
940 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
941 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
942 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
943 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
944 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
945 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
946 setOperationAction(ISD::SMUL_LOHI, MVT::v4i32, Custom);
947 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
948 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
949 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
950 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
951 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
952 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
953 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
954 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
955 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
956 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
957 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
958 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
959 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
960 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
962 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
963 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
964 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
965 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
967 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
968 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
969 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
970 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
971 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
973 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
974 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
975 MVT VT = (MVT::SimpleValueType)i;
976 // Do not attempt to custom lower non-power-of-2 vectors
977 if (!isPowerOf2_32(VT.getVectorNumElements()))
979 // Do not attempt to custom lower non-128-bit vectors
980 if (!VT.is128BitVector())
982 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
983 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
984 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
987 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
988 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
989 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
990 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
991 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
992 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
994 if (Subtarget->is64Bit()) {
995 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
996 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
999 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1000 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1001 MVT VT = (MVT::SimpleValueType)i;
1003 // Do not attempt to promote non-128-bit vectors
1004 if (!VT.is128BitVector())
1007 setOperationAction(ISD::AND, VT, Promote);
1008 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
1009 setOperationAction(ISD::OR, VT, Promote);
1010 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
1011 setOperationAction(ISD::XOR, VT, Promote);
1012 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
1013 setOperationAction(ISD::LOAD, VT, Promote);
1014 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
1015 setOperationAction(ISD::SELECT, VT, Promote);
1016 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1019 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1021 // Custom lower v2i64 and v2f64 selects.
1022 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
1023 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
1024 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
1025 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
1027 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1028 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1030 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1031 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1032 // As there is no 64-bit GPR available, we need build a special custom
1033 // sequence to convert from v2i32 to v2f32.
1034 if (!Subtarget->is64Bit())
1035 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
1037 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1038 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
1040 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
1042 setOperationAction(ISD::BITCAST, MVT::v2i32, Custom);
1045 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1046 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1047 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1048 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1049 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1050 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1051 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1052 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1053 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1054 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1055 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1057 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1058 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
1059 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1060 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
1061 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
1062 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
1063 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
1064 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
1065 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
1066 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
1068 // FIXME: Do we need to handle scalar-to-vector here?
1069 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1071 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
1072 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal);
1073 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
1074 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
1075 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
1077 // i8 and i16 vectors are custom , because the source register and source
1078 // source memory operand types are not the same width. f32 vectors are
1079 // custom since the immediate controlling the insert encodes additional
1081 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1082 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1083 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1084 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1086 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1087 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1088 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1089 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1091 // FIXME: these should be Legal but thats only for the case where
1092 // the index is constant. For now custom expand to deal with that.
1093 if (Subtarget->is64Bit()) {
1094 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1095 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1099 if (Subtarget->hasSSE2()) {
1100 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1101 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1103 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1104 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1106 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1107 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1109 // In the customized shift lowering, the legal cases in AVX2 will be
1111 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1112 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1114 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1115 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1117 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1120 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1121 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1122 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1123 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1124 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1125 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1126 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1128 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1129 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1130 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1132 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1133 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1134 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1135 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1136 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1137 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1138 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1139 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1140 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1141 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1142 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1143 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1145 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1146 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1147 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1148 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1149 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1150 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1151 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1152 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1153 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1154 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1155 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1156 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1158 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1159 // even though v8i16 is a legal type.
1160 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1161 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1162 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1164 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1165 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1166 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1168 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1169 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1171 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1173 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1174 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1176 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1177 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1179 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1180 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1182 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1183 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1184 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1185 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1187 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1188 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1189 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1191 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1192 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal);
1193 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal);
1194 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal);
1196 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1197 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1198 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1199 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1200 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1201 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1202 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1203 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1204 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1205 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1206 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1207 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1209 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1210 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1211 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1212 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1213 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1214 setOperationAction(ISD::FMA, MVT::f32, Legal);
1215 setOperationAction(ISD::FMA, MVT::f64, Legal);
1218 if (Subtarget->hasInt256()) {
1219 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1220 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1221 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1222 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1224 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1225 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1226 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1227 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1229 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1230 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1231 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1232 // Don't lower v32i8 because there is no 128-bit byte mul
1234 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1235 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1236 setOperationAction(ISD::MULHU, MVT::v16i16, Legal);
1237 setOperationAction(ISD::MULHS, MVT::v16i16, Legal);
1239 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1241 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1242 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1243 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1244 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1246 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1247 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1248 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1249 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1251 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1252 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1253 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1254 // Don't lower v32i8 because there is no 128-bit byte mul
1257 // In the customized shift lowering, the legal cases in AVX2 will be
1259 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1260 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1262 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1263 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1265 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1267 // Custom lower several nodes for 256-bit types.
1268 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1269 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1270 MVT VT = (MVT::SimpleValueType)i;
1272 // Extract subvector is special because the value type
1273 // (result) is 128-bit but the source is 256-bit wide.
1274 if (VT.is128BitVector())
1275 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1277 // Do not attempt to custom lower other non-256-bit vectors
1278 if (!VT.is256BitVector())
1281 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1282 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1283 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1284 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1285 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1286 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1287 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1290 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1291 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1292 MVT VT = (MVT::SimpleValueType)i;
1294 // Do not attempt to promote non-256-bit vectors
1295 if (!VT.is256BitVector())
1298 setOperationAction(ISD::AND, VT, Promote);
1299 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1300 setOperationAction(ISD::OR, VT, Promote);
1301 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1302 setOperationAction(ISD::XOR, VT, Promote);
1303 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1304 setOperationAction(ISD::LOAD, VT, Promote);
1305 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1306 setOperationAction(ISD::SELECT, VT, Promote);
1307 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1311 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1312 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1313 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1314 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1315 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1317 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1318 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1319 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1321 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1322 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1323 setOperationAction(ISD::XOR, MVT::i1, Legal);
1324 setOperationAction(ISD::OR, MVT::i1, Legal);
1325 setOperationAction(ISD::AND, MVT::i1, Legal);
1326 setLoadExtAction(ISD::EXTLOAD, MVT::v8f32, Legal);
1327 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1328 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1329 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1330 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1331 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1333 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1334 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1335 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1336 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1337 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1338 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1340 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1341 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1342 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1343 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1344 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1345 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1346 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1347 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1349 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1350 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1351 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1352 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1353 if (Subtarget->is64Bit()) {
1354 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1355 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1356 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1357 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1359 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1360 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1361 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1362 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1363 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1364 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1365 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1366 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1367 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1368 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1370 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1371 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1372 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1373 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1374 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1375 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1376 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1377 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1378 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1379 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1380 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1381 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1382 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1384 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1385 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1386 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1387 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1388 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1389 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1391 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1392 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1394 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1396 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1397 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1398 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1399 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1400 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1401 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1402 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1403 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1404 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1406 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1407 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1409 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1410 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1412 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1414 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1415 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1417 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1418 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1420 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1421 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1423 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1424 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1425 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1426 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1427 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1428 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1430 // Custom lower several nodes.
1431 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1432 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1433 MVT VT = (MVT::SimpleValueType)i;
1435 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1436 // Extract subvector is special because the value type
1437 // (result) is 256/128-bit but the source is 512-bit wide.
1438 if (VT.is128BitVector() || VT.is256BitVector())
1439 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1441 if (VT.getVectorElementType() == MVT::i1)
1442 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1444 // Do not attempt to custom lower other non-512-bit vectors
1445 if (!VT.is512BitVector())
1448 if ( EltSize >= 32) {
1449 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1450 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1451 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1452 setOperationAction(ISD::VSELECT, VT, Legal);
1453 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1454 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1455 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1458 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1459 MVT VT = (MVT::SimpleValueType)i;
1461 // Do not attempt to promote non-256-bit vectors
1462 if (!VT.is512BitVector())
1465 setOperationAction(ISD::SELECT, VT, Promote);
1466 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1470 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1471 // of this type with custom code.
1472 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1473 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1474 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1478 // We want to custom lower some of our intrinsics.
1479 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1480 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1481 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1482 if (!Subtarget->is64Bit())
1483 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1485 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1486 // handle type legalization for these operations here.
1488 // FIXME: We really should do custom legalization for addition and
1489 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1490 // than generic legalization for 64-bit multiplication-with-overflow, though.
1491 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1492 // Add/Sub/Mul with overflow operations are custom lowered.
1494 setOperationAction(ISD::SADDO, VT, Custom);
1495 setOperationAction(ISD::UADDO, VT, Custom);
1496 setOperationAction(ISD::SSUBO, VT, Custom);
1497 setOperationAction(ISD::USUBO, VT, Custom);
1498 setOperationAction(ISD::SMULO, VT, Custom);
1499 setOperationAction(ISD::UMULO, VT, Custom);
1502 // There are no 8-bit 3-address imul/mul instructions
1503 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1504 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1506 if (!Subtarget->is64Bit()) {
1507 // These libcalls are not available in 32-bit.
1508 setLibcallName(RTLIB::SHL_I128, nullptr);
1509 setLibcallName(RTLIB::SRL_I128, nullptr);
1510 setLibcallName(RTLIB::SRA_I128, nullptr);
1513 // Combine sin / cos into one node or libcall if possible.
1514 if (Subtarget->hasSinCos()) {
1515 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1516 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1517 if (Subtarget->isTargetDarwin()) {
1518 // For MacOSX, we don't want to the normal expansion of a libcall to
1519 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1521 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1522 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1526 if (Subtarget->isTargetWin64()) {
1527 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1528 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1529 setOperationAction(ISD::SREM, MVT::i128, Custom);
1530 setOperationAction(ISD::UREM, MVT::i128, Custom);
1531 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1532 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1535 // We have target-specific dag combine patterns for the following nodes:
1536 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1537 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1538 setTargetDAGCombine(ISD::VSELECT);
1539 setTargetDAGCombine(ISD::SELECT);
1540 setTargetDAGCombine(ISD::SHL);
1541 setTargetDAGCombine(ISD::SRA);
1542 setTargetDAGCombine(ISD::SRL);
1543 setTargetDAGCombine(ISD::OR);
1544 setTargetDAGCombine(ISD::AND);
1545 setTargetDAGCombine(ISD::ADD);
1546 setTargetDAGCombine(ISD::FADD);
1547 setTargetDAGCombine(ISD::FSUB);
1548 setTargetDAGCombine(ISD::FMA);
1549 setTargetDAGCombine(ISD::SUB);
1550 setTargetDAGCombine(ISD::LOAD);
1551 setTargetDAGCombine(ISD::STORE);
1552 setTargetDAGCombine(ISD::ZERO_EXTEND);
1553 setTargetDAGCombine(ISD::ANY_EXTEND);
1554 setTargetDAGCombine(ISD::SIGN_EXTEND);
1555 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1556 setTargetDAGCombine(ISD::TRUNCATE);
1557 setTargetDAGCombine(ISD::SINT_TO_FP);
1558 setTargetDAGCombine(ISD::SETCC);
1559 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1560 if (Subtarget->is64Bit())
1561 setTargetDAGCombine(ISD::MUL);
1562 setTargetDAGCombine(ISD::XOR);
1564 computeRegisterProperties();
1566 // On Darwin, -Os means optimize for size without hurting performance,
1567 // do not reduce the limit.
1568 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1569 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1570 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1571 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1572 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1573 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1574 setPrefLoopAlignment(4); // 2^4 bytes.
1576 // Predictable cmov don't hurt on atom because it's in-order.
1577 PredictableSelectIsExpensive = !Subtarget->isAtom();
1579 setPrefFunctionAlignment(4); // 2^4 bytes.
1582 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1584 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1586 if (Subtarget->hasAVX512())
1587 switch(VT.getVectorNumElements()) {
1588 case 8: return MVT::v8i1;
1589 case 16: return MVT::v16i1;
1592 return VT.changeVectorElementTypeToInteger();
1595 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1596 /// the desired ByVal argument alignment.
1597 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1600 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1601 if (VTy->getBitWidth() == 128)
1603 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1604 unsigned EltAlign = 0;
1605 getMaxByValAlign(ATy->getElementType(), EltAlign);
1606 if (EltAlign > MaxAlign)
1607 MaxAlign = EltAlign;
1608 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1609 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1610 unsigned EltAlign = 0;
1611 getMaxByValAlign(STy->getElementType(i), EltAlign);
1612 if (EltAlign > MaxAlign)
1613 MaxAlign = EltAlign;
1620 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1621 /// function arguments in the caller parameter area. For X86, aggregates
1622 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1623 /// are at 4-byte boundaries.
1624 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1625 if (Subtarget->is64Bit()) {
1626 // Max of 8 and alignment of type.
1627 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1634 if (Subtarget->hasSSE1())
1635 getMaxByValAlign(Ty, Align);
1639 /// getOptimalMemOpType - Returns the target specific optimal type for load
1640 /// and store operations as a result of memset, memcpy, and memmove
1641 /// lowering. If DstAlign is zero that means it's safe to destination
1642 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1643 /// means there isn't a need to check it against alignment requirement,
1644 /// probably because the source does not need to be loaded. If 'IsMemset' is
1645 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1646 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1647 /// source is constant so it does not need to be loaded.
1648 /// It returns EVT::Other if the type should be determined using generic
1649 /// target-independent logic.
1651 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1652 unsigned DstAlign, unsigned SrcAlign,
1653 bool IsMemset, bool ZeroMemset,
1655 MachineFunction &MF) const {
1656 const Function *F = MF.getFunction();
1657 if ((!IsMemset || ZeroMemset) &&
1658 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1659 Attribute::NoImplicitFloat)) {
1661 (Subtarget->isUnalignedMemAccessFast() ||
1662 ((DstAlign == 0 || DstAlign >= 16) &&
1663 (SrcAlign == 0 || SrcAlign >= 16)))) {
1665 if (Subtarget->hasInt256())
1667 if (Subtarget->hasFp256())
1670 if (Subtarget->hasSSE2())
1672 if (Subtarget->hasSSE1())
1674 } else if (!MemcpyStrSrc && Size >= 8 &&
1675 !Subtarget->is64Bit() &&
1676 Subtarget->hasSSE2()) {
1677 // Do not use f64 to lower memcpy if source is string constant. It's
1678 // better to use i32 to avoid the loads.
1682 if (Subtarget->is64Bit() && Size >= 8)
1687 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1689 return X86ScalarSSEf32;
1690 else if (VT == MVT::f64)
1691 return X86ScalarSSEf64;
1696 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1700 *Fast = Subtarget->isUnalignedMemAccessFast();
1704 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1705 /// current function. The returned value is a member of the
1706 /// MachineJumpTableInfo::JTEntryKind enum.
1707 unsigned X86TargetLowering::getJumpTableEncoding() const {
1708 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1710 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1711 Subtarget->isPICStyleGOT())
1712 return MachineJumpTableInfo::EK_Custom32;
1714 // Otherwise, use the normal jump table encoding heuristics.
1715 return TargetLowering::getJumpTableEncoding();
1719 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1720 const MachineBasicBlock *MBB,
1721 unsigned uid,MCContext &Ctx) const{
1722 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1723 Subtarget->isPICStyleGOT());
1724 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1726 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1727 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1730 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1732 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1733 SelectionDAG &DAG) const {
1734 if (!Subtarget->is64Bit())
1735 // This doesn't have SDLoc associated with it, but is not really the
1736 // same as a Register.
1737 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1741 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1742 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1744 const MCExpr *X86TargetLowering::
1745 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1746 MCContext &Ctx) const {
1747 // X86-64 uses RIP relative addressing based on the jump table label.
1748 if (Subtarget->isPICStyleRIPRel())
1749 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1751 // Otherwise, the reference is relative to the PIC base.
1752 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1755 // FIXME: Why this routine is here? Move to RegInfo!
1756 std::pair<const TargetRegisterClass*, uint8_t>
1757 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1758 const TargetRegisterClass *RRC = nullptr;
1760 switch (VT.SimpleTy) {
1762 return TargetLowering::findRepresentativeClass(VT);
1763 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1764 RRC = Subtarget->is64Bit() ?
1765 (const TargetRegisterClass*)&X86::GR64RegClass :
1766 (const TargetRegisterClass*)&X86::GR32RegClass;
1769 RRC = &X86::VR64RegClass;
1771 case MVT::f32: case MVT::f64:
1772 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1773 case MVT::v4f32: case MVT::v2f64:
1774 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1776 RRC = &X86::VR128RegClass;
1779 return std::make_pair(RRC, Cost);
1782 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1783 unsigned &Offset) const {
1784 if (!Subtarget->isTargetLinux())
1787 if (Subtarget->is64Bit()) {
1788 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1790 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1802 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1803 unsigned DestAS) const {
1804 assert(SrcAS != DestAS && "Expected different address spaces!");
1806 return SrcAS < 256 && DestAS < 256;
1809 //===----------------------------------------------------------------------===//
1810 // Return Value Calling Convention Implementation
1811 //===----------------------------------------------------------------------===//
1813 #include "X86GenCallingConv.inc"
1816 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1817 MachineFunction &MF, bool isVarArg,
1818 const SmallVectorImpl<ISD::OutputArg> &Outs,
1819 LLVMContext &Context) const {
1820 SmallVector<CCValAssign, 16> RVLocs;
1821 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1823 return CCInfo.CheckReturn(Outs, RetCC_X86);
1826 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1827 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1832 X86TargetLowering::LowerReturn(SDValue Chain,
1833 CallingConv::ID CallConv, bool isVarArg,
1834 const SmallVectorImpl<ISD::OutputArg> &Outs,
1835 const SmallVectorImpl<SDValue> &OutVals,
1836 SDLoc dl, SelectionDAG &DAG) const {
1837 MachineFunction &MF = DAG.getMachineFunction();
1838 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1840 SmallVector<CCValAssign, 16> RVLocs;
1841 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1842 RVLocs, *DAG.getContext());
1843 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1846 SmallVector<SDValue, 6> RetOps;
1847 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1848 // Operand #1 = Bytes To Pop
1849 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1852 // Copy the result values into the output registers.
1853 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1854 CCValAssign &VA = RVLocs[i];
1855 assert(VA.isRegLoc() && "Can only return in registers!");
1856 SDValue ValToCopy = OutVals[i];
1857 EVT ValVT = ValToCopy.getValueType();
1859 // Promote values to the appropriate types
1860 if (VA.getLocInfo() == CCValAssign::SExt)
1861 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1862 else if (VA.getLocInfo() == CCValAssign::ZExt)
1863 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1864 else if (VA.getLocInfo() == CCValAssign::AExt)
1865 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1866 else if (VA.getLocInfo() == CCValAssign::BCvt)
1867 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1869 assert(VA.getLocInfo() != CCValAssign::FPExt &&
1870 "Unexpected FP-extend for return value.");
1872 // If this is x86-64, and we disabled SSE, we can't return FP values,
1873 // or SSE or MMX vectors.
1874 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1875 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1876 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1877 report_fatal_error("SSE register return with SSE disabled");
1879 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1880 // llvm-gcc has never done it right and no one has noticed, so this
1881 // should be OK for now.
1882 if (ValVT == MVT::f64 &&
1883 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1884 report_fatal_error("SSE2 register return with SSE2 disabled");
1886 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1887 // the RET instruction and handled by the FP Stackifier.
1888 if (VA.getLocReg() == X86::ST0 ||
1889 VA.getLocReg() == X86::ST1) {
1890 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1891 // change the value to the FP stack register class.
1892 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1893 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1894 RetOps.push_back(ValToCopy);
1895 // Don't emit a copytoreg.
1899 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1900 // which is returned in RAX / RDX.
1901 if (Subtarget->is64Bit()) {
1902 if (ValVT == MVT::x86mmx) {
1903 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1904 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1905 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1907 // If we don't have SSE2 available, convert to v4f32 so the generated
1908 // register is legal.
1909 if (!Subtarget->hasSSE2())
1910 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1915 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1916 Flag = Chain.getValue(1);
1917 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1920 // The x86-64 ABIs require that for returning structs by value we copy
1921 // the sret argument into %rax/%eax (depending on ABI) for the return.
1922 // Win32 requires us to put the sret argument to %eax as well.
1923 // We saved the argument into a virtual register in the entry block,
1924 // so now we copy the value out and into %rax/%eax.
1925 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1926 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1927 MachineFunction &MF = DAG.getMachineFunction();
1928 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1929 unsigned Reg = FuncInfo->getSRetReturnReg();
1931 "SRetReturnReg should have been set in LowerFormalArguments().");
1932 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1935 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1936 X86::RAX : X86::EAX;
1937 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1938 Flag = Chain.getValue(1);
1940 // RAX/EAX now acts like a return value.
1941 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1944 RetOps[0] = Chain; // Update chain.
1946 // Add the flag if we have it.
1948 RetOps.push_back(Flag);
1950 return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
1953 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1954 if (N->getNumValues() != 1)
1956 if (!N->hasNUsesOfValue(1, 0))
1959 SDValue TCChain = Chain;
1960 SDNode *Copy = *N->use_begin();
1961 if (Copy->getOpcode() == ISD::CopyToReg) {
1962 // If the copy has a glue operand, we conservatively assume it isn't safe to
1963 // perform a tail call.
1964 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1966 TCChain = Copy->getOperand(0);
1967 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1970 bool HasRet = false;
1971 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1973 if (UI->getOpcode() != X86ISD::RET_FLAG)
1986 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1987 ISD::NodeType ExtendKind) const {
1989 // TODO: Is this also valid on 32-bit?
1990 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1991 ReturnMVT = MVT::i8;
1993 ReturnMVT = MVT::i32;
1995 MVT MinVT = getRegisterType(ReturnMVT);
1996 return VT.bitsLT(MinVT) ? MinVT : VT;
1999 /// LowerCallResult - Lower the result values of a call into the
2000 /// appropriate copies out of appropriate physical registers.
2003 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2004 CallingConv::ID CallConv, bool isVarArg,
2005 const SmallVectorImpl<ISD::InputArg> &Ins,
2006 SDLoc dl, SelectionDAG &DAG,
2007 SmallVectorImpl<SDValue> &InVals) const {
2009 // Assign locations to each value returned by this call.
2010 SmallVector<CCValAssign, 16> RVLocs;
2011 bool Is64Bit = Subtarget->is64Bit();
2012 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2013 getTargetMachine(), RVLocs, *DAG.getContext());
2014 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2016 // Copy all of the result registers out of their specified physreg.
2017 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2018 CCValAssign &VA = RVLocs[i];
2019 EVT CopyVT = VA.getValVT();
2021 // If this is x86-64, and we disabled SSE, we can't return FP values
2022 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2023 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2024 report_fatal_error("SSE register return with SSE disabled");
2029 // If this is a call to a function that returns an fp value on the floating
2030 // point stack, we must guarantee the value is popped from the stack, so
2031 // a CopyFromReg is not good enough - the copy instruction may be eliminated
2032 // if the return value is not used. We use the FpPOP_RETVAL instruction
2034 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2035 // If we prefer to use the value in xmm registers, copy it out as f80 and
2036 // use a truncate to move it from fp stack reg to xmm reg.
2037 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2038 SDValue Ops[] = { Chain, InFlag };
2039 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2040 MVT::Other, MVT::Glue, Ops), 1);
2041 Val = Chain.getValue(0);
2043 // Round the f80 to the right size, which also moves it to the appropriate
2045 if (CopyVT != VA.getValVT())
2046 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2047 // This truncation won't change the value.
2048 DAG.getIntPtrConstant(1));
2050 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2051 CopyVT, InFlag).getValue(1);
2052 Val = Chain.getValue(0);
2054 InFlag = Chain.getValue(2);
2055 InVals.push_back(Val);
2061 //===----------------------------------------------------------------------===//
2062 // C & StdCall & Fast Calling Convention implementation
2063 //===----------------------------------------------------------------------===//
2064 // StdCall calling convention seems to be standard for many Windows' API
2065 // routines and around. It differs from C calling convention just a little:
2066 // callee should clean up the stack, not caller. Symbols should be also
2067 // decorated in some fancy way :) It doesn't support any vector arguments.
2068 // For info on fast calling convention see Fast Calling Convention (tail call)
2069 // implementation LowerX86_32FastCCCallTo.
2071 /// CallIsStructReturn - Determines whether a call uses struct return
2073 enum StructReturnType {
2078 static StructReturnType
2079 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2081 return NotStructReturn;
2083 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2084 if (!Flags.isSRet())
2085 return NotStructReturn;
2086 if (Flags.isInReg())
2087 return RegStructReturn;
2088 return StackStructReturn;
2091 /// ArgsAreStructReturn - Determines whether a function uses struct
2092 /// return semantics.
2093 static StructReturnType
2094 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2096 return NotStructReturn;
2098 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2099 if (!Flags.isSRet())
2100 return NotStructReturn;
2101 if (Flags.isInReg())
2102 return RegStructReturn;
2103 return StackStructReturn;
2106 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2107 /// by "Src" to address "Dst" with size and alignment information specified by
2108 /// the specific parameter attribute. The copy will be passed as a byval
2109 /// function parameter.
2111 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2112 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2114 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2116 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2117 /*isVolatile*/false, /*AlwaysInline=*/true,
2118 MachinePointerInfo(), MachinePointerInfo());
2121 /// IsTailCallConvention - Return true if the calling convention is one that
2122 /// supports tail call optimization.
2123 static bool IsTailCallConvention(CallingConv::ID CC) {
2124 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2125 CC == CallingConv::HiPE);
2128 /// \brief Return true if the calling convention is a C calling convention.
2129 static bool IsCCallConvention(CallingConv::ID CC) {
2130 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2131 CC == CallingConv::X86_64_SysV);
2134 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2135 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2139 CallingConv::ID CalleeCC = CS.getCallingConv();
2140 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2146 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2147 /// a tailcall target by changing its ABI.
2148 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2149 bool GuaranteedTailCallOpt) {
2150 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2154 X86TargetLowering::LowerMemArgument(SDValue Chain,
2155 CallingConv::ID CallConv,
2156 const SmallVectorImpl<ISD::InputArg> &Ins,
2157 SDLoc dl, SelectionDAG &DAG,
2158 const CCValAssign &VA,
2159 MachineFrameInfo *MFI,
2161 // Create the nodes corresponding to a load from this parameter slot.
2162 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2163 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2164 getTargetMachine().Options.GuaranteedTailCallOpt);
2165 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2168 // If value is passed by pointer we have address passed instead of the value
2170 if (VA.getLocInfo() == CCValAssign::Indirect)
2171 ValVT = VA.getLocVT();
2173 ValVT = VA.getValVT();
2175 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2176 // changed with more analysis.
2177 // In case of tail call optimization mark all arguments mutable. Since they
2178 // could be overwritten by lowering of arguments in case of a tail call.
2179 if (Flags.isByVal()) {
2180 unsigned Bytes = Flags.getByValSize();
2181 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2182 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2183 return DAG.getFrameIndex(FI, getPointerTy());
2185 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2186 VA.getLocMemOffset(), isImmutable);
2187 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2188 return DAG.getLoad(ValVT, dl, Chain, FIN,
2189 MachinePointerInfo::getFixedStack(FI),
2190 false, false, false, 0);
2195 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2196 CallingConv::ID CallConv,
2198 const SmallVectorImpl<ISD::InputArg> &Ins,
2201 SmallVectorImpl<SDValue> &InVals)
2203 MachineFunction &MF = DAG.getMachineFunction();
2204 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2206 const Function* Fn = MF.getFunction();
2207 if (Fn->hasExternalLinkage() &&
2208 Subtarget->isTargetCygMing() &&
2209 Fn->getName() == "main")
2210 FuncInfo->setForceFramePointer(true);
2212 MachineFrameInfo *MFI = MF.getFrameInfo();
2213 bool Is64Bit = Subtarget->is64Bit();
2214 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2216 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2217 "Var args not supported with calling convention fastcc, ghc or hipe");
2219 // Assign locations to all of the incoming arguments.
2220 SmallVector<CCValAssign, 16> ArgLocs;
2221 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2222 ArgLocs, *DAG.getContext());
2224 // Allocate shadow area for Win64
2226 CCInfo.AllocateStack(32, 8);
2228 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2230 unsigned LastVal = ~0U;
2232 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2233 CCValAssign &VA = ArgLocs[i];
2234 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2236 assert(VA.getValNo() != LastVal &&
2237 "Don't support value assigned to multiple locs yet");
2239 LastVal = VA.getValNo();
2241 if (VA.isRegLoc()) {
2242 EVT RegVT = VA.getLocVT();
2243 const TargetRegisterClass *RC;
2244 if (RegVT == MVT::i32)
2245 RC = &X86::GR32RegClass;
2246 else if (Is64Bit && RegVT == MVT::i64)
2247 RC = &X86::GR64RegClass;
2248 else if (RegVT == MVT::f32)
2249 RC = &X86::FR32RegClass;
2250 else if (RegVT == MVT::f64)
2251 RC = &X86::FR64RegClass;
2252 else if (RegVT.is512BitVector())
2253 RC = &X86::VR512RegClass;
2254 else if (RegVT.is256BitVector())
2255 RC = &X86::VR256RegClass;
2256 else if (RegVT.is128BitVector())
2257 RC = &X86::VR128RegClass;
2258 else if (RegVT == MVT::x86mmx)
2259 RC = &X86::VR64RegClass;
2260 else if (RegVT == MVT::i1)
2261 RC = &X86::VK1RegClass;
2262 else if (RegVT == MVT::v8i1)
2263 RC = &X86::VK8RegClass;
2264 else if (RegVT == MVT::v16i1)
2265 RC = &X86::VK16RegClass;
2267 llvm_unreachable("Unknown argument type!");
2269 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2270 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2272 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2273 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2275 if (VA.getLocInfo() == CCValAssign::SExt)
2276 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2277 DAG.getValueType(VA.getValVT()));
2278 else if (VA.getLocInfo() == CCValAssign::ZExt)
2279 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2280 DAG.getValueType(VA.getValVT()));
2281 else if (VA.getLocInfo() == CCValAssign::BCvt)
2282 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2284 if (VA.isExtInLoc()) {
2285 // Handle MMX values passed in XMM regs.
2286 if (RegVT.isVector())
2287 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2289 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2292 assert(VA.isMemLoc());
2293 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2296 // If value is passed via pointer - do a load.
2297 if (VA.getLocInfo() == CCValAssign::Indirect)
2298 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2299 MachinePointerInfo(), false, false, false, 0);
2301 InVals.push_back(ArgValue);
2304 // The x86-64 ABIs require that for returning structs by value we copy
2305 // the sret argument into %rax/%eax (depending on ABI) for the return.
2306 // Win32 requires us to put the sret argument to %eax as well.
2307 // Save the argument into a virtual register so that we can access it
2308 // from the return points.
2309 if (MF.getFunction()->hasStructRetAttr() &&
2310 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2311 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2312 unsigned Reg = FuncInfo->getSRetReturnReg();
2314 MVT PtrTy = getPointerTy();
2315 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2316 FuncInfo->setSRetReturnReg(Reg);
2318 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2319 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2322 unsigned StackSize = CCInfo.getNextStackOffset();
2323 // Align stack specially for tail calls.
2324 if (FuncIsMadeTailCallSafe(CallConv,
2325 MF.getTarget().Options.GuaranteedTailCallOpt))
2326 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2328 // If the function takes variable number of arguments, make a frame index for
2329 // the start of the first vararg value... for expansion of llvm.va_start.
2331 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2332 CallConv != CallingConv::X86_ThisCall)) {
2333 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2336 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2338 // FIXME: We should really autogenerate these arrays
2339 static const MCPhysReg GPR64ArgRegsWin64[] = {
2340 X86::RCX, X86::RDX, X86::R8, X86::R9
2342 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2343 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2345 static const MCPhysReg XMMArgRegs64Bit[] = {
2346 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2347 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2349 const MCPhysReg *GPR64ArgRegs;
2350 unsigned NumXMMRegs = 0;
2353 // The XMM registers which might contain var arg parameters are shadowed
2354 // in their paired GPR. So we only need to save the GPR to their home
2356 TotalNumIntRegs = 4;
2357 GPR64ArgRegs = GPR64ArgRegsWin64;
2359 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2360 GPR64ArgRegs = GPR64ArgRegs64Bit;
2362 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2365 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2368 bool NoImplicitFloatOps = Fn->getAttributes().
2369 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2370 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2371 "SSE register cannot be used when SSE is disabled!");
2372 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2373 NoImplicitFloatOps) &&
2374 "SSE register cannot be used when SSE is disabled!");
2375 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2376 !Subtarget->hasSSE1())
2377 // Kernel mode asks for SSE to be disabled, so don't push them
2379 TotalNumXMMRegs = 0;
2382 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2383 // Get to the caller-allocated home save location. Add 8 to account
2384 // for the return address.
2385 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2386 FuncInfo->setRegSaveFrameIndex(
2387 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2388 // Fixup to set vararg frame on shadow area (4 x i64).
2390 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2392 // For X86-64, if there are vararg parameters that are passed via
2393 // registers, then we must store them to their spots on the stack so
2394 // they may be loaded by deferencing the result of va_next.
2395 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2396 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2397 FuncInfo->setRegSaveFrameIndex(
2398 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2402 // Store the integer parameter registers.
2403 SmallVector<SDValue, 8> MemOps;
2404 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2406 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2407 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2408 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2409 DAG.getIntPtrConstant(Offset));
2410 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2411 &X86::GR64RegClass);
2412 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2414 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2415 MachinePointerInfo::getFixedStack(
2416 FuncInfo->getRegSaveFrameIndex(), Offset),
2418 MemOps.push_back(Store);
2422 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2423 // Now store the XMM (fp + vector) parameter registers.
2424 SmallVector<SDValue, 11> SaveXMMOps;
2425 SaveXMMOps.push_back(Chain);
2427 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2428 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2429 SaveXMMOps.push_back(ALVal);
2431 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2432 FuncInfo->getRegSaveFrameIndex()));
2433 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2434 FuncInfo->getVarArgsFPOffset()));
2436 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2437 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2438 &X86::VR128RegClass);
2439 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2440 SaveXMMOps.push_back(Val);
2442 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2443 MVT::Other, SaveXMMOps));
2446 if (!MemOps.empty())
2447 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2451 // Some CCs need callee pop.
2452 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2453 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2454 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2456 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2457 // If this is an sret function, the return should pop the hidden pointer.
2458 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2459 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2460 argsAreStructReturn(Ins) == StackStructReturn)
2461 FuncInfo->setBytesToPopOnReturn(4);
2465 // RegSaveFrameIndex is X86-64 only.
2466 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2467 if (CallConv == CallingConv::X86_FastCall ||
2468 CallConv == CallingConv::X86_ThisCall)
2469 // fastcc functions can't have varargs.
2470 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2473 FuncInfo->setArgumentStackSize(StackSize);
2479 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2480 SDValue StackPtr, SDValue Arg,
2481 SDLoc dl, SelectionDAG &DAG,
2482 const CCValAssign &VA,
2483 ISD::ArgFlagsTy Flags) const {
2484 unsigned LocMemOffset = VA.getLocMemOffset();
2485 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2486 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2487 if (Flags.isByVal())
2488 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2490 return DAG.getStore(Chain, dl, Arg, PtrOff,
2491 MachinePointerInfo::getStack(LocMemOffset),
2495 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2496 /// optimization is performed and it is required.
2498 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2499 SDValue &OutRetAddr, SDValue Chain,
2500 bool IsTailCall, bool Is64Bit,
2501 int FPDiff, SDLoc dl) const {
2502 // Adjust the Return address stack slot.
2503 EVT VT = getPointerTy();
2504 OutRetAddr = getReturnAddressFrameIndex(DAG);
2506 // Load the "old" Return address.
2507 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2508 false, false, false, 0);
2509 return SDValue(OutRetAddr.getNode(), 1);
2512 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2513 /// optimization is performed and it is required (FPDiff!=0).
2514 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2515 SDValue Chain, SDValue RetAddrFrIdx,
2516 EVT PtrVT, unsigned SlotSize,
2517 int FPDiff, SDLoc dl) {
2518 // Store the return address to the appropriate stack slot.
2519 if (!FPDiff) return Chain;
2520 // Calculate the new stack slot for the return address.
2521 int NewReturnAddrFI =
2522 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2524 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2525 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2526 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2532 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2533 SmallVectorImpl<SDValue> &InVals) const {
2534 SelectionDAG &DAG = CLI.DAG;
2536 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2537 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2538 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2539 SDValue Chain = CLI.Chain;
2540 SDValue Callee = CLI.Callee;
2541 CallingConv::ID CallConv = CLI.CallConv;
2542 bool &isTailCall = CLI.IsTailCall;
2543 bool isVarArg = CLI.IsVarArg;
2545 MachineFunction &MF = DAG.getMachineFunction();
2546 bool Is64Bit = Subtarget->is64Bit();
2547 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2548 StructReturnType SR = callIsStructReturn(Outs);
2549 bool IsSibcall = false;
2551 if (MF.getTarget().Options.DisableTailCalls)
2554 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2556 // Force this to be a tail call. The verifier rules are enough to ensure
2557 // that we can lower this successfully without moving the return address
2560 } else if (isTailCall) {
2561 // Check if it's really possible to do a tail call.
2562 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2563 isVarArg, SR != NotStructReturn,
2564 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2565 Outs, OutVals, Ins, DAG);
2567 // Sibcalls are automatically detected tailcalls which do not require
2569 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2576 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2577 "Var args not supported with calling convention fastcc, ghc or hipe");
2579 // Analyze operands of the call, assigning locations to each operand.
2580 SmallVector<CCValAssign, 16> ArgLocs;
2581 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2582 ArgLocs, *DAG.getContext());
2584 // Allocate shadow area for Win64
2586 CCInfo.AllocateStack(32, 8);
2588 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2590 // Get a count of how many bytes are to be pushed on the stack.
2591 unsigned NumBytes = CCInfo.getNextStackOffset();
2593 // This is a sibcall. The memory operands are available in caller's
2594 // own caller's stack.
2596 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2597 IsTailCallConvention(CallConv))
2598 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2601 if (isTailCall && !IsSibcall && !IsMustTail) {
2602 // Lower arguments at fp - stackoffset + fpdiff.
2603 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2604 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2606 FPDiff = NumBytesCallerPushed - NumBytes;
2608 // Set the delta of movement of the returnaddr stackslot.
2609 // But only set if delta is greater than previous delta.
2610 if (FPDiff < X86Info->getTCReturnAddrDelta())
2611 X86Info->setTCReturnAddrDelta(FPDiff);
2614 unsigned NumBytesToPush = NumBytes;
2615 unsigned NumBytesToPop = NumBytes;
2617 // If we have an inalloca argument, all stack space has already been allocated
2618 // for us and be right at the top of the stack. We don't support multiple
2619 // arguments passed in memory when using inalloca.
2620 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2622 assert(ArgLocs.back().getLocMemOffset() == 0 &&
2623 "an inalloca argument must be the only memory argument");
2627 Chain = DAG.getCALLSEQ_START(
2628 Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2630 SDValue RetAddrFrIdx;
2631 // Load return address for tail calls.
2632 if (isTailCall && FPDiff)
2633 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2634 Is64Bit, FPDiff, dl);
2636 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2637 SmallVector<SDValue, 8> MemOpChains;
2640 // Walk the register/memloc assignments, inserting copies/loads. In the case
2641 // of tail call optimization arguments are handle later.
2642 const X86RegisterInfo *RegInfo =
2643 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2644 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2645 // Skip inalloca arguments, they have already been written.
2646 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2647 if (Flags.isInAlloca())
2650 CCValAssign &VA = ArgLocs[i];
2651 EVT RegVT = VA.getLocVT();
2652 SDValue Arg = OutVals[i];
2653 bool isByVal = Flags.isByVal();
2655 // Promote the value if needed.
2656 switch (VA.getLocInfo()) {
2657 default: llvm_unreachable("Unknown loc info!");
2658 case CCValAssign::Full: break;
2659 case CCValAssign::SExt:
2660 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2662 case CCValAssign::ZExt:
2663 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2665 case CCValAssign::AExt:
2666 if (RegVT.is128BitVector()) {
2667 // Special case: passing MMX values in XMM registers.
2668 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2669 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2670 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2672 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2674 case CCValAssign::BCvt:
2675 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2677 case CCValAssign::Indirect: {
2678 // Store the argument.
2679 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2680 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2681 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2682 MachinePointerInfo::getFixedStack(FI),
2689 if (VA.isRegLoc()) {
2690 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2691 if (isVarArg && IsWin64) {
2692 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2693 // shadow reg if callee is a varargs function.
2694 unsigned ShadowReg = 0;
2695 switch (VA.getLocReg()) {
2696 case X86::XMM0: ShadowReg = X86::RCX; break;
2697 case X86::XMM1: ShadowReg = X86::RDX; break;
2698 case X86::XMM2: ShadowReg = X86::R8; break;
2699 case X86::XMM3: ShadowReg = X86::R9; break;
2702 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2704 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2705 assert(VA.isMemLoc());
2706 if (!StackPtr.getNode())
2707 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2709 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2710 dl, DAG, VA, Flags));
2714 if (!MemOpChains.empty())
2715 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2717 if (Subtarget->isPICStyleGOT()) {
2718 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2721 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2722 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2724 // If we are tail calling and generating PIC/GOT style code load the
2725 // address of the callee into ECX. The value in ecx is used as target of
2726 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2727 // for tail calls on PIC/GOT architectures. Normally we would just put the
2728 // address of GOT into ebx and then call target@PLT. But for tail calls
2729 // ebx would be restored (since ebx is callee saved) before jumping to the
2732 // Note: The actual moving to ECX is done further down.
2733 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2734 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2735 !G->getGlobal()->hasProtectedVisibility())
2736 Callee = LowerGlobalAddress(Callee, DAG);
2737 else if (isa<ExternalSymbolSDNode>(Callee))
2738 Callee = LowerExternalSymbol(Callee, DAG);
2742 if (Is64Bit && isVarArg && !IsWin64) {
2743 // From AMD64 ABI document:
2744 // For calls that may call functions that use varargs or stdargs
2745 // (prototype-less calls or calls to functions containing ellipsis (...) in
2746 // the declaration) %al is used as hidden argument to specify the number
2747 // of SSE registers used. The contents of %al do not need to match exactly
2748 // the number of registers, but must be an ubound on the number of SSE
2749 // registers used and is in the range 0 - 8 inclusive.
2751 // Count the number of XMM registers allocated.
2752 static const MCPhysReg XMMArgRegs[] = {
2753 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2754 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2756 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2757 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2758 && "SSE registers cannot be used when SSE is disabled");
2760 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2761 DAG.getConstant(NumXMMRegs, MVT::i8)));
2764 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
2765 // don't need this because the eligibility check rejects calls that require
2766 // shuffling arguments passed in memory.
2767 if (!IsSibcall && isTailCall) {
2768 // Force all the incoming stack arguments to be loaded from the stack
2769 // before any new outgoing arguments are stored to the stack, because the
2770 // outgoing stack slots may alias the incoming argument stack slots, and
2771 // the alias isn't otherwise explicit. This is slightly more conservative
2772 // than necessary, because it means that each store effectively depends
2773 // on every argument instead of just those arguments it would clobber.
2774 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2776 SmallVector<SDValue, 8> MemOpChains2;
2779 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2780 CCValAssign &VA = ArgLocs[i];
2783 assert(VA.isMemLoc());
2784 SDValue Arg = OutVals[i];
2785 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2786 // Skip inalloca arguments. They don't require any work.
2787 if (Flags.isInAlloca())
2789 // Create frame index.
2790 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2791 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2792 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2793 FIN = DAG.getFrameIndex(FI, getPointerTy());
2795 if (Flags.isByVal()) {
2796 // Copy relative to framepointer.
2797 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2798 if (!StackPtr.getNode())
2799 StackPtr = DAG.getCopyFromReg(Chain, dl,
2800 RegInfo->getStackRegister(),
2802 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2804 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2808 // Store relative to framepointer.
2809 MemOpChains2.push_back(
2810 DAG.getStore(ArgChain, dl, Arg, FIN,
2811 MachinePointerInfo::getFixedStack(FI),
2816 if (!MemOpChains2.empty())
2817 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2819 // Store the return address to the appropriate stack slot.
2820 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2821 getPointerTy(), RegInfo->getSlotSize(),
2825 // Build a sequence of copy-to-reg nodes chained together with token chain
2826 // and flag operands which copy the outgoing args into registers.
2828 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2829 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2830 RegsToPass[i].second, InFlag);
2831 InFlag = Chain.getValue(1);
2834 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2835 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2836 // In the 64-bit large code model, we have to make all calls
2837 // through a register, since the call instruction's 32-bit
2838 // pc-relative offset may not be large enough to hold the whole
2840 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2841 // If the callee is a GlobalAddress node (quite common, every direct call
2842 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2845 // We should use extra load for direct calls to dllimported functions in
2847 const GlobalValue *GV = G->getGlobal();
2848 if (!GV->hasDLLImportStorageClass()) {
2849 unsigned char OpFlags = 0;
2850 bool ExtraLoad = false;
2851 unsigned WrapperKind = ISD::DELETED_NODE;
2853 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2854 // external symbols most go through the PLT in PIC mode. If the symbol
2855 // has hidden or protected visibility, or if it is static or local, then
2856 // we don't need to use the PLT - we can directly call it.
2857 if (Subtarget->isTargetELF() &&
2858 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2859 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2860 OpFlags = X86II::MO_PLT;
2861 } else if (Subtarget->isPICStyleStubAny() &&
2862 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2863 (!Subtarget->getTargetTriple().isMacOSX() ||
2864 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2865 // PC-relative references to external symbols should go through $stub,
2866 // unless we're building with the leopard linker or later, which
2867 // automatically synthesizes these stubs.
2868 OpFlags = X86II::MO_DARWIN_STUB;
2869 } else if (Subtarget->isPICStyleRIPRel() &&
2870 isa<Function>(GV) &&
2871 cast<Function>(GV)->getAttributes().
2872 hasAttribute(AttributeSet::FunctionIndex,
2873 Attribute::NonLazyBind)) {
2874 // If the function is marked as non-lazy, generate an indirect call
2875 // which loads from the GOT directly. This avoids runtime overhead
2876 // at the cost of eager binding (and one extra byte of encoding).
2877 OpFlags = X86II::MO_GOTPCREL;
2878 WrapperKind = X86ISD::WrapperRIP;
2882 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2883 G->getOffset(), OpFlags);
2885 // Add a wrapper if needed.
2886 if (WrapperKind != ISD::DELETED_NODE)
2887 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2888 // Add extra indirection if needed.
2890 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2891 MachinePointerInfo::getGOT(),
2892 false, false, false, 0);
2894 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2895 unsigned char OpFlags = 0;
2897 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2898 // external symbols should go through the PLT.
2899 if (Subtarget->isTargetELF() &&
2900 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2901 OpFlags = X86II::MO_PLT;
2902 } else if (Subtarget->isPICStyleStubAny() &&
2903 (!Subtarget->getTargetTriple().isMacOSX() ||
2904 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2905 // PC-relative references to external symbols should go through $stub,
2906 // unless we're building with the leopard linker or later, which
2907 // automatically synthesizes these stubs.
2908 OpFlags = X86II::MO_DARWIN_STUB;
2911 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2915 // Returns a chain & a flag for retval copy to use.
2916 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2917 SmallVector<SDValue, 8> Ops;
2919 if (!IsSibcall && isTailCall) {
2920 Chain = DAG.getCALLSEQ_END(Chain,
2921 DAG.getIntPtrConstant(NumBytesToPop, true),
2922 DAG.getIntPtrConstant(0, true), InFlag, dl);
2923 InFlag = Chain.getValue(1);
2926 Ops.push_back(Chain);
2927 Ops.push_back(Callee);
2930 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2932 // Add argument registers to the end of the list so that they are known live
2934 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2935 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2936 RegsToPass[i].second.getValueType()));
2938 // Add a register mask operand representing the call-preserved registers.
2939 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2940 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2941 assert(Mask && "Missing call preserved mask for calling convention");
2942 Ops.push_back(DAG.getRegisterMask(Mask));
2944 if (InFlag.getNode())
2945 Ops.push_back(InFlag);
2949 //// If this is the first return lowered for this function, add the regs
2950 //// to the liveout set for the function.
2951 // This isn't right, although it's probably harmless on x86; liveouts
2952 // should be computed from returns not tail calls. Consider a void
2953 // function making a tail call to a function returning int.
2954 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
2957 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
2958 InFlag = Chain.getValue(1);
2960 // Create the CALLSEQ_END node.
2961 unsigned NumBytesForCalleeToPop;
2962 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2963 getTargetMachine().Options.GuaranteedTailCallOpt))
2964 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
2965 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2966 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2967 SR == StackStructReturn)
2968 // If this is a call to a struct-return function, the callee
2969 // pops the hidden struct pointer, so we have to push it back.
2970 // This is common for Darwin/X86, Linux & Mingw32 targets.
2971 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2972 NumBytesForCalleeToPop = 4;
2974 NumBytesForCalleeToPop = 0; // Callee pops nothing.
2976 // Returns a flag for retval copy to use.
2978 Chain = DAG.getCALLSEQ_END(Chain,
2979 DAG.getIntPtrConstant(NumBytesToPop, true),
2980 DAG.getIntPtrConstant(NumBytesForCalleeToPop,
2983 InFlag = Chain.getValue(1);
2986 // Handle result values, copying them out of physregs into vregs that we
2988 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2989 Ins, dl, DAG, InVals);
2992 //===----------------------------------------------------------------------===//
2993 // Fast Calling Convention (tail call) implementation
2994 //===----------------------------------------------------------------------===//
2996 // Like std call, callee cleans arguments, convention except that ECX is
2997 // reserved for storing the tail called function address. Only 2 registers are
2998 // free for argument passing (inreg). Tail call optimization is performed
3000 // * tailcallopt is enabled
3001 // * caller/callee are fastcc
3002 // On X86_64 architecture with GOT-style position independent code only local
3003 // (within module) calls are supported at the moment.
3004 // To keep the stack aligned according to platform abi the function
3005 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3006 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3007 // If a tail called function callee has more arguments than the caller the
3008 // caller needs to make sure that there is room to move the RETADDR to. This is
3009 // achieved by reserving an area the size of the argument delta right after the
3010 // original REtADDR, but before the saved framepointer or the spilled registers
3011 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3023 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3024 /// for a 16 byte align requirement.
3026 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3027 SelectionDAG& DAG) const {
3028 MachineFunction &MF = DAG.getMachineFunction();
3029 const TargetMachine &TM = MF.getTarget();
3030 const X86RegisterInfo *RegInfo =
3031 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3032 const TargetFrameLowering &TFI = *TM.getFrameLowering();
3033 unsigned StackAlignment = TFI.getStackAlignment();
3034 uint64_t AlignMask = StackAlignment - 1;
3035 int64_t Offset = StackSize;
3036 unsigned SlotSize = RegInfo->getSlotSize();
3037 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3038 // Number smaller than 12 so just add the difference.
3039 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3041 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3042 Offset = ((~AlignMask) & Offset) + StackAlignment +
3043 (StackAlignment-SlotSize);
3048 /// MatchingStackOffset - Return true if the given stack call argument is
3049 /// already available in the same position (relatively) of the caller's
3050 /// incoming argument stack.
3052 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3053 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3054 const X86InstrInfo *TII) {
3055 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3057 if (Arg.getOpcode() == ISD::CopyFromReg) {
3058 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3059 if (!TargetRegisterInfo::isVirtualRegister(VR))
3061 MachineInstr *Def = MRI->getVRegDef(VR);
3064 if (!Flags.isByVal()) {
3065 if (!TII->isLoadFromStackSlot(Def, FI))
3068 unsigned Opcode = Def->getOpcode();
3069 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3070 Def->getOperand(1).isFI()) {
3071 FI = Def->getOperand(1).getIndex();
3072 Bytes = Flags.getByValSize();
3076 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3077 if (Flags.isByVal())
3078 // ByVal argument is passed in as a pointer but it's now being
3079 // dereferenced. e.g.
3080 // define @foo(%struct.X* %A) {
3081 // tail call @bar(%struct.X* byval %A)
3084 SDValue Ptr = Ld->getBasePtr();
3085 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3088 FI = FINode->getIndex();
3089 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3090 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3091 FI = FINode->getIndex();
3092 Bytes = Flags.getByValSize();
3096 assert(FI != INT_MAX);
3097 if (!MFI->isFixedObjectIndex(FI))
3099 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3102 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3103 /// for tail call optimization. Targets which want to do tail call
3104 /// optimization should implement this function.
3106 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3107 CallingConv::ID CalleeCC,
3109 bool isCalleeStructRet,
3110 bool isCallerStructRet,
3112 const SmallVectorImpl<ISD::OutputArg> &Outs,
3113 const SmallVectorImpl<SDValue> &OutVals,
3114 const SmallVectorImpl<ISD::InputArg> &Ins,
3115 SelectionDAG &DAG) const {
3116 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3119 // If -tailcallopt is specified, make fastcc functions tail-callable.
3120 const MachineFunction &MF = DAG.getMachineFunction();
3121 const Function *CallerF = MF.getFunction();
3123 // If the function return type is x86_fp80 and the callee return type is not,
3124 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3125 // perform a tailcall optimization here.
3126 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3129 CallingConv::ID CallerCC = CallerF->getCallingConv();
3130 bool CCMatch = CallerCC == CalleeCC;
3131 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3132 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3134 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3135 if (IsTailCallConvention(CalleeCC) && CCMatch)
3140 // Look for obvious safe cases to perform tail call optimization that do not
3141 // require ABI changes. This is what gcc calls sibcall.
3143 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3144 // emit a special epilogue.
3145 const X86RegisterInfo *RegInfo =
3146 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3147 if (RegInfo->needsStackRealignment(MF))
3150 // Also avoid sibcall optimization if either caller or callee uses struct
3151 // return semantics.
3152 if (isCalleeStructRet || isCallerStructRet)
3155 // An stdcall/thiscall caller is expected to clean up its arguments; the
3156 // callee isn't going to do that.
3157 // FIXME: this is more restrictive than needed. We could produce a tailcall
3158 // when the stack adjustment matches. For example, with a thiscall that takes
3159 // only one argument.
3160 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3161 CallerCC == CallingConv::X86_ThisCall))
3164 // Do not sibcall optimize vararg calls unless all arguments are passed via
3166 if (isVarArg && !Outs.empty()) {
3168 // Optimizing for varargs on Win64 is unlikely to be safe without
3169 // additional testing.
3170 if (IsCalleeWin64 || IsCallerWin64)
3173 SmallVector<CCValAssign, 16> ArgLocs;
3174 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3175 getTargetMachine(), ArgLocs, *DAG.getContext());
3177 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3178 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3179 if (!ArgLocs[i].isRegLoc())
3183 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3184 // stack. Therefore, if it's not used by the call it is not safe to optimize
3185 // this into a sibcall.
3186 bool Unused = false;
3187 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3194 SmallVector<CCValAssign, 16> RVLocs;
3195 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3196 getTargetMachine(), RVLocs, *DAG.getContext());
3197 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3198 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3199 CCValAssign &VA = RVLocs[i];
3200 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3205 // If the calling conventions do not match, then we'd better make sure the
3206 // results are returned in the same way as what the caller expects.
3208 SmallVector<CCValAssign, 16> RVLocs1;
3209 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3210 getTargetMachine(), RVLocs1, *DAG.getContext());
3211 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3213 SmallVector<CCValAssign, 16> RVLocs2;
3214 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3215 getTargetMachine(), RVLocs2, *DAG.getContext());
3216 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3218 if (RVLocs1.size() != RVLocs2.size())
3220 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3221 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3223 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3225 if (RVLocs1[i].isRegLoc()) {
3226 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3229 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3235 // If the callee takes no arguments then go on to check the results of the
3237 if (!Outs.empty()) {
3238 // Check if stack adjustment is needed. For now, do not do this if any
3239 // argument is passed on the stack.
3240 SmallVector<CCValAssign, 16> ArgLocs;
3241 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3242 getTargetMachine(), ArgLocs, *DAG.getContext());
3244 // Allocate shadow area for Win64
3246 CCInfo.AllocateStack(32, 8);
3248 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3249 if (CCInfo.getNextStackOffset()) {
3250 MachineFunction &MF = DAG.getMachineFunction();
3251 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3254 // Check if the arguments are already laid out in the right way as
3255 // the caller's fixed stack objects.
3256 MachineFrameInfo *MFI = MF.getFrameInfo();
3257 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3258 const X86InstrInfo *TII =
3259 ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3260 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3261 CCValAssign &VA = ArgLocs[i];
3262 SDValue Arg = OutVals[i];
3263 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3264 if (VA.getLocInfo() == CCValAssign::Indirect)
3266 if (!VA.isRegLoc()) {
3267 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3274 // If the tailcall address may be in a register, then make sure it's
3275 // possible to register allocate for it. In 32-bit, the call address can
3276 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3277 // callee-saved registers are restored. These happen to be the same
3278 // registers used to pass 'inreg' arguments so watch out for those.
3279 if (!Subtarget->is64Bit() &&
3280 ((!isa<GlobalAddressSDNode>(Callee) &&
3281 !isa<ExternalSymbolSDNode>(Callee)) ||
3282 getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3283 unsigned NumInRegs = 0;
3284 // In PIC we need an extra register to formulate the address computation
3286 unsigned MaxInRegs =
3287 (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3289 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3290 CCValAssign &VA = ArgLocs[i];
3293 unsigned Reg = VA.getLocReg();
3296 case X86::EAX: case X86::EDX: case X86::ECX:
3297 if (++NumInRegs == MaxInRegs)
3309 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3310 const TargetLibraryInfo *libInfo) const {
3311 return X86::createFastISel(funcInfo, libInfo);
3314 //===----------------------------------------------------------------------===//
3315 // Other Lowering Hooks
3316 //===----------------------------------------------------------------------===//
3318 static bool MayFoldLoad(SDValue Op) {
3319 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3322 static bool MayFoldIntoStore(SDValue Op) {
3323 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3326 static bool isTargetShuffle(unsigned Opcode) {
3328 default: return false;
3329 case X86ISD::PSHUFD:
3330 case X86ISD::PSHUFHW:
3331 case X86ISD::PSHUFLW:
3333 case X86ISD::PALIGNR:
3334 case X86ISD::MOVLHPS:
3335 case X86ISD::MOVLHPD:
3336 case X86ISD::MOVHLPS:
3337 case X86ISD::MOVLPS:
3338 case X86ISD::MOVLPD:
3339 case X86ISD::MOVSHDUP:
3340 case X86ISD::MOVSLDUP:
3341 case X86ISD::MOVDDUP:
3344 case X86ISD::UNPCKL:
3345 case X86ISD::UNPCKH:
3346 case X86ISD::VPERMILP:
3347 case X86ISD::VPERM2X128:
3348 case X86ISD::VPERMI:
3353 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3354 SDValue V1, SelectionDAG &DAG) {
3356 default: llvm_unreachable("Unknown x86 shuffle node");
3357 case X86ISD::MOVSHDUP:
3358 case X86ISD::MOVSLDUP:
3359 case X86ISD::MOVDDUP:
3360 return DAG.getNode(Opc, dl, VT, V1);
3364 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3365 SDValue V1, unsigned TargetMask,
3366 SelectionDAG &DAG) {
3368 default: llvm_unreachable("Unknown x86 shuffle node");
3369 case X86ISD::PSHUFD:
3370 case X86ISD::PSHUFHW:
3371 case X86ISD::PSHUFLW:
3372 case X86ISD::VPERMILP:
3373 case X86ISD::VPERMI:
3374 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3378 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3379 SDValue V1, SDValue V2, unsigned TargetMask,
3380 SelectionDAG &DAG) {
3382 default: llvm_unreachable("Unknown x86 shuffle node");
3383 case X86ISD::PALIGNR:
3385 case X86ISD::VPERM2X128:
3386 return DAG.getNode(Opc, dl, VT, V1, V2,
3387 DAG.getConstant(TargetMask, MVT::i8));
3391 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3392 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3394 default: llvm_unreachable("Unknown x86 shuffle node");
3395 case X86ISD::MOVLHPS:
3396 case X86ISD::MOVLHPD:
3397 case X86ISD::MOVHLPS:
3398 case X86ISD::MOVLPS:
3399 case X86ISD::MOVLPD:
3402 case X86ISD::UNPCKL:
3403 case X86ISD::UNPCKH:
3404 return DAG.getNode(Opc, dl, VT, V1, V2);
3408 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3409 MachineFunction &MF = DAG.getMachineFunction();
3410 const X86RegisterInfo *RegInfo =
3411 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3412 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3413 int ReturnAddrIndex = FuncInfo->getRAIndex();
3415 if (ReturnAddrIndex == 0) {
3416 // Set up a frame object for the return address.
3417 unsigned SlotSize = RegInfo->getSlotSize();
3418 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3421 FuncInfo->setRAIndex(ReturnAddrIndex);
3424 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3427 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3428 bool hasSymbolicDisplacement) {
3429 // Offset should fit into 32 bit immediate field.
3430 if (!isInt<32>(Offset))
3433 // If we don't have a symbolic displacement - we don't have any extra
3435 if (!hasSymbolicDisplacement)
3438 // FIXME: Some tweaks might be needed for medium code model.
3439 if (M != CodeModel::Small && M != CodeModel::Kernel)
3442 // For small code model we assume that latest object is 16MB before end of 31
3443 // bits boundary. We may also accept pretty large negative constants knowing
3444 // that all objects are in the positive half of address space.
3445 if (M == CodeModel::Small && Offset < 16*1024*1024)
3448 // For kernel code model we know that all object resist in the negative half
3449 // of 32bits address space. We may not accept negative offsets, since they may
3450 // be just off and we may accept pretty large positive ones.
3451 if (M == CodeModel::Kernel && Offset > 0)
3457 /// isCalleePop - Determines whether the callee is required to pop its
3458 /// own arguments. Callee pop is necessary to support tail calls.
3459 bool X86::isCalleePop(CallingConv::ID CallingConv,
3460 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3464 switch (CallingConv) {
3467 case CallingConv::X86_StdCall:
3469 case CallingConv::X86_FastCall:
3471 case CallingConv::X86_ThisCall:
3473 case CallingConv::Fast:
3475 case CallingConv::GHC:
3477 case CallingConv::HiPE:
3482 /// \brief Return true if the condition is an unsigned comparison operation.
3483 static bool isX86CCUnsigned(unsigned X86CC) {
3485 default: llvm_unreachable("Invalid integer condition!");
3486 case X86::COND_E: return true;
3487 case X86::COND_G: return false;
3488 case X86::COND_GE: return false;
3489 case X86::COND_L: return false;
3490 case X86::COND_LE: return false;
3491 case X86::COND_NE: return true;
3492 case X86::COND_B: return true;
3493 case X86::COND_A: return true;
3494 case X86::COND_BE: return true;
3495 case X86::COND_AE: return true;
3497 llvm_unreachable("covered switch fell through?!");
3500 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3501 /// specific condition code, returning the condition code and the LHS/RHS of the
3502 /// comparison to make.
3503 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3504 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3506 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3507 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3508 // X > -1 -> X == 0, jump !sign.
3509 RHS = DAG.getConstant(0, RHS.getValueType());
3510 return X86::COND_NS;
3512 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3513 // X < 0 -> X == 0, jump on sign.
3516 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3518 RHS = DAG.getConstant(0, RHS.getValueType());
3519 return X86::COND_LE;
3523 switch (SetCCOpcode) {
3524 default: llvm_unreachable("Invalid integer condition!");
3525 case ISD::SETEQ: return X86::COND_E;
3526 case ISD::SETGT: return X86::COND_G;
3527 case ISD::SETGE: return X86::COND_GE;
3528 case ISD::SETLT: return X86::COND_L;
3529 case ISD::SETLE: return X86::COND_LE;
3530 case ISD::SETNE: return X86::COND_NE;
3531 case ISD::SETULT: return X86::COND_B;
3532 case ISD::SETUGT: return X86::COND_A;
3533 case ISD::SETULE: return X86::COND_BE;
3534 case ISD::SETUGE: return X86::COND_AE;
3538 // First determine if it is required or is profitable to flip the operands.
3540 // If LHS is a foldable load, but RHS is not, flip the condition.
3541 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3542 !ISD::isNON_EXTLoad(RHS.getNode())) {
3543 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3544 std::swap(LHS, RHS);
3547 switch (SetCCOpcode) {
3553 std::swap(LHS, RHS);
3557 // On a floating point condition, the flags are set as follows:
3559 // 0 | 0 | 0 | X > Y
3560 // 0 | 0 | 1 | X < Y
3561 // 1 | 0 | 0 | X == Y
3562 // 1 | 1 | 1 | unordered
3563 switch (SetCCOpcode) {
3564 default: llvm_unreachable("Condcode should be pre-legalized away");
3566 case ISD::SETEQ: return X86::COND_E;
3567 case ISD::SETOLT: // flipped
3569 case ISD::SETGT: return X86::COND_A;
3570 case ISD::SETOLE: // flipped
3572 case ISD::SETGE: return X86::COND_AE;
3573 case ISD::SETUGT: // flipped
3575 case ISD::SETLT: return X86::COND_B;
3576 case ISD::SETUGE: // flipped
3578 case ISD::SETLE: return X86::COND_BE;
3580 case ISD::SETNE: return X86::COND_NE;
3581 case ISD::SETUO: return X86::COND_P;
3582 case ISD::SETO: return X86::COND_NP;
3584 case ISD::SETUNE: return X86::COND_INVALID;
3588 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3589 /// code. Current x86 isa includes the following FP cmov instructions:
3590 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3591 static bool hasFPCMov(unsigned X86CC) {
3607 /// isFPImmLegal - Returns true if the target can instruction select the
3608 /// specified FP immediate natively. If false, the legalizer will
3609 /// materialize the FP immediate as a load from a constant pool.
3610 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3611 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3612 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3618 /// \brief Returns true if it is beneficial to convert a load of a constant
3619 /// to just the constant itself.
3620 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3622 assert(Ty->isIntegerTy());
3624 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3625 if (BitSize == 0 || BitSize > 64)
3630 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3631 /// the specified range (L, H].
3632 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3633 return (Val < 0) || (Val >= Low && Val < Hi);
3636 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3637 /// specified value.
3638 static bool isUndefOrEqual(int Val, int CmpVal) {
3639 return (Val < 0 || Val == CmpVal);
3642 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3643 /// from position Pos and ending in Pos+Size, falls within the specified
3644 /// sequential range (L, L+Pos]. or is undef.
3645 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3646 unsigned Pos, unsigned Size, int Low) {
3647 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3648 if (!isUndefOrEqual(Mask[i], Low))
3653 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3654 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3655 /// the second operand.
3656 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3657 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3658 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3659 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3660 return (Mask[0] < 2 && Mask[1] < 2);
3664 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3665 /// is suitable for input to PSHUFHW.
3666 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3667 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3670 // Lower quadword copied in order or undef.
3671 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3674 // Upper quadword shuffled.
3675 for (unsigned i = 4; i != 8; ++i)
3676 if (!isUndefOrInRange(Mask[i], 4, 8))
3679 if (VT == MVT::v16i16) {
3680 // Lower quadword copied in order or undef.
3681 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3684 // Upper quadword shuffled.
3685 for (unsigned i = 12; i != 16; ++i)
3686 if (!isUndefOrInRange(Mask[i], 12, 16))
3693 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3694 /// is suitable for input to PSHUFLW.
3695 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3696 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3699 // Upper quadword copied in order.
3700 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3703 // Lower quadword shuffled.
3704 for (unsigned i = 0; i != 4; ++i)
3705 if (!isUndefOrInRange(Mask[i], 0, 4))
3708 if (VT == MVT::v16i16) {
3709 // Upper quadword copied in order.
3710 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3713 // Lower quadword shuffled.
3714 for (unsigned i = 8; i != 12; ++i)
3715 if (!isUndefOrInRange(Mask[i], 8, 12))
3722 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3723 /// is suitable for input to PALIGNR.
3724 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3725 const X86Subtarget *Subtarget) {
3726 if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3727 (VT.is256BitVector() && !Subtarget->hasInt256()))
3730 unsigned NumElts = VT.getVectorNumElements();
3731 unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3732 unsigned NumLaneElts = NumElts/NumLanes;
3734 // Do not handle 64-bit element shuffles with palignr.
3735 if (NumLaneElts == 2)
3738 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3740 for (i = 0; i != NumLaneElts; ++i) {
3745 // Lane is all undef, go to next lane
3746 if (i == NumLaneElts)
3749 int Start = Mask[i+l];
3751 // Make sure its in this lane in one of the sources
3752 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3753 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3756 // If not lane 0, then we must match lane 0
3757 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3760 // Correct second source to be contiguous with first source
3761 if (Start >= (int)NumElts)
3762 Start -= NumElts - NumLaneElts;
3764 // Make sure we're shifting in the right direction.
3765 if (Start <= (int)(i+l))
3770 // Check the rest of the elements to see if they are consecutive.
3771 for (++i; i != NumLaneElts; ++i) {
3772 int Idx = Mask[i+l];
3774 // Make sure its in this lane
3775 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3776 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3779 // If not lane 0, then we must match lane 0
3780 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3783 if (Idx >= (int)NumElts)
3784 Idx -= NumElts - NumLaneElts;
3786 if (!isUndefOrEqual(Idx, Start+i))
3795 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3796 /// the two vector operands have swapped position.
3797 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3798 unsigned NumElems) {
3799 for (unsigned i = 0; i != NumElems; ++i) {
3803 else if (idx < (int)NumElems)
3804 Mask[i] = idx + NumElems;
3806 Mask[i] = idx - NumElems;
3810 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3811 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3812 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3813 /// reverse of what x86 shuffles want.
3814 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3816 unsigned NumElems = VT.getVectorNumElements();
3817 unsigned NumLanes = VT.getSizeInBits()/128;
3818 unsigned NumLaneElems = NumElems/NumLanes;
3820 if (NumLaneElems != 2 && NumLaneElems != 4)
3823 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3824 bool symetricMaskRequired =
3825 (VT.getSizeInBits() >= 256) && (EltSize == 32);
3827 // VSHUFPSY divides the resulting vector into 4 chunks.
3828 // The sources are also splitted into 4 chunks, and each destination
3829 // chunk must come from a different source chunk.
3831 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3832 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3834 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3835 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3837 // VSHUFPDY divides the resulting vector into 4 chunks.
3838 // The sources are also splitted into 4 chunks, and each destination
3839 // chunk must come from a different source chunk.
3841 // SRC1 => X3 X2 X1 X0
3842 // SRC2 => Y3 Y2 Y1 Y0
3844 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3846 SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3847 unsigned HalfLaneElems = NumLaneElems/2;
3848 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3849 for (unsigned i = 0; i != NumLaneElems; ++i) {
3850 int Idx = Mask[i+l];
3851 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3852 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3854 // For VSHUFPSY, the mask of the second half must be the same as the
3855 // first but with the appropriate offsets. This works in the same way as
3856 // VPERMILPS works with masks.
3857 if (!symetricMaskRequired || Idx < 0)
3859 if (MaskVal[i] < 0) {
3860 MaskVal[i] = Idx - l;
3863 if ((signed)(Idx - l) != MaskVal[i])
3871 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3872 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3873 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3874 if (!VT.is128BitVector())
3877 unsigned NumElems = VT.getVectorNumElements();
3882 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3883 return isUndefOrEqual(Mask[0], 6) &&
3884 isUndefOrEqual(Mask[1], 7) &&
3885 isUndefOrEqual(Mask[2], 2) &&
3886 isUndefOrEqual(Mask[3], 3);
3889 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3890 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3892 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3893 if (!VT.is128BitVector())
3896 unsigned NumElems = VT.getVectorNumElements();
3901 return isUndefOrEqual(Mask[0], 2) &&
3902 isUndefOrEqual(Mask[1], 3) &&
3903 isUndefOrEqual(Mask[2], 2) &&
3904 isUndefOrEqual(Mask[3], 3);
3907 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3908 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3909 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3910 if (!VT.is128BitVector())
3913 unsigned NumElems = VT.getVectorNumElements();
3915 if (NumElems != 2 && NumElems != 4)
3918 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3919 if (!isUndefOrEqual(Mask[i], i + NumElems))
3922 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3923 if (!isUndefOrEqual(Mask[i], i))
3929 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3930 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3931 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3932 if (!VT.is128BitVector())
3935 unsigned NumElems = VT.getVectorNumElements();
3937 if (NumElems != 2 && NumElems != 4)
3940 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3941 if (!isUndefOrEqual(Mask[i], i))
3944 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3945 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3951 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
3952 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
3953 /// i. e: If all but one element come from the same vector.
3954 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
3955 // TODO: Deal with AVX's VINSERTPS
3956 if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
3959 unsigned CorrectPosV1 = 0;
3960 unsigned CorrectPosV2 = 0;
3961 for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i)
3964 else if (Mask[i] == i + 4)
3967 if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
3968 // We have 3 elements from one vector, and one from another.
3975 // Some special combinations that can be optimized.
3978 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3979 SelectionDAG &DAG) {
3980 MVT VT = SVOp->getSimpleValueType(0);
3983 if (VT != MVT::v8i32 && VT != MVT::v8f32)
3986 ArrayRef<int> Mask = SVOp->getMask();
3988 // These are the special masks that may be optimized.
3989 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3990 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
3991 bool MatchEvenMask = true;
3992 bool MatchOddMask = true;
3993 for (int i=0; i<8; ++i) {
3994 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3995 MatchEvenMask = false;
3996 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3997 MatchOddMask = false;
4000 if (!MatchEvenMask && !MatchOddMask)
4003 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4005 SDValue Op0 = SVOp->getOperand(0);
4006 SDValue Op1 = SVOp->getOperand(1);
4008 if (MatchEvenMask) {
4009 // Shift the second operand right to 32 bits.
4010 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4011 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4013 // Shift the first operand left to 32 bits.
4014 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4015 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4017 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4018 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4021 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4022 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4023 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4024 bool HasInt256, bool V2IsSplat = false) {
4026 assert(VT.getSizeInBits() >= 128 &&
4027 "Unsupported vector type for unpckl");
4029 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4031 unsigned NumOf256BitLanes;
4032 unsigned NumElts = VT.getVectorNumElements();
4033 if (VT.is256BitVector()) {
4034 if (NumElts != 4 && NumElts != 8 &&
4035 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4038 NumOf256BitLanes = 1;
4039 } else if (VT.is512BitVector()) {
4040 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4041 "Unsupported vector type for unpckh");
4043 NumOf256BitLanes = 2;
4046 NumOf256BitLanes = 1;
4049 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4050 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4052 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4053 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4054 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4055 int BitI = Mask[l256*NumEltsInStride+l+i];
4056 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4057 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4059 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4061 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4069 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4070 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4071 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4072 bool HasInt256, bool V2IsSplat = false) {
4073 assert(VT.getSizeInBits() >= 128 &&
4074 "Unsupported vector type for unpckh");
4076 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4078 unsigned NumOf256BitLanes;
4079 unsigned NumElts = VT.getVectorNumElements();
4080 if (VT.is256BitVector()) {
4081 if (NumElts != 4 && NumElts != 8 &&
4082 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4085 NumOf256BitLanes = 1;
4086 } else if (VT.is512BitVector()) {
4087 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4088 "Unsupported vector type for unpckh");
4090 NumOf256BitLanes = 2;
4093 NumOf256BitLanes = 1;
4096 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4097 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4099 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4100 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4101 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4102 int BitI = Mask[l256*NumEltsInStride+l+i];
4103 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4104 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4106 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4108 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4116 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4117 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4119 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4120 unsigned NumElts = VT.getVectorNumElements();
4121 bool Is256BitVec = VT.is256BitVector();
4123 if (VT.is512BitVector())
4125 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4126 "Unsupported vector type for unpckh");
4128 if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4129 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4132 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4133 // FIXME: Need a better way to get rid of this, there's no latency difference
4134 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4135 // the former later. We should also remove the "_undef" special mask.
4136 if (NumElts == 4 && Is256BitVec)
4139 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4140 // independently on 128-bit lanes.
4141 unsigned NumLanes = VT.getSizeInBits()/128;
4142 unsigned NumLaneElts = NumElts/NumLanes;
4144 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4145 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4146 int BitI = Mask[l+i];
4147 int BitI1 = Mask[l+i+1];
4149 if (!isUndefOrEqual(BitI, j))
4151 if (!isUndefOrEqual(BitI1, j))
4159 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4160 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4162 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4163 unsigned NumElts = VT.getVectorNumElements();
4165 if (VT.is512BitVector())
4168 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4169 "Unsupported vector type for unpckh");
4171 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4172 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4175 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4176 // independently on 128-bit lanes.
4177 unsigned NumLanes = VT.getSizeInBits()/128;
4178 unsigned NumLaneElts = NumElts/NumLanes;
4180 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4181 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4182 int BitI = Mask[l+i];
4183 int BitI1 = Mask[l+i+1];
4184 if (!isUndefOrEqual(BitI, j))
4186 if (!isUndefOrEqual(BitI1, j))
4193 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4194 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4195 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4196 if (!VT.is512BitVector())
4199 unsigned NumElts = VT.getVectorNumElements();
4200 unsigned HalfSize = NumElts/2;
4201 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4202 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4207 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4208 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4216 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4217 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4218 /// MOVSD, and MOVD, i.e. setting the lowest element.
4219 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4220 if (VT.getVectorElementType().getSizeInBits() < 32)
4222 if (!VT.is128BitVector())
4225 unsigned NumElts = VT.getVectorNumElements();
4227 if (!isUndefOrEqual(Mask[0], NumElts))
4230 for (unsigned i = 1; i != NumElts; ++i)
4231 if (!isUndefOrEqual(Mask[i], i))
4237 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4238 /// as permutations between 128-bit chunks or halves. As an example: this
4240 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4241 /// The first half comes from the second half of V1 and the second half from the
4242 /// the second half of V2.
4243 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4244 if (!HasFp256 || !VT.is256BitVector())
4247 // The shuffle result is divided into half A and half B. In total the two
4248 // sources have 4 halves, namely: C, D, E, F. The final values of A and
4249 // B must come from C, D, E or F.
4250 unsigned HalfSize = VT.getVectorNumElements()/2;
4251 bool MatchA = false, MatchB = false;
4253 // Check if A comes from one of C, D, E, F.
4254 for (unsigned Half = 0; Half != 4; ++Half) {
4255 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4261 // Check if B comes from one of C, D, E, F.
4262 for (unsigned Half = 0; Half != 4; ++Half) {
4263 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4269 return MatchA && MatchB;
4272 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4273 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4274 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4275 MVT VT = SVOp->getSimpleValueType(0);
4277 unsigned HalfSize = VT.getVectorNumElements()/2;
4279 unsigned FstHalf = 0, SndHalf = 0;
4280 for (unsigned i = 0; i < HalfSize; ++i) {
4281 if (SVOp->getMaskElt(i) > 0) {
4282 FstHalf = SVOp->getMaskElt(i)/HalfSize;
4286 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4287 if (SVOp->getMaskElt(i) > 0) {
4288 SndHalf = SVOp->getMaskElt(i)/HalfSize;
4293 return (FstHalf | (SndHalf << 4));
4296 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4297 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4298 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4302 unsigned NumElts = VT.getVectorNumElements();
4304 if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4305 for (unsigned i = 0; i != NumElts; ++i) {
4308 Imm8 |= Mask[i] << (i*2);
4313 unsigned LaneSize = 4;
4314 SmallVector<int, 4> MaskVal(LaneSize, -1);
4316 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4317 for (unsigned i = 0; i != LaneSize; ++i) {
4318 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4322 if (MaskVal[i] < 0) {
4323 MaskVal[i] = Mask[i+l] - l;
4324 Imm8 |= MaskVal[i] << (i*2);
4327 if (Mask[i+l] != (signed)(MaskVal[i]+l))
4334 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4335 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4336 /// Note that VPERMIL mask matching is different depending whether theunderlying
4337 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4338 /// to the same elements of the low, but to the higher half of the source.
4339 /// In VPERMILPD the two lanes could be shuffled independently of each other
4340 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4341 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4342 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4343 if (VT.getSizeInBits() < 256 || EltSize < 32)
4345 bool symetricMaskRequired = (EltSize == 32);
4346 unsigned NumElts = VT.getVectorNumElements();
4348 unsigned NumLanes = VT.getSizeInBits()/128;
4349 unsigned LaneSize = NumElts/NumLanes;
4350 // 2 or 4 elements in one lane
4352 SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4353 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4354 for (unsigned i = 0; i != LaneSize; ++i) {
4355 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4357 if (symetricMaskRequired) {
4358 if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4359 ExpectedMaskVal[i] = Mask[i+l] - l;
4362 if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4370 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4371 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
4372 /// element of vector 2 and the other elements to come from vector 1 in order.
4373 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4374 bool V2IsSplat = false, bool V2IsUndef = false) {
4375 if (!VT.is128BitVector())
4378 unsigned NumOps = VT.getVectorNumElements();
4379 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4382 if (!isUndefOrEqual(Mask[0], 0))
4385 for (unsigned i = 1; i != NumOps; ++i)
4386 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4387 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4388 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4394 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4395 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4396 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4397 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4398 const X86Subtarget *Subtarget) {
4399 if (!Subtarget->hasSSE3())
4402 unsigned NumElems = VT.getVectorNumElements();
4404 if ((VT.is128BitVector() && NumElems != 4) ||
4405 (VT.is256BitVector() && NumElems != 8) ||
4406 (VT.is512BitVector() && NumElems != 16))
4409 // "i+1" is the value the indexed mask element must have
4410 for (unsigned i = 0; i != NumElems; i += 2)
4411 if (!isUndefOrEqual(Mask[i], i+1) ||
4412 !isUndefOrEqual(Mask[i+1], i+1))
4418 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4419 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4420 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4421 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4422 const X86Subtarget *Subtarget) {
4423 if (!Subtarget->hasSSE3())
4426 unsigned NumElems = VT.getVectorNumElements();
4428 if ((VT.is128BitVector() && NumElems != 4) ||
4429 (VT.is256BitVector() && NumElems != 8) ||
4430 (VT.is512BitVector() && NumElems != 16))
4433 // "i" is the value the indexed mask element must have
4434 for (unsigned i = 0; i != NumElems; i += 2)
4435 if (!isUndefOrEqual(Mask[i], i) ||
4436 !isUndefOrEqual(Mask[i+1], i))
4442 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4443 /// specifies a shuffle of elements that is suitable for input to 256-bit
4444 /// version of MOVDDUP.
4445 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4446 if (!HasFp256 || !VT.is256BitVector())
4449 unsigned NumElts = VT.getVectorNumElements();
4453 for (unsigned i = 0; i != NumElts/2; ++i)
4454 if (!isUndefOrEqual(Mask[i], 0))
4456 for (unsigned i = NumElts/2; i != NumElts; ++i)
4457 if (!isUndefOrEqual(Mask[i], NumElts/2))
4462 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4463 /// specifies a shuffle of elements that is suitable for input to 128-bit
4464 /// version of MOVDDUP.
4465 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4466 if (!VT.is128BitVector())
4469 unsigned e = VT.getVectorNumElements() / 2;
4470 for (unsigned i = 0; i != e; ++i)
4471 if (!isUndefOrEqual(Mask[i], i))
4473 for (unsigned i = 0; i != e; ++i)
4474 if (!isUndefOrEqual(Mask[e+i], i))
4479 /// isVEXTRACTIndex - Return true if the specified
4480 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4481 /// suitable for instruction that extract 128 or 256 bit vectors
4482 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4483 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4484 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4487 // The index should be aligned on a vecWidth-bit boundary.
4489 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4491 MVT VT = N->getSimpleValueType(0);
4492 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4493 bool Result = (Index * ElSize) % vecWidth == 0;
4498 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4499 /// operand specifies a subvector insert that is suitable for input to
4500 /// insertion of 128 or 256-bit subvectors
4501 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4502 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4503 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4505 // The index should be aligned on a vecWidth-bit boundary.
4507 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4509 MVT VT = N->getSimpleValueType(0);
4510 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4511 bool Result = (Index * ElSize) % vecWidth == 0;
4516 bool X86::isVINSERT128Index(SDNode *N) {
4517 return isVINSERTIndex(N, 128);
4520 bool X86::isVINSERT256Index(SDNode *N) {
4521 return isVINSERTIndex(N, 256);
4524 bool X86::isVEXTRACT128Index(SDNode *N) {
4525 return isVEXTRACTIndex(N, 128);
4528 bool X86::isVEXTRACT256Index(SDNode *N) {
4529 return isVEXTRACTIndex(N, 256);
4532 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4533 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4534 /// Handles 128-bit and 256-bit.
4535 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4536 MVT VT = N->getSimpleValueType(0);
4538 assert((VT.getSizeInBits() >= 128) &&
4539 "Unsupported vector type for PSHUF/SHUFP");
4541 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4542 // independently on 128-bit lanes.
4543 unsigned NumElts = VT.getVectorNumElements();
4544 unsigned NumLanes = VT.getSizeInBits()/128;
4545 unsigned NumLaneElts = NumElts/NumLanes;
4547 assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4548 "Only supports 2, 4 or 8 elements per lane");
4550 unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4552 for (unsigned i = 0; i != NumElts; ++i) {
4553 int Elt = N->getMaskElt(i);
4554 if (Elt < 0) continue;
4555 Elt &= NumLaneElts - 1;
4556 unsigned ShAmt = (i << Shift) % 8;
4557 Mask |= Elt << ShAmt;
4563 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4564 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4565 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4566 MVT VT = N->getSimpleValueType(0);
4568 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4569 "Unsupported vector type for PSHUFHW");
4571 unsigned NumElts = VT.getVectorNumElements();
4574 for (unsigned l = 0; l != NumElts; l += 8) {
4575 // 8 nodes per lane, but we only care about the last 4.
4576 for (unsigned i = 0; i < 4; ++i) {
4577 int Elt = N->getMaskElt(l+i+4);
4578 if (Elt < 0) continue;
4579 Elt &= 0x3; // only 2-bits.
4580 Mask |= Elt << (i * 2);
4587 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4588 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4589 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4590 MVT VT = N->getSimpleValueType(0);
4592 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4593 "Unsupported vector type for PSHUFHW");
4595 unsigned NumElts = VT.getVectorNumElements();
4598 for (unsigned l = 0; l != NumElts; l += 8) {
4599 // 8 nodes per lane, but we only care about the first 4.
4600 for (unsigned i = 0; i < 4; ++i) {
4601 int Elt = N->getMaskElt(l+i);
4602 if (Elt < 0) continue;
4603 Elt &= 0x3; // only 2-bits
4604 Mask |= Elt << (i * 2);
4611 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4612 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4613 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4614 MVT VT = SVOp->getSimpleValueType(0);
4615 unsigned EltSize = VT.is512BitVector() ? 1 :
4616 VT.getVectorElementType().getSizeInBits() >> 3;
4618 unsigned NumElts = VT.getVectorNumElements();
4619 unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4620 unsigned NumLaneElts = NumElts/NumLanes;
4624 for (i = 0; i != NumElts; ++i) {
4625 Val = SVOp->getMaskElt(i);
4629 if (Val >= (int)NumElts)
4630 Val -= NumElts - NumLaneElts;
4632 assert(Val - i > 0 && "PALIGNR imm should be positive");
4633 return (Val - i) * EltSize;
4636 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4637 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4638 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4639 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4642 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4644 MVT VecVT = N->getOperand(0).getSimpleValueType();
4645 MVT ElVT = VecVT.getVectorElementType();
4647 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4648 return Index / NumElemsPerChunk;
4651 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4652 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4653 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4654 llvm_unreachable("Illegal insert subvector for VINSERT");
4657 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4659 MVT VecVT = N->getSimpleValueType(0);
4660 MVT ElVT = VecVT.getVectorElementType();
4662 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4663 return Index / NumElemsPerChunk;
4666 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4667 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4668 /// and VINSERTI128 instructions.
4669 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4670 return getExtractVEXTRACTImmediate(N, 128);
4673 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4674 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4675 /// and VINSERTI64x4 instructions.
4676 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4677 return getExtractVEXTRACTImmediate(N, 256);
4680 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4681 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4682 /// and VINSERTI128 instructions.
4683 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4684 return getInsertVINSERTImmediate(N, 128);
4687 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4688 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4689 /// and VINSERTI64x4 instructions.
4690 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4691 return getInsertVINSERTImmediate(N, 256);
4694 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4696 bool X86::isZeroNode(SDValue Elt) {
4697 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4698 return CN->isNullValue();
4699 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4700 return CFP->getValueAPF().isPosZero();
4704 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4705 /// their permute mask.
4706 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4707 SelectionDAG &DAG) {
4708 MVT VT = SVOp->getSimpleValueType(0);
4709 unsigned NumElems = VT.getVectorNumElements();
4710 SmallVector<int, 8> MaskVec;
4712 for (unsigned i = 0; i != NumElems; ++i) {
4713 int Idx = SVOp->getMaskElt(i);
4715 if (Idx < (int)NumElems)
4720 MaskVec.push_back(Idx);
4722 return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4723 SVOp->getOperand(0), &MaskVec[0]);
4726 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4727 /// match movhlps. The lower half elements should come from upper half of
4728 /// V1 (and in order), and the upper half elements should come from the upper
4729 /// half of V2 (and in order).
4730 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4731 if (!VT.is128BitVector())
4733 if (VT.getVectorNumElements() != 4)
4735 for (unsigned i = 0, e = 2; i != e; ++i)
4736 if (!isUndefOrEqual(Mask[i], i+2))
4738 for (unsigned i = 2; i != 4; ++i)
4739 if (!isUndefOrEqual(Mask[i], i+4))
4744 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4745 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4747 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4748 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4750 N = N->getOperand(0).getNode();
4751 if (!ISD::isNON_EXTLoad(N))
4754 *LD = cast<LoadSDNode>(N);
4758 // Test whether the given value is a vector value which will be legalized
4760 static bool WillBeConstantPoolLoad(SDNode *N) {
4761 if (N->getOpcode() != ISD::BUILD_VECTOR)
4764 // Check for any non-constant elements.
4765 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4766 switch (N->getOperand(i).getNode()->getOpcode()) {
4768 case ISD::ConstantFP:
4775 // Vectors of all-zeros and all-ones are materialized with special
4776 // instructions rather than being loaded.
4777 return !ISD::isBuildVectorAllZeros(N) &&
4778 !ISD::isBuildVectorAllOnes(N);
4781 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4782 /// match movlp{s|d}. The lower half elements should come from lower half of
4783 /// V1 (and in order), and the upper half elements should come from the upper
4784 /// half of V2 (and in order). And since V1 will become the source of the
4785 /// MOVLP, it must be either a vector load or a scalar load to vector.
4786 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4787 ArrayRef<int> Mask, MVT VT) {
4788 if (!VT.is128BitVector())
4791 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4793 // Is V2 is a vector load, don't do this transformation. We will try to use
4794 // load folding shufps op.
4795 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4798 unsigned NumElems = VT.getVectorNumElements();
4800 if (NumElems != 2 && NumElems != 4)
4802 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4803 if (!isUndefOrEqual(Mask[i], i))
4805 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4806 if (!isUndefOrEqual(Mask[i], i+NumElems))
4811 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4813 static bool isSplatVector(SDNode *N) {
4814 if (N->getOpcode() != ISD::BUILD_VECTOR)
4817 SDValue SplatValue = N->getOperand(0);
4818 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4819 if (N->getOperand(i) != SplatValue)
4824 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4825 /// to an zero vector.
4826 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4827 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4828 SDValue V1 = N->getOperand(0);
4829 SDValue V2 = N->getOperand(1);
4830 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4831 for (unsigned i = 0; i != NumElems; ++i) {
4832 int Idx = N->getMaskElt(i);
4833 if (Idx >= (int)NumElems) {
4834 unsigned Opc = V2.getOpcode();
4835 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4837 if (Opc != ISD::BUILD_VECTOR ||
4838 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4840 } else if (Idx >= 0) {
4841 unsigned Opc = V1.getOpcode();
4842 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4844 if (Opc != ISD::BUILD_VECTOR ||
4845 !X86::isZeroNode(V1.getOperand(Idx)))
4852 /// getZeroVector - Returns a vector of specified type with all zero elements.
4854 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4855 SelectionDAG &DAG, SDLoc dl) {
4856 assert(VT.isVector() && "Expected a vector type");
4858 // Always build SSE zero vectors as <4 x i32> bitcasted
4859 // to their dest type. This ensures they get CSE'd.
4861 if (VT.is128BitVector()) { // SSE
4862 if (Subtarget->hasSSE2()) { // SSE2
4863 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4864 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4866 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4867 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4869 } else if (VT.is256BitVector()) { // AVX
4870 if (Subtarget->hasInt256()) { // AVX2
4871 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4872 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4873 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4875 // 256-bit logic and arithmetic instructions in AVX are all
4876 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4877 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4878 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4879 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4881 } else if (VT.is512BitVector()) { // AVX-512
4882 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4883 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4884 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4885 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4886 } else if (VT.getScalarType() == MVT::i1) {
4887 assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4888 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4889 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4890 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4892 llvm_unreachable("Unexpected vector type");
4894 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4897 /// getOnesVector - Returns a vector of specified type with all bits set.
4898 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4899 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4900 /// Then bitcast to their original type, ensuring they get CSE'd.
4901 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4903 assert(VT.isVector() && "Expected a vector type");
4905 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4907 if (VT.is256BitVector()) {
4908 if (HasInt256) { // AVX2
4909 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4910 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4912 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4913 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4915 } else if (VT.is128BitVector()) {
4916 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4918 llvm_unreachable("Unexpected vector type");
4920 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4923 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4924 /// that point to V2 points to its first element.
4925 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4926 for (unsigned i = 0; i != NumElems; ++i) {
4927 if (Mask[i] > (int)NumElems) {
4933 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4934 /// operation of specified width.
4935 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4937 unsigned NumElems = VT.getVectorNumElements();
4938 SmallVector<int, 8> Mask;
4939 Mask.push_back(NumElems);
4940 for (unsigned i = 1; i != NumElems; ++i)
4942 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4945 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4946 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4948 unsigned NumElems = VT.getVectorNumElements();
4949 SmallVector<int, 8> Mask;
4950 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4952 Mask.push_back(i + NumElems);
4954 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4957 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4958 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4960 unsigned NumElems = VT.getVectorNumElements();
4961 SmallVector<int, 8> Mask;
4962 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4963 Mask.push_back(i + Half);
4964 Mask.push_back(i + NumElems + Half);
4966 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4969 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4970 // a generic shuffle instruction because the target has no such instructions.
4971 // Generate shuffles which repeat i16 and i8 several times until they can be
4972 // represented by v4f32 and then be manipulated by target suported shuffles.
4973 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4974 MVT VT = V.getSimpleValueType();
4975 int NumElems = VT.getVectorNumElements();
4978 while (NumElems > 4) {
4979 if (EltNo < NumElems/2) {
4980 V = getUnpackl(DAG, dl, VT, V, V);
4982 V = getUnpackh(DAG, dl, VT, V, V);
4983 EltNo -= NumElems/2;
4990 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4991 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4992 MVT VT = V.getSimpleValueType();
4995 if (VT.is128BitVector()) {
4996 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4997 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4998 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5000 } else if (VT.is256BitVector()) {
5001 // To use VPERMILPS to splat scalars, the second half of indicies must
5002 // refer to the higher part, which is a duplication of the lower one,
5003 // because VPERMILPS can only handle in-lane permutations.
5004 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5005 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5007 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5008 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5011 llvm_unreachable("Vector size not supported");
5013 return DAG.getNode(ISD::BITCAST, dl, VT, V);
5016 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5017 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5018 MVT SrcVT = SV->getSimpleValueType(0);
5019 SDValue V1 = SV->getOperand(0);
5022 int EltNo = SV->getSplatIndex();
5023 int NumElems = SrcVT.getVectorNumElements();
5024 bool Is256BitVec = SrcVT.is256BitVector();
5026 assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5027 "Unknown how to promote splat for type");
5029 // Extract the 128-bit part containing the splat element and update
5030 // the splat element index when it refers to the higher register.
5032 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5033 if (EltNo >= NumElems/2)
5034 EltNo -= NumElems/2;
5037 // All i16 and i8 vector types can't be used directly by a generic shuffle
5038 // instruction because the target has no such instruction. Generate shuffles
5039 // which repeat i16 and i8 several times until they fit in i32, and then can
5040 // be manipulated by target suported shuffles.
5041 MVT EltVT = SrcVT.getVectorElementType();
5042 if (EltVT == MVT::i8 || EltVT == MVT::i16)
5043 V1 = PromoteSplati8i16(V1, DAG, EltNo);
5045 // Recreate the 256-bit vector and place the same 128-bit vector
5046 // into the low and high part. This is necessary because we want
5047 // to use VPERM* to shuffle the vectors
5049 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5052 return getLegalSplat(DAG, V1, EltNo);
5055 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5056 /// vector of zero or undef vector. This produces a shuffle where the low
5057 /// element of V2 is swizzled into the zero/undef vector, landing at element
5058 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
5059 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5061 const X86Subtarget *Subtarget,
5062 SelectionDAG &DAG) {
5063 MVT VT = V2.getSimpleValueType();
5065 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5066 unsigned NumElems = VT.getVectorNumElements();
5067 SmallVector<int, 16> MaskVec;
5068 for (unsigned i = 0; i != NumElems; ++i)
5069 // If this is the insertion idx, put the low elt of V2 here.
5070 MaskVec.push_back(i == Idx ? NumElems : i);
5071 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5074 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5075 /// target specific opcode. Returns true if the Mask could be calculated.
5076 /// Sets IsUnary to true if only uses one source.
5077 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5078 SmallVectorImpl<int> &Mask, bool &IsUnary) {
5079 unsigned NumElems = VT.getVectorNumElements();
5083 switch(N->getOpcode()) {
5085 ImmN = N->getOperand(N->getNumOperands()-1);
5086 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5088 case X86ISD::UNPCKH:
5089 DecodeUNPCKHMask(VT, Mask);
5091 case X86ISD::UNPCKL:
5092 DecodeUNPCKLMask(VT, Mask);
5094 case X86ISD::MOVHLPS:
5095 DecodeMOVHLPSMask(NumElems, Mask);
5097 case X86ISD::MOVLHPS:
5098 DecodeMOVLHPSMask(NumElems, Mask);
5100 case X86ISD::PALIGNR:
5101 ImmN = N->getOperand(N->getNumOperands()-1);
5102 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5104 case X86ISD::PSHUFD:
5105 case X86ISD::VPERMILP:
5106 ImmN = N->getOperand(N->getNumOperands()-1);
5107 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5110 case X86ISD::PSHUFHW:
5111 ImmN = N->getOperand(N->getNumOperands()-1);
5112 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5115 case X86ISD::PSHUFLW:
5116 ImmN = N->getOperand(N->getNumOperands()-1);
5117 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5120 case X86ISD::VPERMI:
5121 ImmN = N->getOperand(N->getNumOperands()-1);
5122 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5126 case X86ISD::MOVSD: {
5127 // The index 0 always comes from the first element of the second source,
5128 // this is why MOVSS and MOVSD are used in the first place. The other
5129 // elements come from the other positions of the first source vector
5130 Mask.push_back(NumElems);
5131 for (unsigned i = 1; i != NumElems; ++i) {
5136 case X86ISD::VPERM2X128:
5137 ImmN = N->getOperand(N->getNumOperands()-1);
5138 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5139 if (Mask.empty()) return false;
5141 case X86ISD::MOVDDUP:
5142 case X86ISD::MOVLHPD:
5143 case X86ISD::MOVLPD:
5144 case X86ISD::MOVLPS:
5145 case X86ISD::MOVSHDUP:
5146 case X86ISD::MOVSLDUP:
5147 // Not yet implemented
5149 default: llvm_unreachable("unknown target shuffle node");
5155 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5156 /// element of the result of the vector shuffle.
5157 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5160 return SDValue(); // Limit search depth.
5162 SDValue V = SDValue(N, 0);
5163 EVT VT = V.getValueType();
5164 unsigned Opcode = V.getOpcode();
5166 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5167 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5168 int Elt = SV->getMaskElt(Index);
5171 return DAG.getUNDEF(VT.getVectorElementType());
5173 unsigned NumElems = VT.getVectorNumElements();
5174 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5175 : SV->getOperand(1);
5176 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5179 // Recurse into target specific vector shuffles to find scalars.
5180 if (isTargetShuffle(Opcode)) {
5181 MVT ShufVT = V.getSimpleValueType();
5182 unsigned NumElems = ShufVT.getVectorNumElements();
5183 SmallVector<int, 16> ShuffleMask;
5186 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5189 int Elt = ShuffleMask[Index];
5191 return DAG.getUNDEF(ShufVT.getVectorElementType());
5193 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5195 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5199 // Actual nodes that may contain scalar elements
5200 if (Opcode == ISD::BITCAST) {
5201 V = V.getOperand(0);
5202 EVT SrcVT = V.getValueType();
5203 unsigned NumElems = VT.getVectorNumElements();
5205 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5209 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5210 return (Index == 0) ? V.getOperand(0)
5211 : DAG.getUNDEF(VT.getVectorElementType());
5213 if (V.getOpcode() == ISD::BUILD_VECTOR)
5214 return V.getOperand(Index);
5219 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5220 /// shuffle operation which come from a consecutively from a zero. The
5221 /// search can start in two different directions, from left or right.
5222 /// We count undefs as zeros until PreferredNum is reached.
5223 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5224 unsigned NumElems, bool ZerosFromLeft,
5226 unsigned PreferredNum = -1U) {
5227 unsigned NumZeros = 0;
5228 for (unsigned i = 0; i != NumElems; ++i) {
5229 unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5230 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5234 if (X86::isZeroNode(Elt))
5236 else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5237 NumZeros = std::min(NumZeros + 1, PreferredNum);
5245 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5246 /// correspond consecutively to elements from one of the vector operands,
5247 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5249 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5250 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5251 unsigned NumElems, unsigned &OpNum) {
5252 bool SeenV1 = false;
5253 bool SeenV2 = false;
5255 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5256 int Idx = SVOp->getMaskElt(i);
5257 // Ignore undef indicies
5261 if (Idx < (int)NumElems)
5266 // Only accept consecutive elements from the same vector
5267 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5271 OpNum = SeenV1 ? 0 : 1;
5275 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5276 /// logical left shift of a vector.
5277 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5278 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5280 SVOp->getSimpleValueType(0).getVectorNumElements();
5281 unsigned NumZeros = getNumOfConsecutiveZeros(
5282 SVOp, NumElems, false /* check zeros from right */, DAG,
5283 SVOp->getMaskElt(0));
5289 // Considering the elements in the mask that are not consecutive zeros,
5290 // check if they consecutively come from only one of the source vectors.
5292 // V1 = {X, A, B, C} 0
5294 // vector_shuffle V1, V2 <1, 2, 3, X>
5296 if (!isShuffleMaskConsecutive(SVOp,
5297 0, // Mask Start Index
5298 NumElems-NumZeros, // Mask End Index(exclusive)
5299 NumZeros, // Where to start looking in the src vector
5300 NumElems, // Number of elements in vector
5301 OpSrc)) // Which source operand ?
5306 ShVal = SVOp->getOperand(OpSrc);
5310 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5311 /// logical left shift of a vector.
5312 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5313 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5315 SVOp->getSimpleValueType(0).getVectorNumElements();
5316 unsigned NumZeros = getNumOfConsecutiveZeros(
5317 SVOp, NumElems, true /* check zeros from left */, DAG,
5318 NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5324 // Considering the elements in the mask that are not consecutive zeros,
5325 // check if they consecutively come from only one of the source vectors.
5327 // 0 { A, B, X, X } = V2
5329 // vector_shuffle V1, V2 <X, X, 4, 5>
5331 if (!isShuffleMaskConsecutive(SVOp,
5332 NumZeros, // Mask Start Index
5333 NumElems, // Mask End Index(exclusive)
5334 0, // Where to start looking in the src vector
5335 NumElems, // Number of elements in vector
5336 OpSrc)) // Which source operand ?
5341 ShVal = SVOp->getOperand(OpSrc);
5345 /// isVectorShift - Returns true if the shuffle can be implemented as a
5346 /// logical left or right shift of a vector.
5347 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5348 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5349 // Although the logic below support any bitwidth size, there are no
5350 // shift instructions which handle more than 128-bit vectors.
5351 if (!SVOp->getSimpleValueType(0).is128BitVector())
5354 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5355 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5361 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5363 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5364 unsigned NumNonZero, unsigned NumZero,
5366 const X86Subtarget* Subtarget,
5367 const TargetLowering &TLI) {
5374 for (unsigned i = 0; i < 16; ++i) {
5375 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5376 if (ThisIsNonZero && First) {
5378 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5380 V = DAG.getUNDEF(MVT::v8i16);
5385 SDValue ThisElt, LastElt;
5386 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5387 if (LastIsNonZero) {
5388 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5389 MVT::i16, Op.getOperand(i-1));
5391 if (ThisIsNonZero) {
5392 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5393 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5394 ThisElt, DAG.getConstant(8, MVT::i8));
5396 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5400 if (ThisElt.getNode())
5401 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5402 DAG.getIntPtrConstant(i/2));
5406 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5409 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5411 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5412 unsigned NumNonZero, unsigned NumZero,
5414 const X86Subtarget* Subtarget,
5415 const TargetLowering &TLI) {
5422 for (unsigned i = 0; i < 8; ++i) {
5423 bool isNonZero = (NonZeros & (1 << i)) != 0;
5427 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5429 V = DAG.getUNDEF(MVT::v8i16);
5432 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5433 MVT::v8i16, V, Op.getOperand(i),
5434 DAG.getIntPtrConstant(i));
5441 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5442 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5443 unsigned NonZeros, unsigned NumNonZero,
5444 unsigned NumZero, SelectionDAG &DAG,
5445 const X86Subtarget *Subtarget,
5446 const TargetLowering &TLI) {
5447 // We know there's at least one non-zero element
5448 unsigned FirstNonZeroIdx = 0;
5449 SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5450 while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5451 X86::isZeroNode(FirstNonZero)) {
5453 FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5456 if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5457 !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5460 SDValue V = FirstNonZero.getOperand(0);
5461 unsigned FirstNonZeroDst = cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5462 unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5463 unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5464 unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5466 for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5467 SDValue Elem = Op.getOperand(Idx);
5468 if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5471 // TODO: What else can be here? Deal with it.
5472 if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5475 // TODO: Some optimizations are still possible here
5476 // ex: Getting one element from a vector, and the rest from another.
5477 if (Elem.getOperand(0) != V)
5480 unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5483 else if (IncorrectIdx == -1U) {
5487 // There was already one element with an incorrect index.
5488 // We can't optimize this case to an insertps.
5492 if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5494 EVT VT = Op.getSimpleValueType();
5495 unsigned ElementMoveMask = 0;
5496 if (IncorrectIdx == -1U)
5497 ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5499 ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5501 SDValue InsertpsMask = DAG.getIntPtrConstant(
5502 ElementMoveMask | (~NonZeros & 0xf));
5503 return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5509 /// getVShift - Return a vector logical shift node.
5511 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5512 unsigned NumBits, SelectionDAG &DAG,
5513 const TargetLowering &TLI, SDLoc dl) {
5514 assert(VT.is128BitVector() && "Unknown type for VShift");
5515 EVT ShVT = MVT::v2i64;
5516 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5517 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5518 return DAG.getNode(ISD::BITCAST, dl, VT,
5519 DAG.getNode(Opc, dl, ShVT, SrcOp,
5520 DAG.getConstant(NumBits,
5521 TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5525 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5527 // Check if the scalar load can be widened into a vector load. And if
5528 // the address is "base + cst" see if the cst can be "absorbed" into
5529 // the shuffle mask.
5530 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5531 SDValue Ptr = LD->getBasePtr();
5532 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5534 EVT PVT = LD->getValueType(0);
5535 if (PVT != MVT::i32 && PVT != MVT::f32)
5540 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5541 FI = FINode->getIndex();
5543 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5544 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5545 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5546 Offset = Ptr.getConstantOperandVal(1);
5547 Ptr = Ptr.getOperand(0);
5552 // FIXME: 256-bit vector instructions don't require a strict alignment,
5553 // improve this code to support it better.
5554 unsigned RequiredAlign = VT.getSizeInBits()/8;
5555 SDValue Chain = LD->getChain();
5556 // Make sure the stack object alignment is at least 16 or 32.
5557 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5558 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5559 if (MFI->isFixedObjectIndex(FI)) {
5560 // Can't change the alignment. FIXME: It's possible to compute
5561 // the exact stack offset and reference FI + adjust offset instead.
5562 // If someone *really* cares about this. That's the way to implement it.
5565 MFI->setObjectAlignment(FI, RequiredAlign);
5569 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5570 // Ptr + (Offset & ~15).
5573 if ((Offset % RequiredAlign) & 3)
5575 int64_t StartOffset = Offset & ~(RequiredAlign-1);
5577 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5578 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5580 int EltNo = (Offset - StartOffset) >> 2;
5581 unsigned NumElems = VT.getVectorNumElements();
5583 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5584 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5585 LD->getPointerInfo().getWithOffset(StartOffset),
5586 false, false, false, 0);
5588 SmallVector<int, 8> Mask;
5589 for (unsigned i = 0; i != NumElems; ++i)
5590 Mask.push_back(EltNo);
5592 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5598 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5599 /// vector of type 'VT', see if the elements can be replaced by a single large
5600 /// load which has the same value as a build_vector whose operands are 'elts'.
5602 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5604 /// FIXME: we'd also like to handle the case where the last elements are zero
5605 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5606 /// There's even a handy isZeroNode for that purpose.
5607 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5608 SDLoc &DL, SelectionDAG &DAG,
5609 bool isAfterLegalize) {
5610 EVT EltVT = VT.getVectorElementType();
5611 unsigned NumElems = Elts.size();
5613 LoadSDNode *LDBase = nullptr;
5614 unsigned LastLoadedElt = -1U;
5616 // For each element in the initializer, see if we've found a load or an undef.
5617 // If we don't find an initial load element, or later load elements are
5618 // non-consecutive, bail out.
5619 for (unsigned i = 0; i < NumElems; ++i) {
5620 SDValue Elt = Elts[i];
5622 if (!Elt.getNode() ||
5623 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5626 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5628 LDBase = cast<LoadSDNode>(Elt.getNode());
5632 if (Elt.getOpcode() == ISD::UNDEF)
5635 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5636 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5641 // If we have found an entire vector of loads and undefs, then return a large
5642 // load of the entire vector width starting at the base pointer. If we found
5643 // consecutive loads for the low half, generate a vzext_load node.
5644 if (LastLoadedElt == NumElems - 1) {
5646 if (isAfterLegalize &&
5647 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5650 SDValue NewLd = SDValue();
5652 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5653 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5654 LDBase->getPointerInfo(),
5655 LDBase->isVolatile(), LDBase->isNonTemporal(),
5656 LDBase->isInvariant(), 0);
5657 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5658 LDBase->getPointerInfo(),
5659 LDBase->isVolatile(), LDBase->isNonTemporal(),
5660 LDBase->isInvariant(), LDBase->getAlignment());
5662 if (LDBase->hasAnyUseOfValue(1)) {
5663 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5665 SDValue(NewLd.getNode(), 1));
5666 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5667 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5668 SDValue(NewLd.getNode(), 1));
5673 if (NumElems == 4 && LastLoadedElt == 1 &&
5674 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5675 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5676 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5678 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5679 LDBase->getPointerInfo(),
5680 LDBase->getAlignment(),
5681 false/*isVolatile*/, true/*ReadMem*/,
5684 // Make sure the newly-created LOAD is in the same position as LDBase in
5685 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5686 // update uses of LDBase's output chain to use the TokenFactor.
5687 if (LDBase->hasAnyUseOfValue(1)) {
5688 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5689 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5690 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5691 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5692 SDValue(ResNode.getNode(), 1));
5695 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5700 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5701 /// to generate a splat value for the following cases:
5702 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5703 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5704 /// a scalar load, or a constant.
5705 /// The VBROADCAST node is returned when a pattern is found,
5706 /// or SDValue() otherwise.
5707 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5708 SelectionDAG &DAG) {
5709 if (!Subtarget->hasFp256())
5712 MVT VT = Op.getSimpleValueType();
5715 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5716 "Unsupported vector type for broadcast.");
5721 switch (Op.getOpcode()) {
5723 // Unknown pattern found.
5726 case ISD::BUILD_VECTOR: {
5727 // The BUILD_VECTOR node must be a splat.
5728 if (!isSplatVector(Op.getNode()))
5731 Ld = Op.getOperand(0);
5732 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5733 Ld.getOpcode() == ISD::ConstantFP);
5735 // The suspected load node has several users. Make sure that all
5736 // of its users are from the BUILD_VECTOR node.
5737 // Constants may have multiple users.
5738 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5743 case ISD::VECTOR_SHUFFLE: {
5744 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5746 // Shuffles must have a splat mask where the first element is
5748 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5751 SDValue Sc = Op.getOperand(0);
5752 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5753 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5755 if (!Subtarget->hasInt256())
5758 // Use the register form of the broadcast instruction available on AVX2.
5759 if (VT.getSizeInBits() >= 256)
5760 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5761 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5764 Ld = Sc.getOperand(0);
5765 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5766 Ld.getOpcode() == ISD::ConstantFP);
5768 // The scalar_to_vector node and the suspected
5769 // load node must have exactly one user.
5770 // Constants may have multiple users.
5772 // AVX-512 has register version of the broadcast
5773 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5774 Ld.getValueType().getSizeInBits() >= 32;
5775 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5782 bool IsGE256 = (VT.getSizeInBits() >= 256);
5784 // Handle the broadcasting a single constant scalar from the constant pool
5785 // into a vector. On Sandybridge it is still better to load a constant vector
5786 // from the constant pool and not to broadcast it from a scalar.
5787 if (ConstSplatVal && Subtarget->hasInt256()) {
5788 EVT CVT = Ld.getValueType();
5789 assert(!CVT.isVector() && "Must not broadcast a vector type");
5790 unsigned ScalarSize = CVT.getSizeInBits();
5792 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5793 const Constant *C = nullptr;
5794 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5795 C = CI->getConstantIntValue();
5796 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5797 C = CF->getConstantFPValue();
5799 assert(C && "Invalid constant type");
5801 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5802 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5803 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5804 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5805 MachinePointerInfo::getConstantPool(),
5806 false, false, false, Alignment);
5808 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5812 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5813 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5815 // Handle AVX2 in-register broadcasts.
5816 if (!IsLoad && Subtarget->hasInt256() &&
5817 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5818 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5820 // The scalar source must be a normal load.
5824 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5825 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5827 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5828 // double since there is no vbroadcastsd xmm
5829 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5830 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5831 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5834 // Unsupported broadcast.
5838 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5839 /// underlying vector and index.
5841 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5843 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5845 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5846 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5849 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5851 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5853 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5854 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5857 // In this case the vector is the extract_subvector expression and the index
5858 // is 2, as specified by the shuffle.
5859 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5860 SDValue ShuffleVec = SVOp->getOperand(0);
5861 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5862 assert(ShuffleVecVT.getVectorElementType() ==
5863 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5865 int ShuffleIdx = SVOp->getMaskElt(Idx);
5866 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5867 ExtractedFromVec = ShuffleVec;
5873 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5874 MVT VT = Op.getSimpleValueType();
5876 // Skip if insert_vec_elt is not supported.
5877 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5878 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5882 unsigned NumElems = Op.getNumOperands();
5886 SmallVector<unsigned, 4> InsertIndices;
5887 SmallVector<int, 8> Mask(NumElems, -1);
5889 for (unsigned i = 0; i != NumElems; ++i) {
5890 unsigned Opc = Op.getOperand(i).getOpcode();
5892 if (Opc == ISD::UNDEF)
5895 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5896 // Quit if more than 1 elements need inserting.
5897 if (InsertIndices.size() > 1)
5900 InsertIndices.push_back(i);
5904 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5905 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5906 // Quit if non-constant index.
5907 if (!isa<ConstantSDNode>(ExtIdx))
5909 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5911 // Quit if extracted from vector of different type.
5912 if (ExtractedFromVec.getValueType() != VT)
5915 if (!VecIn1.getNode())
5916 VecIn1 = ExtractedFromVec;
5917 else if (VecIn1 != ExtractedFromVec) {
5918 if (!VecIn2.getNode())
5919 VecIn2 = ExtractedFromVec;
5920 else if (VecIn2 != ExtractedFromVec)
5921 // Quit if more than 2 vectors to shuffle
5925 if (ExtractedFromVec == VecIn1)
5927 else if (ExtractedFromVec == VecIn2)
5928 Mask[i] = Idx + NumElems;
5931 if (!VecIn1.getNode())
5934 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5935 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5936 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5937 unsigned Idx = InsertIndices[i];
5938 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5939 DAG.getIntPtrConstant(Idx));
5945 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5947 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5949 MVT VT = Op.getSimpleValueType();
5950 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5951 "Unexpected type in LowerBUILD_VECTORvXi1!");
5954 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5955 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5956 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5957 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5960 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5961 SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5962 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5963 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5966 bool AllContants = true;
5967 uint64_t Immediate = 0;
5968 int NonConstIdx = -1;
5969 bool IsSplat = true;
5970 unsigned NumNonConsts = 0;
5971 unsigned NumConsts = 0;
5972 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5973 SDValue In = Op.getOperand(idx);
5974 if (In.getOpcode() == ISD::UNDEF)
5976 if (!isa<ConstantSDNode>(In)) {
5977 AllContants = false;
5983 if (cast<ConstantSDNode>(In)->getZExtValue())
5984 Immediate |= (1ULL << idx);
5986 if (In != Op.getOperand(0))
5991 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5992 DAG.getConstant(Immediate, MVT::i16));
5993 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5994 DAG.getIntPtrConstant(0));
5997 if (NumNonConsts == 1 && NonConstIdx != 0) {
6000 SDValue VecAsImm = DAG.getConstant(Immediate,
6001 MVT::getIntegerVT(VT.getSizeInBits()));
6002 DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6005 DstVec = DAG.getUNDEF(VT);
6006 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6007 Op.getOperand(NonConstIdx),
6008 DAG.getIntPtrConstant(NonConstIdx));
6010 if (!IsSplat && (NonConstIdx != 0))
6011 llvm_unreachable("Unsupported BUILD_VECTOR operation");
6012 MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6015 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6016 DAG.getConstant(-1, SelectVT),
6017 DAG.getConstant(0, SelectVT));
6019 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6020 DAG.getConstant((Immediate | 1), SelectVT),
6021 DAG.getConstant(Immediate, SelectVT));
6022 return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6026 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6029 MVT VT = Op.getSimpleValueType();
6030 MVT ExtVT = VT.getVectorElementType();
6031 unsigned NumElems = Op.getNumOperands();
6033 // Generate vectors for predicate vectors.
6034 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6035 return LowerBUILD_VECTORvXi1(Op, DAG);
6037 // Vectors containing all zeros can be matched by pxor and xorps later
6038 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6039 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6040 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6041 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6044 return getZeroVector(VT, Subtarget, DAG, dl);
6047 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6048 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6049 // vpcmpeqd on 256-bit vectors.
6050 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6051 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6054 if (!VT.is512BitVector())
6055 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6058 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6059 if (Broadcast.getNode())
6062 unsigned EVTBits = ExtVT.getSizeInBits();
6064 unsigned NumZero = 0;
6065 unsigned NumNonZero = 0;
6066 unsigned NonZeros = 0;
6067 bool IsAllConstants = true;
6068 SmallSet<SDValue, 8> Values;
6069 for (unsigned i = 0; i < NumElems; ++i) {
6070 SDValue Elt = Op.getOperand(i);
6071 if (Elt.getOpcode() == ISD::UNDEF)
6074 if (Elt.getOpcode() != ISD::Constant &&
6075 Elt.getOpcode() != ISD::ConstantFP)
6076 IsAllConstants = false;
6077 if (X86::isZeroNode(Elt))
6080 NonZeros |= (1 << i);
6085 // All undef vector. Return an UNDEF. All zero vectors were handled above.
6086 if (NumNonZero == 0)
6087 return DAG.getUNDEF(VT);
6089 // Special case for single non-zero, non-undef, element.
6090 if (NumNonZero == 1) {
6091 unsigned Idx = countTrailingZeros(NonZeros);
6092 SDValue Item = Op.getOperand(Idx);
6094 // If this is an insertion of an i64 value on x86-32, and if the top bits of
6095 // the value are obviously zero, truncate the value to i32 and do the
6096 // insertion that way. Only do this if the value is non-constant or if the
6097 // value is a constant being inserted into element 0. It is cheaper to do
6098 // a constant pool load than it is to do a movd + shuffle.
6099 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6100 (!IsAllConstants || Idx == 0)) {
6101 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6103 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6104 EVT VecVT = MVT::v4i32;
6105 unsigned VecElts = 4;
6107 // Truncate the value (which may itself be a constant) to i32, and
6108 // convert it to a vector with movd (S2V+shuffle to zero extend).
6109 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6110 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6111 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6113 // Now we have our 32-bit value zero extended in the low element of
6114 // a vector. If Idx != 0, swizzle it into place.
6116 SmallVector<int, 4> Mask;
6117 Mask.push_back(Idx);
6118 for (unsigned i = 1; i != VecElts; ++i)
6120 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6123 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6127 // If we have a constant or non-constant insertion into the low element of
6128 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6129 // the rest of the elements. This will be matched as movd/movq/movss/movsd
6130 // depending on what the source datatype is.
6133 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6135 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6136 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6137 if (VT.is256BitVector() || VT.is512BitVector()) {
6138 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6139 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6140 Item, DAG.getIntPtrConstant(0));
6142 assert(VT.is128BitVector() && "Expected an SSE value type!");
6143 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6144 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6145 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6148 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6149 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6150 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6151 if (VT.is256BitVector()) {
6152 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6153 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6155 assert(VT.is128BitVector() && "Expected an SSE value type!");
6156 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6158 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6162 // Is it a vector logical left shift?
6163 if (NumElems == 2 && Idx == 1 &&
6164 X86::isZeroNode(Op.getOperand(0)) &&
6165 !X86::isZeroNode(Op.getOperand(1))) {
6166 unsigned NumBits = VT.getSizeInBits();
6167 return getVShift(true, VT,
6168 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6169 VT, Op.getOperand(1)),
6170 NumBits/2, DAG, *this, dl);
6173 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6176 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6177 // is a non-constant being inserted into an element other than the low one,
6178 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6179 // movd/movss) to move this into the low element, then shuffle it into
6181 if (EVTBits == 32) {
6182 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6184 // Turn it into a shuffle of zero and zero-extended scalar to vector.
6185 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6186 SmallVector<int, 8> MaskVec;
6187 for (unsigned i = 0; i != NumElems; ++i)
6188 MaskVec.push_back(i == Idx ? 0 : 1);
6189 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6193 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6194 if (Values.size() == 1) {
6195 if (EVTBits == 32) {
6196 // Instead of a shuffle like this:
6197 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6198 // Check if it's possible to issue this instead.
6199 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6200 unsigned Idx = countTrailingZeros(NonZeros);
6201 SDValue Item = Op.getOperand(Idx);
6202 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6203 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6208 // A vector full of immediates; various special cases are already
6209 // handled, so this is best done with a single constant-pool load.
6213 // For AVX-length vectors, build the individual 128-bit pieces and use
6214 // shuffles to put them in place.
6215 if (VT.is256BitVector() || VT.is512BitVector()) {
6216 SmallVector<SDValue, 64> V;
6217 for (unsigned i = 0; i != NumElems; ++i)
6218 V.push_back(Op.getOperand(i));
6220 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6222 // Build both the lower and upper subvector.
6223 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6224 makeArrayRef(&V[0], NumElems/2));
6225 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6226 makeArrayRef(&V[NumElems / 2], NumElems/2));
6228 // Recreate the wider vector with the lower and upper part.
6229 if (VT.is256BitVector())
6230 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6231 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6234 // Let legalizer expand 2-wide build_vectors.
6235 if (EVTBits == 64) {
6236 if (NumNonZero == 1) {
6237 // One half is zero or undef.
6238 unsigned Idx = countTrailingZeros(NonZeros);
6239 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6240 Op.getOperand(Idx));
6241 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6246 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6247 if (EVTBits == 8 && NumElems == 16) {
6248 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6250 if (V.getNode()) return V;
6253 if (EVTBits == 16 && NumElems == 8) {
6254 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6256 if (V.getNode()) return V;
6259 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6260 if (EVTBits == 32 && NumElems == 4) {
6261 SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6262 NumZero, DAG, Subtarget, *this);
6267 // If element VT is == 32 bits, turn it into a number of shuffles.
6268 SmallVector<SDValue, 8> V(NumElems);
6269 if (NumElems == 4 && NumZero > 0) {
6270 for (unsigned i = 0; i < 4; ++i) {
6271 bool isZero = !(NonZeros & (1 << i));
6273 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6275 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6278 for (unsigned i = 0; i < 2; ++i) {
6279 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6282 V[i] = V[i*2]; // Must be a zero vector.
6285 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6288 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6291 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6296 bool Reverse1 = (NonZeros & 0x3) == 2;
6297 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6301 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6302 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6304 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6307 if (Values.size() > 1 && VT.is128BitVector()) {
6308 // Check for a build vector of consecutive loads.
6309 for (unsigned i = 0; i < NumElems; ++i)
6310 V[i] = Op.getOperand(i);
6312 // Check for elements which are consecutive loads.
6313 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6317 // Check for a build vector from mostly shuffle plus few inserting.
6318 SDValue Sh = buildFromShuffleMostly(Op, DAG);
6322 // For SSE 4.1, use insertps to put the high elements into the low element.
6323 if (getSubtarget()->hasSSE41()) {
6325 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6326 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6328 Result = DAG.getUNDEF(VT);
6330 for (unsigned i = 1; i < NumElems; ++i) {
6331 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6332 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6333 Op.getOperand(i), DAG.getIntPtrConstant(i));
6338 // Otherwise, expand into a number of unpckl*, start by extending each of
6339 // our (non-undef) elements to the full vector width with the element in the
6340 // bottom slot of the vector (which generates no code for SSE).
6341 for (unsigned i = 0; i < NumElems; ++i) {
6342 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6343 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6345 V[i] = DAG.getUNDEF(VT);
6348 // Next, we iteratively mix elements, e.g. for v4f32:
6349 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6350 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6351 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6352 unsigned EltStride = NumElems >> 1;
6353 while (EltStride != 0) {
6354 for (unsigned i = 0; i < EltStride; ++i) {
6355 // If V[i+EltStride] is undef and this is the first round of mixing,
6356 // then it is safe to just drop this shuffle: V[i] is already in the
6357 // right place, the one element (since it's the first round) being
6358 // inserted as undef can be dropped. This isn't safe for successive
6359 // rounds because they will permute elements within both vectors.
6360 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6361 EltStride == NumElems/2)
6364 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6373 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6374 // to create 256-bit vectors from two other 128-bit ones.
6375 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6377 MVT ResVT = Op.getSimpleValueType();
6379 assert((ResVT.is256BitVector() ||
6380 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6382 SDValue V1 = Op.getOperand(0);
6383 SDValue V2 = Op.getOperand(1);
6384 unsigned NumElems = ResVT.getVectorNumElements();
6385 if(ResVT.is256BitVector())
6386 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6388 if (Op.getNumOperands() == 4) {
6389 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6390 ResVT.getVectorNumElements()/2);
6391 SDValue V3 = Op.getOperand(2);
6392 SDValue V4 = Op.getOperand(3);
6393 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6394 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6396 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6399 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6400 MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6401 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6402 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6403 Op.getNumOperands() == 4)));
6405 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6406 // from two other 128-bit ones.
6408 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6409 return LowerAVXCONCAT_VECTORS(Op, DAG);
6412 // Try to lower a shuffle node into a simple blend instruction.
6414 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6415 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6416 SDValue V1 = SVOp->getOperand(0);
6417 SDValue V2 = SVOp->getOperand(1);
6419 MVT VT = SVOp->getSimpleValueType(0);
6420 MVT EltVT = VT.getVectorElementType();
6421 unsigned NumElems = VT.getVectorNumElements();
6423 // There is no blend with immediate in AVX-512.
6424 if (VT.is512BitVector())
6427 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
6429 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
6432 // Check the mask for BLEND and build the value.
6433 unsigned MaskValue = 0;
6434 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6435 unsigned NumLanes = (NumElems-1)/8 + 1;
6436 unsigned NumElemsInLane = NumElems / NumLanes;
6438 // Blend for v16i16 should be symetric for the both lanes.
6439 for (unsigned i = 0; i < NumElemsInLane; ++i) {
6441 int SndLaneEltIdx = (NumLanes == 2) ?
6442 SVOp->getMaskElt(i + NumElemsInLane) : -1;
6443 int EltIdx = SVOp->getMaskElt(i);
6445 if ((EltIdx < 0 || EltIdx == (int)i) &&
6446 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6449 if (((unsigned)EltIdx == (i + NumElems)) &&
6450 (SndLaneEltIdx < 0 ||
6451 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6452 MaskValue |= (1<<i);
6457 // Convert i32 vectors to floating point if it is not AVX2.
6458 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6460 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6461 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6463 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6464 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6467 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6468 DAG.getConstant(MaskValue, MVT::i32));
6469 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6472 /// In vector type \p VT, return true if the element at index \p InputIdx
6473 /// falls on a different 128-bit lane than \p OutputIdx.
6474 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
6475 unsigned OutputIdx) {
6476 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6477 return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
6480 /// Generate a PSHUFB if possible. Selects elements from \p V1 according to
6481 /// \p MaskVals. MaskVals[OutputIdx] = InputIdx specifies that we want to
6482 /// shuffle the element at InputIdx in V1 to OutputIdx in the result. If \p
6483 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
6485 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
6486 SelectionDAG &DAG) {
6487 MVT VT = V1.getSimpleValueType();
6488 assert(VT.is128BitVector() || VT.is256BitVector());
6490 MVT EltVT = VT.getVectorElementType();
6491 unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
6492 unsigned NumElts = VT.getVectorNumElements();
6494 SmallVector<SDValue, 32> PshufbMask;
6495 for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
6496 int InputIdx = MaskVals[OutputIdx];
6497 unsigned InputByteIdx;
6499 if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
6500 InputByteIdx = 0x80;
6502 // Cross lane is not allowed.
6503 if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
6505 InputByteIdx = InputIdx * EltSizeInBytes;
6506 // Index is an byte offset within the 128-bit lane.
6507 InputByteIdx &= 0xf;
6510 for (unsigned j = 0; j < EltSizeInBytes; ++j) {
6511 PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
6512 if (InputByteIdx != 0x80)
6517 MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
6519 V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
6520 return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
6521 DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
6524 // v8i16 shuffles - Prefer shuffles in the following order:
6525 // 1. [all] pshuflw, pshufhw, optional move
6526 // 2. [ssse3] 1 x pshufb
6527 // 3. [ssse3] 2 x pshufb + 1 x por
6528 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6530 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6531 SelectionDAG &DAG) {
6532 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6533 SDValue V1 = SVOp->getOperand(0);
6534 SDValue V2 = SVOp->getOperand(1);
6536 SmallVector<int, 8> MaskVals;
6538 // Determine if more than 1 of the words in each of the low and high quadwords
6539 // of the result come from the same quadword of one of the two inputs. Undef
6540 // mask values count as coming from any quadword, for better codegen.
6542 // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
6543 // feeds this quad. For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
6544 unsigned LoQuad[] = { 0, 0, 0, 0 };
6545 unsigned HiQuad[] = { 0, 0, 0, 0 };
6546 // Indices of quads used.
6547 std::bitset<4> InputQuads;
6548 for (unsigned i = 0; i < 8; ++i) {
6549 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6550 int EltIdx = SVOp->getMaskElt(i);
6551 MaskVals.push_back(EltIdx);
6560 InputQuads.set(EltIdx / 4);
6563 int BestLoQuad = -1;
6564 unsigned MaxQuad = 1;
6565 for (unsigned i = 0; i < 4; ++i) {
6566 if (LoQuad[i] > MaxQuad) {
6568 MaxQuad = LoQuad[i];
6572 int BestHiQuad = -1;
6574 for (unsigned i = 0; i < 4; ++i) {
6575 if (HiQuad[i] > MaxQuad) {
6577 MaxQuad = HiQuad[i];
6581 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6582 // of the two input vectors, shuffle them into one input vector so only a
6583 // single pshufb instruction is necessary. If there are more than 2 input
6584 // quads, disable the next transformation since it does not help SSSE3.
6585 bool V1Used = InputQuads[0] || InputQuads[1];
6586 bool V2Used = InputQuads[2] || InputQuads[3];
6587 if (Subtarget->hasSSSE3()) {
6588 if (InputQuads.count() == 2 && V1Used && V2Used) {
6589 BestLoQuad = InputQuads[0] ? 0 : 1;
6590 BestHiQuad = InputQuads[2] ? 2 : 3;
6592 if (InputQuads.count() > 2) {
6598 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6599 // the shuffle mask. If a quad is scored as -1, that means that it contains
6600 // words from all 4 input quadwords.
6602 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6604 BestLoQuad < 0 ? 0 : BestLoQuad,
6605 BestHiQuad < 0 ? 1 : BestHiQuad
6607 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6608 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6609 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6610 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6612 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6613 // source words for the shuffle, to aid later transformations.
6614 bool AllWordsInNewV = true;
6615 bool InOrder[2] = { true, true };
6616 for (unsigned i = 0; i != 8; ++i) {
6617 int idx = MaskVals[i];
6619 InOrder[i/4] = false;
6620 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6622 AllWordsInNewV = false;
6626 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6627 if (AllWordsInNewV) {
6628 for (int i = 0; i != 8; ++i) {
6629 int idx = MaskVals[i];
6632 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6633 if ((idx != i) && idx < 4)
6635 if ((idx != i) && idx > 3)
6644 // If we've eliminated the use of V2, and the new mask is a pshuflw or
6645 // pshufhw, that's as cheap as it gets. Return the new shuffle.
6646 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6647 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6648 unsigned TargetMask = 0;
6649 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6650 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6651 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6652 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6653 getShufflePSHUFLWImmediate(SVOp);
6654 V1 = NewV.getOperand(0);
6655 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6659 // Promote splats to a larger type which usually leads to more efficient code.
6660 // FIXME: Is this true if pshufb is available?
6661 if (SVOp->isSplat())
6662 return PromoteSplat(SVOp, DAG);
6664 // If we have SSSE3, and all words of the result are from 1 input vector,
6665 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
6666 // is present, fall back to case 4.
6667 if (Subtarget->hasSSSE3()) {
6668 SmallVector<SDValue,16> pshufbMask;
6670 // If we have elements from both input vectors, set the high bit of the
6671 // shuffle mask element to zero out elements that come from V2 in the V1
6672 // mask, and elements that come from V1 in the V2 mask, so that the two
6673 // results can be OR'd together.
6674 bool TwoInputs = V1Used && V2Used;
6675 V1 = getPSHUFB(MaskVals, V1, dl, DAG);
6677 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6679 // Calculate the shuffle mask for the second input, shuffle it, and
6680 // OR it with the first shuffled input.
6681 CommuteVectorShuffleMask(MaskVals, 8);
6682 V2 = getPSHUFB(MaskVals, V2, dl, DAG);
6683 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6684 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6687 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6688 // and update MaskVals with new element order.
6689 std::bitset<8> InOrder;
6690 if (BestLoQuad >= 0) {
6691 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6692 for (int i = 0; i != 4; ++i) {
6693 int idx = MaskVals[i];
6696 } else if ((idx / 4) == BestLoQuad) {
6701 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6704 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6705 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6706 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6708 getShufflePSHUFLWImmediate(SVOp), DAG);
6712 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6713 // and update MaskVals with the new element order.
6714 if (BestHiQuad >= 0) {
6715 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6716 for (unsigned i = 4; i != 8; ++i) {
6717 int idx = MaskVals[i];
6720 } else if ((idx / 4) == BestHiQuad) {
6721 MaskV[i] = (idx & 3) + 4;
6725 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6728 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6729 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6730 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6732 getShufflePSHUFHWImmediate(SVOp), DAG);
6736 // In case BestHi & BestLo were both -1, which means each quadword has a word
6737 // from each of the four input quadwords, calculate the InOrder bitvector now
6738 // before falling through to the insert/extract cleanup.
6739 if (BestLoQuad == -1 && BestHiQuad == -1) {
6741 for (int i = 0; i != 8; ++i)
6742 if (MaskVals[i] < 0 || MaskVals[i] == i)
6746 // The other elements are put in the right place using pextrw and pinsrw.
6747 for (unsigned i = 0; i != 8; ++i) {
6750 int EltIdx = MaskVals[i];
6753 SDValue ExtOp = (EltIdx < 8) ?
6754 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6755 DAG.getIntPtrConstant(EltIdx)) :
6756 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6757 DAG.getIntPtrConstant(EltIdx - 8));
6758 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6759 DAG.getIntPtrConstant(i));
6764 /// \brief v16i16 shuffles
6766 /// FIXME: We only support generation of a single pshufb currently. We can
6767 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
6768 /// well (e.g 2 x pshufb + 1 x por).
6770 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
6771 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6772 SDValue V1 = SVOp->getOperand(0);
6773 SDValue V2 = SVOp->getOperand(1);
6776 if (V2.getOpcode() != ISD::UNDEF)
6779 SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6780 return getPSHUFB(MaskVals, V1, dl, DAG);
6783 // v16i8 shuffles - Prefer shuffles in the following order:
6784 // 1. [ssse3] 1 x pshufb
6785 // 2. [ssse3] 2 x pshufb + 1 x por
6786 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
6787 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6788 const X86Subtarget* Subtarget,
6789 SelectionDAG &DAG) {
6790 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6791 SDValue V1 = SVOp->getOperand(0);
6792 SDValue V2 = SVOp->getOperand(1);
6794 ArrayRef<int> MaskVals = SVOp->getMask();
6796 // Promote splats to a larger type which usually leads to more efficient code.
6797 // FIXME: Is this true if pshufb is available?
6798 if (SVOp->isSplat())
6799 return PromoteSplat(SVOp, DAG);
6801 // If we have SSSE3, case 1 is generated when all result bytes come from
6802 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
6803 // present, fall back to case 3.
6805 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6806 if (Subtarget->hasSSSE3()) {
6807 SmallVector<SDValue,16> pshufbMask;
6809 // If all result elements are from one input vector, then only translate
6810 // undef mask values to 0x80 (zero out result) in the pshufb mask.
6812 // Otherwise, we have elements from both input vectors, and must zero out
6813 // elements that come from V2 in the first mask, and V1 in the second mask
6814 // so that we can OR them together.
6815 for (unsigned i = 0; i != 16; ++i) {
6816 int EltIdx = MaskVals[i];
6817 if (EltIdx < 0 || EltIdx >= 16)
6819 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6821 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6822 DAG.getNode(ISD::BUILD_VECTOR, dl,
6823 MVT::v16i8, pshufbMask));
6825 // As PSHUFB will zero elements with negative indices, it's safe to ignore
6826 // the 2nd operand if it's undefined or zero.
6827 if (V2.getOpcode() == ISD::UNDEF ||
6828 ISD::isBuildVectorAllZeros(V2.getNode()))
6831 // Calculate the shuffle mask for the second input, shuffle it, and
6832 // OR it with the first shuffled input.
6834 for (unsigned i = 0; i != 16; ++i) {
6835 int EltIdx = MaskVals[i];
6836 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6837 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6839 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6840 DAG.getNode(ISD::BUILD_VECTOR, dl,
6841 MVT::v16i8, pshufbMask));
6842 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6845 // No SSSE3 - Calculate in place words and then fix all out of place words
6846 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
6847 // the 16 different words that comprise the two doublequadword input vectors.
6848 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6849 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6851 for (int i = 0; i != 8; ++i) {
6852 int Elt0 = MaskVals[i*2];
6853 int Elt1 = MaskVals[i*2+1];
6855 // This word of the result is all undef, skip it.
6856 if (Elt0 < 0 && Elt1 < 0)
6859 // This word of the result is already in the correct place, skip it.
6860 if ((Elt0 == i*2) && (Elt1 == i*2+1))
6863 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6864 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6867 // If Elt0 and Elt1 are defined, are consecutive, and can be load
6868 // using a single extract together, load it and store it.
6869 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6870 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6871 DAG.getIntPtrConstant(Elt1 / 2));
6872 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6873 DAG.getIntPtrConstant(i));
6877 // If Elt1 is defined, extract it from the appropriate source. If the
6878 // source byte is not also odd, shift the extracted word left 8 bits
6879 // otherwise clear the bottom 8 bits if we need to do an or.
6881 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6882 DAG.getIntPtrConstant(Elt1 / 2));
6883 if ((Elt1 & 1) == 0)
6884 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6886 TLI.getShiftAmountTy(InsElt.getValueType())));
6888 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6889 DAG.getConstant(0xFF00, MVT::i16));
6891 // If Elt0 is defined, extract it from the appropriate source. If the
6892 // source byte is not also even, shift the extracted word right 8 bits. If
6893 // Elt1 was also defined, OR the extracted values together before
6894 // inserting them in the result.
6896 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6897 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6898 if ((Elt0 & 1) != 0)
6899 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6901 TLI.getShiftAmountTy(InsElt0.getValueType())));
6903 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6904 DAG.getConstant(0x00FF, MVT::i16));
6905 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6908 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6909 DAG.getIntPtrConstant(i));
6911 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6914 // v32i8 shuffles - Translate to VPSHUFB if possible.
6916 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6917 const X86Subtarget *Subtarget,
6918 SelectionDAG &DAG) {
6919 MVT VT = SVOp->getSimpleValueType(0);
6920 SDValue V1 = SVOp->getOperand(0);
6921 SDValue V2 = SVOp->getOperand(1);
6923 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6925 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6926 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6927 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6929 // VPSHUFB may be generated if
6930 // (1) one of input vector is undefined or zeroinitializer.
6931 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6932 // And (2) the mask indexes don't cross the 128-bit lane.
6933 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6934 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6937 if (V1IsAllZero && !V2IsAllZero) {
6938 CommuteVectorShuffleMask(MaskVals, 32);
6941 return getPSHUFB(MaskVals, V1, dl, DAG);
6944 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6945 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6946 /// done when every pair / quad of shuffle mask elements point to elements in
6947 /// the right sequence. e.g.
6948 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6950 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6951 SelectionDAG &DAG) {
6952 MVT VT = SVOp->getSimpleValueType(0);
6954 unsigned NumElems = VT.getVectorNumElements();
6957 switch (VT.SimpleTy) {
6958 default: llvm_unreachable("Unexpected!");
6961 return SDValue(SVOp, 0);
6962 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
6963 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
6964 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
6965 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
6966 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6967 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
6970 SmallVector<int, 8> MaskVec;
6971 for (unsigned i = 0; i != NumElems; i += Scale) {
6973 for (unsigned j = 0; j != Scale; ++j) {
6974 int EltIdx = SVOp->getMaskElt(i+j);
6978 StartIdx = (EltIdx / Scale);
6979 if (EltIdx != (int)(StartIdx*Scale + j))
6982 MaskVec.push_back(StartIdx);
6985 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6986 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6987 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6990 /// getVZextMovL - Return a zero-extending vector move low node.
6992 static SDValue getVZextMovL(MVT VT, MVT OpVT,
6993 SDValue SrcOp, SelectionDAG &DAG,
6994 const X86Subtarget *Subtarget, SDLoc dl) {
6995 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6996 LoadSDNode *LD = nullptr;
6997 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6998 LD = dyn_cast<LoadSDNode>(SrcOp);
7000 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
7002 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
7003 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
7004 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
7005 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
7006 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
7008 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
7009 return DAG.getNode(ISD::BITCAST, dl, VT,
7010 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
7011 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7019 return DAG.getNode(ISD::BITCAST, dl, VT,
7020 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
7021 DAG.getNode(ISD::BITCAST, dl,
7025 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
7026 /// which could not be matched by any known target speficic shuffle
7028 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7030 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
7031 if (NewOp.getNode())
7034 MVT VT = SVOp->getSimpleValueType(0);
7036 unsigned NumElems = VT.getVectorNumElements();
7037 unsigned NumLaneElems = NumElems / 2;
7040 MVT EltVT = VT.getVectorElementType();
7041 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
7044 SmallVector<int, 16> Mask;
7045 for (unsigned l = 0; l < 2; ++l) {
7046 // Build a shuffle mask for the output, discovering on the fly which
7047 // input vectors to use as shuffle operands (recorded in InputUsed).
7048 // If building a suitable shuffle vector proves too hard, then bail
7049 // out with UseBuildVector set.
7050 bool UseBuildVector = false;
7051 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
7052 unsigned LaneStart = l * NumLaneElems;
7053 for (unsigned i = 0; i != NumLaneElems; ++i) {
7054 // The mask element. This indexes into the input.
7055 int Idx = SVOp->getMaskElt(i+LaneStart);
7057 // the mask element does not index into any input vector.
7062 // The input vector this mask element indexes into.
7063 int Input = Idx / NumLaneElems;
7065 // Turn the index into an offset from the start of the input vector.
7066 Idx -= Input * NumLaneElems;
7068 // Find or create a shuffle vector operand to hold this input.
7070 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
7071 if (InputUsed[OpNo] == Input)
7072 // This input vector is already an operand.
7074 if (InputUsed[OpNo] < 0) {
7075 // Create a new operand for this input vector.
7076 InputUsed[OpNo] = Input;
7081 if (OpNo >= array_lengthof(InputUsed)) {
7082 // More than two input vectors used! Give up on trying to create a
7083 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
7084 UseBuildVector = true;
7088 // Add the mask index for the new shuffle vector.
7089 Mask.push_back(Idx + OpNo * NumLaneElems);
7092 if (UseBuildVector) {
7093 SmallVector<SDValue, 16> SVOps;
7094 for (unsigned i = 0; i != NumLaneElems; ++i) {
7095 // The mask element. This indexes into the input.
7096 int Idx = SVOp->getMaskElt(i+LaneStart);
7098 SVOps.push_back(DAG.getUNDEF(EltVT));
7102 // The input vector this mask element indexes into.
7103 int Input = Idx / NumElems;
7105 // Turn the index into an offset from the start of the input vector.
7106 Idx -= Input * NumElems;
7108 // Extract the vector element by hand.
7109 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
7110 SVOp->getOperand(Input),
7111 DAG.getIntPtrConstant(Idx)));
7114 // Construct the output using a BUILD_VECTOR.
7115 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
7116 } else if (InputUsed[0] < 0) {
7117 // No input vectors were used! The result is undefined.
7118 Output[l] = DAG.getUNDEF(NVT);
7120 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
7121 (InputUsed[0] % 2) * NumLaneElems,
7123 // If only one input was used, use an undefined vector for the other.
7124 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
7125 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
7126 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
7127 // At least one input vector was used. Create a new shuffle vector.
7128 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
7134 // Concatenate the result back
7135 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
7138 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
7139 /// 4 elements, and match them with several different shuffle types.
7141 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7142 SDValue V1 = SVOp->getOperand(0);
7143 SDValue V2 = SVOp->getOperand(1);
7145 MVT VT = SVOp->getSimpleValueType(0);
7147 assert(VT.is128BitVector() && "Unsupported vector size");
7149 std::pair<int, int> Locs[4];
7150 int Mask1[] = { -1, -1, -1, -1 };
7151 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
7155 for (unsigned i = 0; i != 4; ++i) {
7156 int Idx = PermMask[i];
7158 Locs[i] = std::make_pair(-1, -1);
7160 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
7162 Locs[i] = std::make_pair(0, NumLo);
7166 Locs[i] = std::make_pair(1, NumHi);
7168 Mask1[2+NumHi] = Idx;
7174 if (NumLo <= 2 && NumHi <= 2) {
7175 // If no more than two elements come from either vector. This can be
7176 // implemented with two shuffles. First shuffle gather the elements.
7177 // The second shuffle, which takes the first shuffle as both of its
7178 // vector operands, put the elements into the right order.
7179 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7181 int Mask2[] = { -1, -1, -1, -1 };
7183 for (unsigned i = 0; i != 4; ++i)
7184 if (Locs[i].first != -1) {
7185 unsigned Idx = (i < 2) ? 0 : 4;
7186 Idx += Locs[i].first * 2 + Locs[i].second;
7190 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
7193 if (NumLo == 3 || NumHi == 3) {
7194 // Otherwise, we must have three elements from one vector, call it X, and
7195 // one element from the other, call it Y. First, use a shufps to build an
7196 // intermediate vector with the one element from Y and the element from X
7197 // that will be in the same half in the final destination (the indexes don't
7198 // matter). Then, use a shufps to build the final vector, taking the half
7199 // containing the element from Y from the intermediate, and the other half
7202 // Normalize it so the 3 elements come from V1.
7203 CommuteVectorShuffleMask(PermMask, 4);
7207 // Find the element from V2.
7209 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
7210 int Val = PermMask[HiIndex];
7217 Mask1[0] = PermMask[HiIndex];
7219 Mask1[2] = PermMask[HiIndex^1];
7221 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7224 Mask1[0] = PermMask[0];
7225 Mask1[1] = PermMask[1];
7226 Mask1[2] = HiIndex & 1 ? 6 : 4;
7227 Mask1[3] = HiIndex & 1 ? 4 : 6;
7228 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7231 Mask1[0] = HiIndex & 1 ? 2 : 0;
7232 Mask1[1] = HiIndex & 1 ? 0 : 2;
7233 Mask1[2] = PermMask[2];
7234 Mask1[3] = PermMask[3];
7239 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7242 // Break it into (shuffle shuffle_hi, shuffle_lo).
7243 int LoMask[] = { -1, -1, -1, -1 };
7244 int HiMask[] = { -1, -1, -1, -1 };
7246 int *MaskPtr = LoMask;
7247 unsigned MaskIdx = 0;
7250 for (unsigned i = 0; i != 4; ++i) {
7257 int Idx = PermMask[i];
7259 Locs[i] = std::make_pair(-1, -1);
7260 } else if (Idx < 4) {
7261 Locs[i] = std::make_pair(MaskIdx, LoIdx);
7262 MaskPtr[LoIdx] = Idx;
7265 Locs[i] = std::make_pair(MaskIdx, HiIdx);
7266 MaskPtr[HiIdx] = Idx;
7271 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7272 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7273 int MaskOps[] = { -1, -1, -1, -1 };
7274 for (unsigned i = 0; i != 4; ++i)
7275 if (Locs[i].first != -1)
7276 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7277 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7280 static bool MayFoldVectorLoad(SDValue V) {
7281 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7282 V = V.getOperand(0);
7284 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7285 V = V.getOperand(0);
7286 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7287 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7288 // BUILD_VECTOR (load), undef
7289 V = V.getOperand(0);
7291 return MayFoldLoad(V);
7295 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7296 MVT VT = Op.getSimpleValueType();
7298 // Canonizalize to v2f64.
7299 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7300 return DAG.getNode(ISD::BITCAST, dl, VT,
7301 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7306 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7308 SDValue V1 = Op.getOperand(0);
7309 SDValue V2 = Op.getOperand(1);
7310 MVT VT = Op.getSimpleValueType();
7312 assert(VT != MVT::v2i64 && "unsupported shuffle type");
7314 if (HasSSE2 && VT == MVT::v2f64)
7315 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7317 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7318 return DAG.getNode(ISD::BITCAST, dl, VT,
7319 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7320 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7321 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7325 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7326 SDValue V1 = Op.getOperand(0);
7327 SDValue V2 = Op.getOperand(1);
7328 MVT VT = Op.getSimpleValueType();
7330 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7331 "unsupported shuffle type");
7333 if (V2.getOpcode() == ISD::UNDEF)
7337 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7341 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7342 SDValue V1 = Op.getOperand(0);
7343 SDValue V2 = Op.getOperand(1);
7344 MVT VT = Op.getSimpleValueType();
7345 unsigned NumElems = VT.getVectorNumElements();
7347 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7348 // operand of these instructions is only memory, so check if there's a
7349 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7351 bool CanFoldLoad = false;
7353 // Trivial case, when V2 comes from a load.
7354 if (MayFoldVectorLoad(V2))
7357 // When V1 is a load, it can be folded later into a store in isel, example:
7358 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7360 // (MOVLPSmr addr:$src1, VR128:$src2)
7361 // So, recognize this potential and also use MOVLPS or MOVLPD
7362 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7365 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7367 if (HasSSE2 && NumElems == 2)
7368 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7371 // If we don't care about the second element, proceed to use movss.
7372 if (SVOp->getMaskElt(1) != -1)
7373 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7376 // movl and movlp will both match v2i64, but v2i64 is never matched by
7377 // movl earlier because we make it strict to avoid messing with the movlp load
7378 // folding logic (see the code above getMOVLP call). Match it here then,
7379 // this is horrible, but will stay like this until we move all shuffle
7380 // matching to x86 specific nodes. Note that for the 1st condition all
7381 // types are matched with movsd.
7383 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7384 // as to remove this logic from here, as much as possible
7385 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7386 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7387 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7390 assert(VT != MVT::v4i32 && "unsupported shuffle type");
7392 // Invert the operand order and use SHUFPS to match it.
7393 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7394 getShuffleSHUFImmediate(SVOp), DAG);
7397 // It is only safe to call this function if isINSERTPSMask is true for
7398 // this shufflevector mask.
7399 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
7400 SelectionDAG &DAG) {
7401 // Generate an insertps instruction when inserting an f32 from memory onto a
7402 // v4f32 or when copying a member from one v4f32 to another.
7403 // We also use it for transferring i32 from one register to another,
7404 // since it simply copies the same bits.
7405 // If we're transfering an i32 from memory to a specific element in a
7406 // register, we output a generic DAG that will match the PINSRD
7408 // TODO: Optimize for AVX cases too (VINSERTPS)
7409 MVT VT = SVOp->getSimpleValueType(0);
7410 MVT EVT = VT.getVectorElementType();
7411 SDValue V1 = SVOp->getOperand(0);
7412 SDValue V2 = SVOp->getOperand(1);
7413 auto Mask = SVOp->getMask();
7414 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
7415 "unsupported vector type for insertps/pinsrd");
7417 int FromV1 = std::count_if(Mask.begin(), Mask.end(),
7418 [](const int &i) { return i < 4; });
7426 DestIndex = std::find_if(Mask.begin(), Mask.end(),
7427 [](const int &i) { return i < 4; }) -
7432 DestIndex = std::find_if(Mask.begin(), Mask.end(),
7433 [](const int &i) { return i >= 4; }) -
7437 if (MayFoldLoad(From)) {
7438 // Trivial case, when From comes from a load and is only used by the
7439 // shuffle. Make it use insertps from the vector that we need from that
7441 SDValue Addr = From.getOperand(1);
7443 DAG.getNode(ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
7444 DAG.getConstant(DestIndex * EVT.getStoreSize(),
7445 Addr.getSimpleValueType()));
7447 LoadSDNode *Load = cast<LoadSDNode>(From);
7449 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
7450 DAG.getMachineFunction().getMachineMemOperand(
7451 Load->getMemOperand(), 0, EVT.getStoreSize()));
7453 if (EVT == MVT::f32) {
7454 // Create this as a scalar to vector to match the instruction pattern.
7455 SDValue LoadScalarToVector =
7456 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
7457 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
7458 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
7460 } else { // EVT == MVT::i32
7461 // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
7462 // instruction, to match the PINSRD instruction, which loads an i32 to a
7463 // certain vector element.
7464 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
7465 DAG.getConstant(DestIndex, MVT::i32));
7469 // Vector-element-to-vector
7470 unsigned SrcIndex = Mask[DestIndex] % 4;
7471 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
7472 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
7475 // Reduce a vector shuffle to zext.
7476 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7477 SelectionDAG &DAG) {
7478 // PMOVZX is only available from SSE41.
7479 if (!Subtarget->hasSSE41())
7482 MVT VT = Op.getSimpleValueType();
7484 // Only AVX2 support 256-bit vector integer extending.
7485 if (!Subtarget->hasInt256() && VT.is256BitVector())
7488 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7490 SDValue V1 = Op.getOperand(0);
7491 SDValue V2 = Op.getOperand(1);
7492 unsigned NumElems = VT.getVectorNumElements();
7494 // Extending is an unary operation and the element type of the source vector
7495 // won't be equal to or larger than i64.
7496 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7497 VT.getVectorElementType() == MVT::i64)
7500 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7501 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7502 while ((1U << Shift) < NumElems) {
7503 if (SVOp->getMaskElt(1U << Shift) == 1)
7506 // The maximal ratio is 8, i.e. from i8 to i64.
7511 // Check the shuffle mask.
7512 unsigned Mask = (1U << Shift) - 1;
7513 for (unsigned i = 0; i != NumElems; ++i) {
7514 int EltIdx = SVOp->getMaskElt(i);
7515 if ((i & Mask) != 0 && EltIdx != -1)
7517 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7521 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7522 MVT NeVT = MVT::getIntegerVT(NBits);
7523 MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7525 if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7528 // Simplify the operand as it's prepared to be fed into shuffle.
7529 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7530 if (V1.getOpcode() == ISD::BITCAST &&
7531 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7532 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7533 V1.getOperand(0).getOperand(0)
7534 .getSimpleValueType().getSizeInBits() == SignificantBits) {
7535 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7536 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7537 ConstantSDNode *CIdx =
7538 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7539 // If it's foldable, i.e. normal load with single use, we will let code
7540 // selection to fold it. Otherwise, we will short the conversion sequence.
7541 if (CIdx && CIdx->getZExtValue() == 0 &&
7542 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7543 MVT FullVT = V.getSimpleValueType();
7544 MVT V1VT = V1.getSimpleValueType();
7545 if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7546 // The "ext_vec_elt" node is wider than the result node.
7547 // In this case we should extract subvector from V.
7548 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7549 unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7550 MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7551 FullVT.getVectorNumElements()/Ratio);
7552 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7553 DAG.getIntPtrConstant(0));
7555 V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7559 return DAG.getNode(ISD::BITCAST, DL, VT,
7560 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7563 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7564 SelectionDAG &DAG) {
7565 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7566 MVT VT = Op.getSimpleValueType();
7568 SDValue V1 = Op.getOperand(0);
7569 SDValue V2 = Op.getOperand(1);
7571 if (isZeroShuffle(SVOp))
7572 return getZeroVector(VT, Subtarget, DAG, dl);
7574 // Handle splat operations
7575 if (SVOp->isSplat()) {
7576 // Use vbroadcast whenever the splat comes from a foldable load
7577 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7578 if (Broadcast.getNode())
7582 // Check integer expanding shuffles.
7583 SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7584 if (NewOp.getNode())
7587 // If the shuffle can be profitably rewritten as a narrower shuffle, then
7589 if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
7591 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7592 if (NewOp.getNode())
7593 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7594 } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
7595 // FIXME: Figure out a cleaner way to do this.
7596 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7597 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7598 if (NewOp.getNode()) {
7599 MVT NewVT = NewOp.getSimpleValueType();
7600 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7601 NewVT, true, false))
7602 return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
7605 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7606 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7607 if (NewOp.getNode()) {
7608 MVT NewVT = NewOp.getSimpleValueType();
7609 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7610 return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
7619 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7620 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7621 SDValue V1 = Op.getOperand(0);
7622 SDValue V2 = Op.getOperand(1);
7623 MVT VT = Op.getSimpleValueType();
7625 unsigned NumElems = VT.getVectorNumElements();
7626 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7627 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7628 bool V1IsSplat = false;
7629 bool V2IsSplat = false;
7630 bool HasSSE2 = Subtarget->hasSSE2();
7631 bool HasFp256 = Subtarget->hasFp256();
7632 bool HasInt256 = Subtarget->hasInt256();
7633 MachineFunction &MF = DAG.getMachineFunction();
7634 bool OptForSize = MF.getFunction()->getAttributes().
7635 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7637 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7639 if (V1IsUndef && V2IsUndef)
7640 return DAG.getUNDEF(VT);
7642 // When we create a shuffle node we put the UNDEF node to second operand,
7643 // but in some cases the first operand may be transformed to UNDEF.
7644 // In this case we should just commute the node.
7646 return CommuteVectorShuffle(SVOp, DAG);
7648 // Vector shuffle lowering takes 3 steps:
7650 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7651 // narrowing and commutation of operands should be handled.
7652 // 2) Matching of shuffles with known shuffle masks to x86 target specific
7654 // 3) Rewriting of unmatched masks into new generic shuffle operations,
7655 // so the shuffle can be broken into other shuffles and the legalizer can
7656 // try the lowering again.
7658 // The general idea is that no vector_shuffle operation should be left to
7659 // be matched during isel, all of them must be converted to a target specific
7662 // Normalize the input vectors. Here splats, zeroed vectors, profitable
7663 // narrowing and commutation of operands should be handled. The actual code
7664 // doesn't include all of those, work in progress...
7665 SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7666 if (NewOp.getNode())
7669 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7671 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7672 // unpckh_undef). Only use pshufd if speed is more important than size.
7673 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7674 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7675 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7676 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7678 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7679 V2IsUndef && MayFoldVectorLoad(V1))
7680 return getMOVDDup(Op, dl, V1, DAG);
7682 if (isMOVHLPS_v_undef_Mask(M, VT))
7683 return getMOVHighToLow(Op, dl, DAG);
7685 // Use to match splats
7686 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7687 (VT == MVT::v2f64 || VT == MVT::v2i64))
7688 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7690 if (isPSHUFDMask(M, VT)) {
7691 // The actual implementation will match the mask in the if above and then
7692 // during isel it can match several different instructions, not only pshufd
7693 // as its name says, sad but true, emulate the behavior for now...
7694 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7695 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7697 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7699 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7700 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7702 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7703 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7706 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7710 if (isPALIGNRMask(M, VT, Subtarget))
7711 return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7712 getShufflePALIGNRImmediate(SVOp),
7715 // Check if this can be converted into a logical shift.
7716 bool isLeft = false;
7719 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7720 if (isShift && ShVal.hasOneUse()) {
7721 // If the shifted value has multiple uses, it may be cheaper to use
7722 // v_set0 + movlhps or movhlps, etc.
7723 MVT EltVT = VT.getVectorElementType();
7724 ShAmt *= EltVT.getSizeInBits();
7725 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7728 if (isMOVLMask(M, VT)) {
7729 if (ISD::isBuildVectorAllZeros(V1.getNode()))
7730 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7731 if (!isMOVLPMask(M, VT)) {
7732 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7733 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7735 if (VT == MVT::v4i32 || VT == MVT::v4f32)
7736 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7740 // FIXME: fold these into legal mask.
7741 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7742 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7744 if (isMOVHLPSMask(M, VT))
7745 return getMOVHighToLow(Op, dl, DAG);
7747 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7748 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7750 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7751 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7753 if (isMOVLPMask(M, VT))
7754 return getMOVLP(Op, dl, DAG, HasSSE2);
7756 if (ShouldXformToMOVHLPS(M, VT) ||
7757 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7758 return CommuteVectorShuffle(SVOp, DAG);
7761 // No better options. Use a vshldq / vsrldq.
7762 MVT EltVT = VT.getVectorElementType();
7763 ShAmt *= EltVT.getSizeInBits();
7764 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7767 bool Commuted = false;
7768 // FIXME: This should also accept a bitcast of a splat? Be careful, not
7769 // 1,1,1,1 -> v8i16 though.
7770 V1IsSplat = isSplatVector(V1.getNode());
7771 V2IsSplat = isSplatVector(V2.getNode());
7773 // Canonicalize the splat or undef, if present, to be on the RHS.
7774 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7775 CommuteVectorShuffleMask(M, NumElems);
7777 std::swap(V1IsSplat, V2IsSplat);
7781 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7782 // Shuffling low element of v1 into undef, just return v1.
7785 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7786 // the instruction selector will not match, so get a canonical MOVL with
7787 // swapped operands to undo the commute.
7788 return getMOVL(DAG, dl, VT, V2, V1);
7791 if (isUNPCKLMask(M, VT, HasInt256))
7792 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7794 if (isUNPCKHMask(M, VT, HasInt256))
7795 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7798 // Normalize mask so all entries that point to V2 points to its first
7799 // element then try to match unpck{h|l} again. If match, return a
7800 // new vector_shuffle with the corrected mask.p
7801 SmallVector<int, 8> NewMask(M.begin(), M.end());
7802 NormalizeMask(NewMask, NumElems);
7803 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7804 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7805 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7806 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7810 // Commute is back and try unpck* again.
7811 // FIXME: this seems wrong.
7812 CommuteVectorShuffleMask(M, NumElems);
7814 std::swap(V1IsSplat, V2IsSplat);
7816 if (isUNPCKLMask(M, VT, HasInt256))
7817 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7819 if (isUNPCKHMask(M, VT, HasInt256))
7820 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7823 // Normalize the node to match x86 shuffle ops if needed
7824 if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
7825 return CommuteVectorShuffle(SVOp, DAG);
7827 // The checks below are all present in isShuffleMaskLegal, but they are
7828 // inlined here right now to enable us to directly emit target specific
7829 // nodes, and remove one by one until they don't return Op anymore.
7831 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7832 SVOp->getSplatIndex() == 0 && V2IsUndef) {
7833 if (VT == MVT::v2f64 || VT == MVT::v2i64)
7834 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7837 if (isPSHUFHWMask(M, VT, HasInt256))
7838 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7839 getShufflePSHUFHWImmediate(SVOp),
7842 if (isPSHUFLWMask(M, VT, HasInt256))
7843 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7844 getShufflePSHUFLWImmediate(SVOp),
7847 if (isSHUFPMask(M, VT))
7848 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7849 getShuffleSHUFImmediate(SVOp), DAG);
7851 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7852 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7853 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7854 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7856 //===--------------------------------------------------------------------===//
7857 // Generate target specific nodes for 128 or 256-bit shuffles only
7858 // supported in the AVX instruction set.
7861 // Handle VMOVDDUPY permutations
7862 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7863 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7865 // Handle VPERMILPS/D* permutations
7866 if (isVPERMILPMask(M, VT)) {
7867 if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
7868 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7869 getShuffleSHUFImmediate(SVOp), DAG);
7870 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7871 getShuffleSHUFImmediate(SVOp), DAG);
7875 if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
7876 return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
7877 Idx*(NumElems/2), DAG, dl);
7879 // Handle VPERM2F128/VPERM2I128 permutations
7880 if (isVPERM2X128Mask(M, VT, HasFp256))
7881 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7882 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7884 SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7885 if (BlendOp.getNode())
7888 if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
7889 return getINSERTPS(SVOp, dl, DAG);
7892 if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
7893 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
7895 if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
7896 VT.is512BitVector()) {
7897 MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
7898 MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
7899 SmallVector<SDValue, 16> permclMask;
7900 for (unsigned i = 0; i != NumElems; ++i) {
7901 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
7904 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
7906 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7907 return DAG.getNode(X86ISD::VPERMV, dl, VT,
7908 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7909 return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
7910 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
7913 //===--------------------------------------------------------------------===//
7914 // Since no target specific shuffle was selected for this generic one,
7915 // lower it into other known shuffles. FIXME: this isn't true yet, but
7916 // this is the plan.
7919 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7920 if (VT == MVT::v8i16) {
7921 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7922 if (NewOp.getNode())
7926 if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
7927 SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
7928 if (NewOp.getNode())
7932 if (VT == MVT::v16i8) {
7933 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
7934 if (NewOp.getNode())
7938 if (VT == MVT::v32i8) {
7939 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7940 if (NewOp.getNode())
7944 // Handle all 128-bit wide vectors with 4 elements, and match them with
7945 // several different shuffle types.
7946 if (NumElems == 4 && VT.is128BitVector())
7947 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7949 // Handle general 256-bit shuffles
7950 if (VT.is256BitVector())
7951 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7956 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7957 MVT VT = Op.getSimpleValueType();
7960 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
7963 if (VT.getSizeInBits() == 8) {
7964 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7965 Op.getOperand(0), Op.getOperand(1));
7966 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7967 DAG.getValueType(VT));
7968 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7971 if (VT.getSizeInBits() == 16) {
7972 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7973 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7975 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7976 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7977 DAG.getNode(ISD::BITCAST, dl,
7981 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7982 Op.getOperand(0), Op.getOperand(1));
7983 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7984 DAG.getValueType(VT));
7985 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7988 if (VT == MVT::f32) {
7989 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7990 // the result back to FR32 register. It's only worth matching if the
7991 // result has a single use which is a store or a bitcast to i32. And in
7992 // the case of a store, it's not worth it if the index is a constant 0,
7993 // because a MOVSSmr can be used instead, which is smaller and faster.
7994 if (!Op.hasOneUse())
7996 SDNode *User = *Op.getNode()->use_begin();
7997 if ((User->getOpcode() != ISD::STORE ||
7998 (isa<ConstantSDNode>(Op.getOperand(1)) &&
7999 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
8000 (User->getOpcode() != ISD::BITCAST ||
8001 User->getValueType(0) != MVT::i32))
8003 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8004 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
8007 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
8010 if (VT == MVT::i32 || VT == MVT::i64) {
8011 // ExtractPS/pextrq works with constant index.
8012 if (isa<ConstantSDNode>(Op.getOperand(1)))
8018 /// Extract one bit from mask vector, like v16i1 or v8i1.
8019 /// AVX-512 feature.
8021 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
8022 SDValue Vec = Op.getOperand(0);
8024 MVT VecVT = Vec.getSimpleValueType();
8025 SDValue Idx = Op.getOperand(1);
8026 MVT EltVT = Op.getSimpleValueType();
8028 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
8030 // variable index can't be handled in mask registers,
8031 // extend vector to VR512
8032 if (!isa<ConstantSDNode>(Idx)) {
8033 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
8034 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
8035 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
8036 ExtVT.getVectorElementType(), Ext, Idx);
8037 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
8040 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8041 const TargetRegisterClass* rc = getRegClassFor(VecVT);
8042 unsigned MaxSift = rc->getSize()*8 - 1;
8043 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
8044 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8045 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
8046 DAG.getConstant(MaxSift, MVT::i8));
8047 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
8048 DAG.getIntPtrConstant(0));
8052 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
8053 SelectionDAG &DAG) const {
8055 SDValue Vec = Op.getOperand(0);
8056 MVT VecVT = Vec.getSimpleValueType();
8057 SDValue Idx = Op.getOperand(1);
8059 if (Op.getSimpleValueType() == MVT::i1)
8060 return ExtractBitFromMaskVector(Op, DAG);
8062 if (!isa<ConstantSDNode>(Idx)) {
8063 if (VecVT.is512BitVector() ||
8064 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
8065 VecVT.getVectorElementType().getSizeInBits() == 32)) {
8068 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
8069 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
8070 MaskEltVT.getSizeInBits());
8072 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
8073 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
8074 getZeroVector(MaskVT, Subtarget, DAG, dl),
8075 Idx, DAG.getConstant(0, getPointerTy()));
8076 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
8077 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
8078 Perm, DAG.getConstant(0, getPointerTy()));
8083 // If this is a 256-bit vector result, first extract the 128-bit vector and
8084 // then extract the element from the 128-bit vector.
8085 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
8087 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8088 // Get the 128-bit vector.
8089 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
8090 MVT EltVT = VecVT.getVectorElementType();
8092 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
8094 //if (IdxVal >= NumElems/2)
8095 // IdxVal -= NumElems/2;
8096 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
8097 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
8098 DAG.getConstant(IdxVal, MVT::i32));
8101 assert(VecVT.is128BitVector() && "Unexpected vector length");
8103 if (Subtarget->hasSSE41()) {
8104 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
8109 MVT VT = Op.getSimpleValueType();
8110 // TODO: handle v16i8.
8111 if (VT.getSizeInBits() == 16) {
8112 SDValue Vec = Op.getOperand(0);
8113 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8115 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8116 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8117 DAG.getNode(ISD::BITCAST, dl,
8120 // Transform it so it match pextrw which produces a 32-bit result.
8121 MVT EltVT = MVT::i32;
8122 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
8123 Op.getOperand(0), Op.getOperand(1));
8124 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
8125 DAG.getValueType(VT));
8126 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8129 if (VT.getSizeInBits() == 32) {
8130 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8134 // SHUFPS the element to the lowest double word, then movss.
8135 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
8136 MVT VVT = Op.getOperand(0).getSimpleValueType();
8137 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8138 DAG.getUNDEF(VVT), Mask);
8139 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8140 DAG.getIntPtrConstant(0));
8143 if (VT.getSizeInBits() == 64) {
8144 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
8145 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
8146 // to match extract_elt for f64.
8147 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8151 // UNPCKHPD the element to the lowest double word, then movsd.
8152 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
8153 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
8154 int Mask[2] = { 1, -1 };
8155 MVT VVT = Op.getOperand(0).getSimpleValueType();
8156 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8157 DAG.getUNDEF(VVT), Mask);
8158 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8159 DAG.getIntPtrConstant(0));
8165 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8166 MVT VT = Op.getSimpleValueType();
8167 MVT EltVT = VT.getVectorElementType();
8170 SDValue N0 = Op.getOperand(0);
8171 SDValue N1 = Op.getOperand(1);
8172 SDValue N2 = Op.getOperand(2);
8174 if (!VT.is128BitVector())
8177 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
8178 isa<ConstantSDNode>(N2)) {
8180 if (VT == MVT::v8i16)
8181 Opc = X86ISD::PINSRW;
8182 else if (VT == MVT::v16i8)
8183 Opc = X86ISD::PINSRB;
8185 Opc = X86ISD::PINSRB;
8187 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
8189 if (N1.getValueType() != MVT::i32)
8190 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8191 if (N2.getValueType() != MVT::i32)
8192 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8193 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
8196 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
8197 // Bits [7:6] of the constant are the source select. This will always be
8198 // zero here. The DAG Combiner may combine an extract_elt index into these
8199 // bits. For example (insert (extract, 3), 2) could be matched by putting
8200 // the '3' into bits [7:6] of X86ISD::INSERTPS.
8201 // Bits [5:4] of the constant are the destination select. This is the
8202 // value of the incoming immediate.
8203 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
8204 // combine either bitwise AND or insert of float 0.0 to set these bits.
8205 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
8206 // Create this as a scalar to vector..
8207 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
8208 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
8211 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
8212 // PINSR* works with constant index.
8218 /// Insert one bit to mask vector, like v16i1 or v8i1.
8219 /// AVX-512 feature.
8221 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
8223 SDValue Vec = Op.getOperand(0);
8224 SDValue Elt = Op.getOperand(1);
8225 SDValue Idx = Op.getOperand(2);
8226 MVT VecVT = Vec.getSimpleValueType();
8228 if (!isa<ConstantSDNode>(Idx)) {
8229 // Non constant index. Extend source and destination,
8230 // insert element and then truncate the result.
8231 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
8232 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
8233 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
8234 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
8235 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
8236 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
8239 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8240 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
8241 if (Vec.getOpcode() == ISD::UNDEF)
8242 return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8243 DAG.getConstant(IdxVal, MVT::i8));
8244 const TargetRegisterClass* rc = getRegClassFor(VecVT);
8245 unsigned MaxSift = rc->getSize()*8 - 1;
8246 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8247 DAG.getConstant(MaxSift, MVT::i8));
8248 EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
8249 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8250 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
8253 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
8254 MVT VT = Op.getSimpleValueType();
8255 MVT EltVT = VT.getVectorElementType();
8257 if (EltVT == MVT::i1)
8258 return InsertBitToMaskVector(Op, DAG);
8261 SDValue N0 = Op.getOperand(0);
8262 SDValue N1 = Op.getOperand(1);
8263 SDValue N2 = Op.getOperand(2);
8265 // If this is a 256-bit vector result, first extract the 128-bit vector,
8266 // insert the element into the extracted half and then place it back.
8267 if (VT.is256BitVector() || VT.is512BitVector()) {
8268 if (!isa<ConstantSDNode>(N2))
8271 // Get the desired 128-bit vector half.
8272 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
8273 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
8275 // Insert the element into the desired half.
8276 unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
8277 unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
8279 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
8280 DAG.getConstant(IdxIn128, MVT::i32));
8282 // Insert the changed part back to the 256-bit vector
8283 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
8286 if (Subtarget->hasSSE41())
8287 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
8289 if (EltVT == MVT::i8)
8292 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
8293 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
8294 // as its second argument.
8295 if (N1.getValueType() != MVT::i32)
8296 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8297 if (N2.getValueType() != MVT::i32)
8298 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8299 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
8304 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
8306 MVT OpVT = Op.getSimpleValueType();
8308 // If this is a 256-bit vector result, first insert into a 128-bit
8309 // vector and then insert into the 256-bit vector.
8310 if (!OpVT.is128BitVector()) {
8311 // Insert into a 128-bit vector.
8312 unsigned SizeFactor = OpVT.getSizeInBits()/128;
8313 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
8314 OpVT.getVectorNumElements() / SizeFactor);
8316 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
8318 // Insert the 128-bit vector.
8319 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
8322 if (OpVT == MVT::v1i64 &&
8323 Op.getOperand(0).getValueType() == MVT::i64)
8324 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
8326 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
8327 assert(OpVT.is128BitVector() && "Expected an SSE type!");
8328 return DAG.getNode(ISD::BITCAST, dl, OpVT,
8329 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
8332 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
8333 // a simple subregister reference or explicit instructions to grab
8334 // upper bits of a vector.
8335 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8336 SelectionDAG &DAG) {
8338 SDValue In = Op.getOperand(0);
8339 SDValue Idx = Op.getOperand(1);
8340 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8341 MVT ResVT = Op.getSimpleValueType();
8342 MVT InVT = In.getSimpleValueType();
8344 if (Subtarget->hasFp256()) {
8345 if (ResVT.is128BitVector() &&
8346 (InVT.is256BitVector() || InVT.is512BitVector()) &&
8347 isa<ConstantSDNode>(Idx)) {
8348 return Extract128BitVector(In, IdxVal, DAG, dl);
8350 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
8351 isa<ConstantSDNode>(Idx)) {
8352 return Extract256BitVector(In, IdxVal, DAG, dl);
8358 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
8359 // simple superregister reference or explicit instructions to insert
8360 // the upper bits of a vector.
8361 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8362 SelectionDAG &DAG) {
8363 if (Subtarget->hasFp256()) {
8364 SDLoc dl(Op.getNode());
8365 SDValue Vec = Op.getNode()->getOperand(0);
8366 SDValue SubVec = Op.getNode()->getOperand(1);
8367 SDValue Idx = Op.getNode()->getOperand(2);
8369 if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8370 Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8371 SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8372 isa<ConstantSDNode>(Idx)) {
8373 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8374 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8377 if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8378 SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8379 isa<ConstantSDNode>(Idx)) {
8380 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8381 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8387 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8388 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8389 // one of the above mentioned nodes. It has to be wrapped because otherwise
8390 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8391 // be used to form addressing mode. These wrapped nodes will be selected
8394 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8395 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8397 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8399 unsigned char OpFlag = 0;
8400 unsigned WrapperKind = X86ISD::Wrapper;
8401 CodeModel::Model M = getTargetMachine().getCodeModel();
8403 if (Subtarget->isPICStyleRIPRel() &&
8404 (M == CodeModel::Small || M == CodeModel::Kernel))
8405 WrapperKind = X86ISD::WrapperRIP;
8406 else if (Subtarget->isPICStyleGOT())
8407 OpFlag = X86II::MO_GOTOFF;
8408 else if (Subtarget->isPICStyleStubPIC())
8409 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8411 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8413 CP->getOffset(), OpFlag);
8415 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8416 // With PIC, the address is actually $g + Offset.
8418 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8419 DAG.getNode(X86ISD::GlobalBaseReg,
8420 SDLoc(), getPointerTy()),
8427 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8428 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8430 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8432 unsigned char OpFlag = 0;
8433 unsigned WrapperKind = X86ISD::Wrapper;
8434 CodeModel::Model M = getTargetMachine().getCodeModel();
8436 if (Subtarget->isPICStyleRIPRel() &&
8437 (M == CodeModel::Small || M == CodeModel::Kernel))
8438 WrapperKind = X86ISD::WrapperRIP;
8439 else if (Subtarget->isPICStyleGOT())
8440 OpFlag = X86II::MO_GOTOFF;
8441 else if (Subtarget->isPICStyleStubPIC())
8442 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8444 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8447 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8449 // With PIC, the address is actually $g + Offset.
8451 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8452 DAG.getNode(X86ISD::GlobalBaseReg,
8453 SDLoc(), getPointerTy()),
8460 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8461 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8463 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8465 unsigned char OpFlag = 0;
8466 unsigned WrapperKind = X86ISD::Wrapper;
8467 CodeModel::Model M = getTargetMachine().getCodeModel();
8469 if (Subtarget->isPICStyleRIPRel() &&
8470 (M == CodeModel::Small || M == CodeModel::Kernel)) {
8471 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8472 OpFlag = X86II::MO_GOTPCREL;
8473 WrapperKind = X86ISD::WrapperRIP;
8474 } else if (Subtarget->isPICStyleGOT()) {
8475 OpFlag = X86II::MO_GOT;
8476 } else if (Subtarget->isPICStyleStubPIC()) {
8477 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8478 } else if (Subtarget->isPICStyleStubNoDynamic()) {
8479 OpFlag = X86II::MO_DARWIN_NONLAZY;
8482 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8485 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8487 // With PIC, the address is actually $g + Offset.
8488 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
8489 !Subtarget->is64Bit()) {
8490 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8491 DAG.getNode(X86ISD::GlobalBaseReg,
8492 SDLoc(), getPointerTy()),
8496 // For symbols that require a load from a stub to get the address, emit the
8498 if (isGlobalStubReference(OpFlag))
8499 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8500 MachinePointerInfo::getGOT(), false, false, false, 0);
8506 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8507 // Create the TargetBlockAddressAddress node.
8508 unsigned char OpFlags =
8509 Subtarget->ClassifyBlockAddressReference();
8510 CodeModel::Model M = getTargetMachine().getCodeModel();
8511 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8512 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8514 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8517 if (Subtarget->isPICStyleRIPRel() &&
8518 (M == CodeModel::Small || M == CodeModel::Kernel))
8519 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8521 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8523 // With PIC, the address is actually $g + Offset.
8524 if (isGlobalRelativeToPICBase(OpFlags)) {
8525 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8526 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8534 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8535 int64_t Offset, SelectionDAG &DAG) const {
8536 // Create the TargetGlobalAddress node, folding in the constant
8537 // offset if it is legal.
8538 unsigned char OpFlags =
8539 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
8540 CodeModel::Model M = getTargetMachine().getCodeModel();
8542 if (OpFlags == X86II::MO_NO_FLAG &&
8543 X86::isOffsetSuitableForCodeModel(Offset, M)) {
8544 // A direct static reference to a global.
8545 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8548 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8551 if (Subtarget->isPICStyleRIPRel() &&
8552 (M == CodeModel::Small || M == CodeModel::Kernel))
8553 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8555 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8557 // With PIC, the address is actually $g + Offset.
8558 if (isGlobalRelativeToPICBase(OpFlags)) {
8559 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8560 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8564 // For globals that require a load from a stub to get the address, emit the
8566 if (isGlobalStubReference(OpFlags))
8567 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8568 MachinePointerInfo::getGOT(), false, false, false, 0);
8570 // If there was a non-zero offset that we didn't fold, create an explicit
8573 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8574 DAG.getConstant(Offset, getPointerTy()));
8580 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8581 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8582 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8583 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8587 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8588 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8589 unsigned char OperandFlags, bool LocalDynamic = false) {
8590 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8591 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8593 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8594 GA->getValueType(0),
8598 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8602 SDValue Ops[] = { Chain, TGA, *InFlag };
8603 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8605 SDValue Ops[] = { Chain, TGA };
8606 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8609 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8610 MFI->setAdjustsStack(true);
8612 SDValue Flag = Chain.getValue(1);
8613 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8616 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8618 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8621 SDLoc dl(GA); // ? function entry point might be better
8622 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8623 DAG.getNode(X86ISD::GlobalBaseReg,
8624 SDLoc(), PtrVT), InFlag);
8625 InFlag = Chain.getValue(1);
8627 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8630 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8632 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8634 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
8635 X86::RAX, X86II::MO_TLSGD);
8638 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8644 // Get the start address of the TLS block for this module.
8645 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8646 .getInfo<X86MachineFunctionInfo>();
8647 MFI->incNumLocalDynamicTLSAccesses();
8651 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
8652 X86II::MO_TLSLD, /*LocalDynamic=*/true);
8655 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8656 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8657 InFlag = Chain.getValue(1);
8658 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8659 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8662 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8666 unsigned char OperandFlags = X86II::MO_DTPOFF;
8667 unsigned WrapperKind = X86ISD::Wrapper;
8668 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8669 GA->getValueType(0),
8670 GA->getOffset(), OperandFlags);
8671 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8673 // Add x@dtpoff with the base.
8674 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8677 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8678 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8679 const EVT PtrVT, TLSModel::Model model,
8680 bool is64Bit, bool isPIC) {
8683 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8684 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8685 is64Bit ? 257 : 256));
8687 SDValue ThreadPointer =
8688 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
8689 MachinePointerInfo(Ptr), false, false, false, 0);
8691 unsigned char OperandFlags = 0;
8692 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
8694 unsigned WrapperKind = X86ISD::Wrapper;
8695 if (model == TLSModel::LocalExec) {
8696 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8697 } else if (model == TLSModel::InitialExec) {
8699 OperandFlags = X86II::MO_GOTTPOFF;
8700 WrapperKind = X86ISD::WrapperRIP;
8702 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8705 llvm_unreachable("Unexpected model");
8708 // emit "addl x@ntpoff,%eax" (local exec)
8709 // or "addl x@indntpoff,%eax" (initial exec)
8710 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8712 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
8713 GA->getOffset(), OperandFlags);
8714 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8716 if (model == TLSModel::InitialExec) {
8717 if (isPIC && !is64Bit) {
8718 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8719 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8723 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8724 MachinePointerInfo::getGOT(), false, false, false, 0);
8727 // The address of the thread local variable is the add of the thread
8728 // pointer with the offset of the variable.
8729 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8733 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8735 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8736 const GlobalValue *GV = GA->getGlobal();
8738 if (Subtarget->isTargetELF()) {
8739 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8742 case TLSModel::GeneralDynamic:
8743 if (Subtarget->is64Bit())
8744 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8745 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8746 case TLSModel::LocalDynamic:
8747 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8748 Subtarget->is64Bit());
8749 case TLSModel::InitialExec:
8750 case TLSModel::LocalExec:
8751 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8752 Subtarget->is64Bit(),
8753 getTargetMachine().getRelocationModel() == Reloc::PIC_);
8755 llvm_unreachable("Unknown TLS model.");
8758 if (Subtarget->isTargetDarwin()) {
8759 // Darwin only has one model of TLS. Lower to that.
8760 unsigned char OpFlag = 0;
8761 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8762 X86ISD::WrapperRIP : X86ISD::Wrapper;
8764 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8766 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8767 !Subtarget->is64Bit();
8769 OpFlag = X86II::MO_TLVP_PIC_BASE;
8771 OpFlag = X86II::MO_TLVP;
8773 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8774 GA->getValueType(0),
8775 GA->getOffset(), OpFlag);
8776 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8778 // With PIC32, the address is actually $g + Offset.
8780 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8781 DAG.getNode(X86ISD::GlobalBaseReg,
8782 SDLoc(), getPointerTy()),
8785 // Lowering the machine isd will make sure everything is in the right
8787 SDValue Chain = DAG.getEntryNode();
8788 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8789 SDValue Args[] = { Chain, Offset };
8790 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
8792 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8793 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8794 MFI->setAdjustsStack(true);
8796 // And our return value (tls address) is in the standard call return value
8798 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8799 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8803 if (Subtarget->isTargetKnownWindowsMSVC() ||
8804 Subtarget->isTargetWindowsGNU()) {
8805 // Just use the implicit TLS architecture
8806 // Need to generate someting similar to:
8807 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8809 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
8810 // mov rcx, qword [rdx+rcx*8]
8811 // mov eax, .tls$:tlsvar
8812 // [rax+rcx] contains the address
8813 // Windows 64bit: gs:0x58
8814 // Windows 32bit: fs:__tls_array
8816 // If GV is an alias then use the aliasee for determining
8817 // thread-localness.
8818 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
8819 GV = GA->getAliasedGlobal();
8821 SDValue Chain = DAG.getEntryNode();
8823 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8824 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8825 // use its literal value of 0x2C.
8826 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8827 ? Type::getInt8PtrTy(*DAG.getContext(),
8829 : Type::getInt32PtrTy(*DAG.getContext(),
8833 Subtarget->is64Bit()
8834 ? DAG.getIntPtrConstant(0x58)
8835 : (Subtarget->isTargetWindowsGNU()
8836 ? DAG.getIntPtrConstant(0x2C)
8837 : DAG.getExternalSymbol("_tls_array", getPointerTy()));
8839 SDValue ThreadPointer =
8840 DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8841 MachinePointerInfo(Ptr), false, false, false, 0);
8843 // Load the _tls_index variable
8844 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8845 if (Subtarget->is64Bit())
8846 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8847 IDX, MachinePointerInfo(), MVT::i32,
8850 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
8851 false, false, false, 0);
8853 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
8855 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
8857 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
8858 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
8859 false, false, false, 0);
8861 // Get the offset of start of .tls section
8862 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8863 GA->getValueType(0),
8864 GA->getOffset(), X86II::MO_SECREL);
8865 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
8867 // The address of the thread local variable is the add of the thread
8868 // pointer with the offset of the variable.
8869 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
8872 llvm_unreachable("TLS not implemented for this target.");
8875 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
8876 /// and take a 2 x i32 value to shift plus a shift amount.
8877 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
8878 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
8879 MVT VT = Op.getSimpleValueType();
8880 unsigned VTBits = VT.getSizeInBits();
8882 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
8883 SDValue ShOpLo = Op.getOperand(0);
8884 SDValue ShOpHi = Op.getOperand(1);
8885 SDValue ShAmt = Op.getOperand(2);
8886 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
8887 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
8889 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8890 DAG.getConstant(VTBits - 1, MVT::i8));
8891 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
8892 DAG.getConstant(VTBits - 1, MVT::i8))
8893 : DAG.getConstant(0, VT);
8896 if (Op.getOpcode() == ISD::SHL_PARTS) {
8897 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
8898 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
8900 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
8901 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
8904 // If the shift amount is larger or equal than the width of a part we can't
8905 // rely on the results of shld/shrd. Insert a test and select the appropriate
8906 // values for large shift amounts.
8907 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8908 DAG.getConstant(VTBits, MVT::i8));
8909 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8910 AndNode, DAG.getConstant(0, MVT::i8));
8913 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8914 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
8915 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
8917 if (Op.getOpcode() == ISD::SHL_PARTS) {
8918 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
8919 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
8921 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
8922 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
8925 SDValue Ops[2] = { Lo, Hi };
8926 return DAG.getMergeValues(Ops, dl);
8929 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
8930 SelectionDAG &DAG) const {
8931 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
8933 if (SrcVT.isVector())
8936 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
8937 "Unknown SINT_TO_FP to lower!");
8939 // These are really Legal; return the operand so the caller accepts it as
8941 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
8943 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
8944 Subtarget->is64Bit()) {
8949 unsigned Size = SrcVT.getSizeInBits()/8;
8950 MachineFunction &MF = DAG.getMachineFunction();
8951 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8952 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8953 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8955 MachinePointerInfo::getFixedStack(SSFI),
8957 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8960 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8962 SelectionDAG &DAG) const {
8966 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8968 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8970 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8972 unsigned ByteSize = SrcVT.getSizeInBits()/8;
8974 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8975 MachineMemOperand *MMO;
8977 int SSFI = FI->getIndex();
8979 DAG.getMachineFunction()
8980 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8981 MachineMemOperand::MOLoad, ByteSize, ByteSize);
8983 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8984 StackSlot = StackSlot.getOperand(1);
8986 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8987 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8989 Tys, Ops, SrcVT, MMO);
8992 Chain = Result.getValue(1);
8993 SDValue InFlag = Result.getValue(2);
8995 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8996 // shouldn't be necessary except that RFP cannot be live across
8997 // multiple blocks. When stackifier is fixed, they can be uncoupled.
8998 MachineFunction &MF = DAG.getMachineFunction();
8999 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
9000 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
9001 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9002 Tys = DAG.getVTList(MVT::Other);
9004 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
9006 MachineMemOperand *MMO =
9007 DAG.getMachineFunction()
9008 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9009 MachineMemOperand::MOStore, SSFISize, SSFISize);
9011 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
9012 Ops, Op.getValueType(), MMO);
9013 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
9014 MachinePointerInfo::getFixedStack(SSFI),
9015 false, false, false, 0);
9021 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
9022 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
9023 SelectionDAG &DAG) const {
9024 // This algorithm is not obvious. Here it is what we're trying to output:
9027 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
9028 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
9032 pshufd $0x4e, %xmm0, %xmm1
9038 LLVMContext *Context = DAG.getContext();
9040 // Build some magic constants.
9041 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
9042 Constant *C0 = ConstantDataVector::get(*Context, CV0);
9043 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
9045 SmallVector<Constant*,2> CV1;
9047 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9048 APInt(64, 0x4330000000000000ULL))));
9050 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9051 APInt(64, 0x4530000000000000ULL))));
9052 Constant *C1 = ConstantVector::get(CV1);
9053 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
9055 // Load the 64-bit value into an XMM register.
9056 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
9058 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
9059 MachinePointerInfo::getConstantPool(),
9060 false, false, false, 16);
9061 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
9062 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
9065 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
9066 MachinePointerInfo::getConstantPool(),
9067 false, false, false, 16);
9068 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
9069 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
9072 if (Subtarget->hasSSE3()) {
9073 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
9074 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
9076 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
9077 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
9079 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
9080 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
9084 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
9085 DAG.getIntPtrConstant(0));
9088 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
9089 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
9090 SelectionDAG &DAG) const {
9092 // FP constant to bias correct the final result.
9093 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
9096 // Load the 32-bit value into an XMM register.
9097 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
9100 // Zero out the upper parts of the register.
9101 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
9103 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9104 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
9105 DAG.getIntPtrConstant(0));
9107 // Or the load with the bias.
9108 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
9109 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9110 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9112 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9113 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9114 MVT::v2f64, Bias)));
9115 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9116 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
9117 DAG.getIntPtrConstant(0));
9119 // Subtract the bias.
9120 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
9122 // Handle final rounding.
9123 EVT DestVT = Op.getValueType();
9125 if (DestVT.bitsLT(MVT::f64))
9126 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
9127 DAG.getIntPtrConstant(0));
9128 if (DestVT.bitsGT(MVT::f64))
9129 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
9131 // Handle final rounding.
9135 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
9136 SelectionDAG &DAG) const {
9137 SDValue N0 = Op.getOperand(0);
9138 MVT SVT = N0.getSimpleValueType();
9141 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
9142 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
9143 "Custom UINT_TO_FP is not supported!");
9145 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
9146 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
9147 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
9150 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
9151 SelectionDAG &DAG) const {
9152 SDValue N0 = Op.getOperand(0);
9155 if (Op.getValueType().isVector())
9156 return lowerUINT_TO_FP_vec(Op, DAG);
9158 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
9159 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
9160 // the optimization here.
9161 if (DAG.SignBitIsZero(N0))
9162 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
9164 MVT SrcVT = N0.getSimpleValueType();
9165 MVT DstVT = Op.getSimpleValueType();
9166 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
9167 return LowerUINT_TO_FP_i64(Op, DAG);
9168 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
9169 return LowerUINT_TO_FP_i32(Op, DAG);
9170 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
9173 // Make a 64-bit buffer, and use it to build an FILD.
9174 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
9175 if (SrcVT == MVT::i32) {
9176 SDValue WordOff = DAG.getConstant(4, getPointerTy());
9177 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
9178 getPointerTy(), StackSlot, WordOff);
9179 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9180 StackSlot, MachinePointerInfo(),
9182 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
9183 OffsetSlot, MachinePointerInfo(),
9185 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
9189 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
9190 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9191 StackSlot, MachinePointerInfo(),
9193 // For i64 source, we need to add the appropriate power of 2 if the input
9194 // was negative. This is the same as the optimization in
9195 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
9196 // we must be careful to do the computation in x87 extended precision, not
9197 // in SSE. (The generic code can't know it's OK to do this, or how to.)
9198 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
9199 MachineMemOperand *MMO =
9200 DAG.getMachineFunction()
9201 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9202 MachineMemOperand::MOLoad, 8, 8);
9204 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
9205 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
9206 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
9209 APInt FF(32, 0x5F800000ULL);
9211 // Check whether the sign bit is set.
9212 SDValue SignSet = DAG.getSetCC(dl,
9213 getSetCCResultType(*DAG.getContext(), MVT::i64),
9214 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
9217 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
9218 SDValue FudgePtr = DAG.getConstantPool(
9219 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
9222 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
9223 SDValue Zero = DAG.getIntPtrConstant(0);
9224 SDValue Four = DAG.getIntPtrConstant(4);
9225 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
9227 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
9229 // Load the value out, extending it from f32 to f80.
9230 // FIXME: Avoid the extend by constructing the right constant pool?
9231 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
9232 FudgePtr, MachinePointerInfo::getConstantPool(),
9233 MVT::f32, false, false, 4);
9234 // Extend everything to 80 bits to force it to be done on x87.
9235 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
9236 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
9239 std::pair<SDValue,SDValue>
9240 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
9241 bool IsSigned, bool IsReplace) const {
9244 EVT DstTy = Op.getValueType();
9246 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
9247 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
9251 assert(DstTy.getSimpleVT() <= MVT::i64 &&
9252 DstTy.getSimpleVT() >= MVT::i16 &&
9253 "Unknown FP_TO_INT to lower!");
9255 // These are really Legal.
9256 if (DstTy == MVT::i32 &&
9257 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9258 return std::make_pair(SDValue(), SDValue());
9259 if (Subtarget->is64Bit() &&
9260 DstTy == MVT::i64 &&
9261 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9262 return std::make_pair(SDValue(), SDValue());
9264 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
9265 // stack slot, or into the FTOL runtime function.
9266 MachineFunction &MF = DAG.getMachineFunction();
9267 unsigned MemSize = DstTy.getSizeInBits()/8;
9268 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9269 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9272 if (!IsSigned && isIntegerTypeFTOL(DstTy))
9273 Opc = X86ISD::WIN_FTOL;
9275 switch (DstTy.getSimpleVT().SimpleTy) {
9276 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
9277 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
9278 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
9279 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
9282 SDValue Chain = DAG.getEntryNode();
9283 SDValue Value = Op.getOperand(0);
9284 EVT TheVT = Op.getOperand(0).getValueType();
9285 // FIXME This causes a redundant load/store if the SSE-class value is already
9286 // in memory, such as if it is on the callstack.
9287 if (isScalarFPTypeInSSEReg(TheVT)) {
9288 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
9289 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
9290 MachinePointerInfo::getFixedStack(SSFI),
9292 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
9294 Chain, StackSlot, DAG.getValueType(TheVT)
9297 MachineMemOperand *MMO =
9298 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9299 MachineMemOperand::MOLoad, MemSize, MemSize);
9300 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
9301 Chain = Value.getValue(1);
9302 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9303 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9306 MachineMemOperand *MMO =
9307 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9308 MachineMemOperand::MOStore, MemSize, MemSize);
9310 if (Opc != X86ISD::WIN_FTOL) {
9311 // Build the FP_TO_INT*_IN_MEM
9312 SDValue Ops[] = { Chain, Value, StackSlot };
9313 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
9315 return std::make_pair(FIST, StackSlot);
9317 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
9318 DAG.getVTList(MVT::Other, MVT::Glue),
9320 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
9321 MVT::i32, ftol.getValue(1));
9322 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
9323 MVT::i32, eax.getValue(2));
9324 SDValue Ops[] = { eax, edx };
9325 SDValue pair = IsReplace
9326 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
9327 : DAG.getMergeValues(Ops, DL);
9328 return std::make_pair(pair, SDValue());
9332 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
9333 const X86Subtarget *Subtarget) {
9334 MVT VT = Op->getSimpleValueType(0);
9335 SDValue In = Op->getOperand(0);
9336 MVT InVT = In.getSimpleValueType();
9339 // Optimize vectors in AVX mode:
9342 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
9343 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
9344 // Concat upper and lower parts.
9347 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
9348 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
9349 // Concat upper and lower parts.
9352 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
9353 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
9354 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
9357 if (Subtarget->hasInt256())
9358 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
9360 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
9361 SDValue Undef = DAG.getUNDEF(InVT);
9362 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9363 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9364 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9366 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9367 VT.getVectorNumElements()/2);
9369 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9370 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9372 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9375 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9376 SelectionDAG &DAG) {
9377 MVT VT = Op->getSimpleValueType(0);
9378 SDValue In = Op->getOperand(0);
9379 MVT InVT = In.getSimpleValueType();
9381 unsigned int NumElts = VT.getVectorNumElements();
9382 if (NumElts != 8 && NumElts != 16)
9385 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9386 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9388 EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9389 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9390 // Now we have only mask extension
9391 assert(InVT.getVectorElementType() == MVT::i1);
9392 SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9393 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9394 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9395 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9396 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9397 MachinePointerInfo::getConstantPool(),
9398 false, false, false, Alignment);
9400 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9401 if (VT.is512BitVector())
9403 return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9406 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9407 SelectionDAG &DAG) {
9408 if (Subtarget->hasFp256()) {
9409 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9417 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9418 SelectionDAG &DAG) {
9420 MVT VT = Op.getSimpleValueType();
9421 SDValue In = Op.getOperand(0);
9422 MVT SVT = In.getSimpleValueType();
9424 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9425 return LowerZERO_EXTEND_AVX512(Op, DAG);
9427 if (Subtarget->hasFp256()) {
9428 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9433 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9434 VT.getVectorNumElements() != SVT.getVectorNumElements());
9438 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9440 MVT VT = Op.getSimpleValueType();
9441 SDValue In = Op.getOperand(0);
9442 MVT InVT = In.getSimpleValueType();
9444 if (VT == MVT::i1) {
9445 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9446 "Invalid scalar TRUNCATE operation");
9447 if (InVT == MVT::i32)
9449 if (InVT.getSizeInBits() == 64)
9450 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9451 else if (InVT.getSizeInBits() < 32)
9452 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9453 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
9455 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9456 "Invalid TRUNCATE operation");
9458 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9459 if (VT.getVectorElementType().getSizeInBits() >=8)
9460 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9462 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9463 unsigned NumElts = InVT.getVectorNumElements();
9464 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9465 if (InVT.getSizeInBits() < 512) {
9466 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9467 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9471 SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9472 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9473 SDValue CP = DAG.getConstantPool(C, getPointerTy());
9474 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9475 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9476 MachinePointerInfo::getConstantPool(),
9477 false, false, false, Alignment);
9478 SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9479 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9480 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9483 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9484 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9485 if (Subtarget->hasInt256()) {
9486 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9487 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9488 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9490 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9491 DAG.getIntPtrConstant(0));
9494 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9495 DAG.getIntPtrConstant(0));
9496 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9497 DAG.getIntPtrConstant(2));
9498 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9499 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9500 static const int ShufMask[] = {0, 2, 4, 6};
9501 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
9504 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9505 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9506 if (Subtarget->hasInt256()) {
9507 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9509 SmallVector<SDValue,32> pshufbMask;
9510 for (unsigned i = 0; i < 2; ++i) {
9511 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9512 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9513 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9514 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9515 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9516 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9517 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9518 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9519 for (unsigned j = 0; j < 8; ++j)
9520 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9522 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
9523 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9524 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9526 static const int ShufMask[] = {0, 2, -1, -1};
9527 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
9529 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9530 DAG.getIntPtrConstant(0));
9531 return DAG.getNode(ISD::BITCAST, DL, VT, In);
9534 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9535 DAG.getIntPtrConstant(0));
9537 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9538 DAG.getIntPtrConstant(4));
9540 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9541 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9544 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
9545 -1, -1, -1, -1, -1, -1, -1, -1};
9547 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9548 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9549 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9551 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9552 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9554 // The MOVLHPS Mask:
9555 static const int ShufMask2[] = {0, 1, 4, 5};
9556 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9557 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9560 // Handle truncation of V256 to V128 using shuffles.
9561 if (!VT.is128BitVector() || !InVT.is256BitVector())
9564 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9566 unsigned NumElems = VT.getVectorNumElements();
9567 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
9569 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9570 // Prepare truncation shuffle mask
9571 for (unsigned i = 0; i != NumElems; ++i)
9573 SDValue V = DAG.getVectorShuffle(NVT, DL,
9574 DAG.getNode(ISD::BITCAST, DL, NVT, In),
9575 DAG.getUNDEF(NVT), &MaskVec[0]);
9576 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9577 DAG.getIntPtrConstant(0));
9580 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9581 SelectionDAG &DAG) const {
9582 assert(!Op.getSimpleValueType().isVector());
9584 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9585 /*IsSigned=*/ true, /*IsReplace=*/ false);
9586 SDValue FIST = Vals.first, StackSlot = Vals.second;
9587 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9588 if (!FIST.getNode()) return Op;
9590 if (StackSlot.getNode())
9592 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9593 FIST, StackSlot, MachinePointerInfo(),
9594 false, false, false, 0);
9596 // The node is the result.
9600 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9601 SelectionDAG &DAG) const {
9602 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9603 /*IsSigned=*/ false, /*IsReplace=*/ false);
9604 SDValue FIST = Vals.first, StackSlot = Vals.second;
9605 assert(FIST.getNode() && "Unexpected failure");
9607 if (StackSlot.getNode())
9609 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9610 FIST, StackSlot, MachinePointerInfo(),
9611 false, false, false, 0);
9613 // The node is the result.
9617 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9619 MVT VT = Op.getSimpleValueType();
9620 SDValue In = Op.getOperand(0);
9621 MVT SVT = In.getSimpleValueType();
9623 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9625 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9626 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9627 In, DAG.getUNDEF(SVT)));
9630 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
9631 LLVMContext *Context = DAG.getContext();
9633 MVT VT = Op.getSimpleValueType();
9635 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9636 if (VT.isVector()) {
9637 EltVT = VT.getVectorElementType();
9638 NumElts = VT.getVectorNumElements();
9641 if (EltVT == MVT::f64)
9642 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9643 APInt(64, ~(1ULL << 63))));
9645 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9646 APInt(32, ~(1U << 31))));
9647 C = ConstantVector::getSplat(NumElts, C);
9648 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9649 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9650 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9651 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9652 MachinePointerInfo::getConstantPool(),
9653 false, false, false, Alignment);
9654 if (VT.isVector()) {
9655 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9656 return DAG.getNode(ISD::BITCAST, dl, VT,
9657 DAG.getNode(ISD::AND, dl, ANDVT,
9658 DAG.getNode(ISD::BITCAST, dl, ANDVT,
9660 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9662 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9665 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
9666 LLVMContext *Context = DAG.getContext();
9668 MVT VT = Op.getSimpleValueType();
9670 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9671 if (VT.isVector()) {
9672 EltVT = VT.getVectorElementType();
9673 NumElts = VT.getVectorNumElements();
9676 if (EltVT == MVT::f64)
9677 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9678 APInt(64, 1ULL << 63)));
9680 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9681 APInt(32, 1U << 31)));
9682 C = ConstantVector::getSplat(NumElts, C);
9683 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9684 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9685 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9686 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9687 MachinePointerInfo::getConstantPool(),
9688 false, false, false, Alignment);
9689 if (VT.isVector()) {
9690 MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
9691 return DAG.getNode(ISD::BITCAST, dl, VT,
9692 DAG.getNode(ISD::XOR, dl, XORVT,
9693 DAG.getNode(ISD::BITCAST, dl, XORVT,
9695 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9698 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9701 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
9702 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9703 LLVMContext *Context = DAG.getContext();
9704 SDValue Op0 = Op.getOperand(0);
9705 SDValue Op1 = Op.getOperand(1);
9707 MVT VT = Op.getSimpleValueType();
9708 MVT SrcVT = Op1.getSimpleValueType();
9710 // If second operand is smaller, extend it first.
9711 if (SrcVT.bitsLT(VT)) {
9712 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9715 // And if it is bigger, shrink it first.
9716 if (SrcVT.bitsGT(VT)) {
9717 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9721 // At this point the operands and the result should have the same
9722 // type, and that won't be f80 since that is not custom lowered.
9724 // First get the sign bit of second operand.
9725 SmallVector<Constant*,4> CV;
9726 if (SrcVT == MVT::f64) {
9727 const fltSemantics &Sem = APFloat::IEEEdouble;
9728 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9729 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9731 const fltSemantics &Sem = APFloat::IEEEsingle;
9732 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9733 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9734 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9735 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9737 Constant *C = ConstantVector::get(CV);
9738 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9739 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9740 MachinePointerInfo::getConstantPool(),
9741 false, false, false, 16);
9742 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9744 // Shift sign bit right or left if the two operands have different types.
9745 if (SrcVT.bitsGT(VT)) {
9746 // Op0 is MVT::f32, Op1 is MVT::f64.
9747 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9748 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9749 DAG.getConstant(32, MVT::i32));
9750 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9751 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9752 DAG.getIntPtrConstant(0));
9755 // Clear first operand sign bit.
9757 if (VT == MVT::f64) {
9758 const fltSemantics &Sem = APFloat::IEEEdouble;
9759 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9760 APInt(64, ~(1ULL << 63)))));
9761 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9763 const fltSemantics &Sem = APFloat::IEEEsingle;
9764 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9765 APInt(32, ~(1U << 31)))));
9766 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9767 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9768 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9770 C = ConstantVector::get(CV);
9771 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9772 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9773 MachinePointerInfo::getConstantPool(),
9774 false, false, false, 16);
9775 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9777 // Or the value with the sign bit.
9778 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9781 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9782 SDValue N0 = Op.getOperand(0);
9784 MVT VT = Op.getSimpleValueType();
9786 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9787 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9788 DAG.getConstant(1, VT));
9789 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9792 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9794 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
9795 SelectionDAG &DAG) {
9796 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9798 if (!Subtarget->hasSSE41())
9801 if (!Op->hasOneUse())
9804 SDNode *N = Op.getNode();
9807 SmallVector<SDValue, 8> Opnds;
9808 DenseMap<SDValue, unsigned> VecInMap;
9809 SmallVector<SDValue, 8> VecIns;
9810 EVT VT = MVT::Other;
9812 // Recognize a special case where a vector is casted into wide integer to
9814 Opnds.push_back(N->getOperand(0));
9815 Opnds.push_back(N->getOperand(1));
9817 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9818 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9819 // BFS traverse all OR'd operands.
9820 if (I->getOpcode() == ISD::OR) {
9821 Opnds.push_back(I->getOperand(0));
9822 Opnds.push_back(I->getOperand(1));
9823 // Re-evaluate the number of nodes to be traversed.
9824 e += 2; // 2 more nodes (LHS and RHS) are pushed.
9828 // Quit if a non-EXTRACT_VECTOR_ELT
9829 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9832 // Quit if without a constant index.
9833 SDValue Idx = I->getOperand(1);
9834 if (!isa<ConstantSDNode>(Idx))
9837 SDValue ExtractedFromVec = I->getOperand(0);
9838 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9839 if (M == VecInMap.end()) {
9840 VT = ExtractedFromVec.getValueType();
9841 // Quit if not 128/256-bit vector.
9842 if (!VT.is128BitVector() && !VT.is256BitVector())
9844 // Quit if not the same type.
9845 if (VecInMap.begin() != VecInMap.end() &&
9846 VT != VecInMap.begin()->first.getValueType())
9848 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9849 VecIns.push_back(ExtractedFromVec);
9851 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9854 assert((VT.is128BitVector() || VT.is256BitVector()) &&
9855 "Not extracted from 128-/256-bit vector.");
9857 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
9859 for (DenseMap<SDValue, unsigned>::const_iterator
9860 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
9861 // Quit if not all elements are used.
9862 if (I->second != FullMask)
9866 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9868 // Cast all vectors into TestVT for PTEST.
9869 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
9870 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
9872 // If more than one full vectors are evaluated, OR them first before PTEST.
9873 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
9874 // Each iteration will OR 2 nodes and append the result until there is only
9875 // 1 node left, i.e. the final OR'd value of all vectors.
9876 SDValue LHS = VecIns[Slot];
9877 SDValue RHS = VecIns[Slot + 1];
9878 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
9881 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
9882 VecIns.back(), VecIns.back());
9885 /// \brief return true if \c Op has a use that doesn't just read flags.
9886 static bool hasNonFlagsUse(SDValue Op) {
9887 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
9890 unsigned UOpNo = UI.getOperandNo();
9891 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9892 // Look pass truncate.
9893 UOpNo = User->use_begin().getOperandNo();
9894 User = *User->use_begin();
9897 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
9898 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
9904 /// Emit nodes that will be selected as "test Op0,Op0", or something
9906 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
9907 SelectionDAG &DAG) const {
9908 if (Op.getValueType() == MVT::i1)
9909 // KORTEST instruction should be selected
9910 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9911 DAG.getConstant(0, Op.getValueType()));
9913 // CF and OF aren't always set the way we want. Determine which
9914 // of these we need.
9915 bool NeedCF = false;
9916 bool NeedOF = false;
9919 case X86::COND_A: case X86::COND_AE:
9920 case X86::COND_B: case X86::COND_BE:
9923 case X86::COND_G: case X86::COND_GE:
9924 case X86::COND_L: case X86::COND_LE:
9925 case X86::COND_O: case X86::COND_NO:
9929 // See if we can use the EFLAGS value from the operand instead of
9930 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
9931 // we prove that the arithmetic won't overflow, we can't use OF or CF.
9932 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
9933 // Emit a CMP with 0, which is the TEST pattern.
9934 //if (Op.getValueType() == MVT::i1)
9935 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
9936 // DAG.getConstant(0, MVT::i1));
9937 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9938 DAG.getConstant(0, Op.getValueType()));
9940 unsigned Opcode = 0;
9941 unsigned NumOperands = 0;
9943 // Truncate operations may prevent the merge of the SETCC instruction
9944 // and the arithmetic instruction before it. Attempt to truncate the operands
9945 // of the arithmetic instruction and use a reduced bit-width instruction.
9946 bool NeedTruncation = false;
9947 SDValue ArithOp = Op;
9948 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
9949 SDValue Arith = Op->getOperand(0);
9950 // Both the trunc and the arithmetic op need to have one user each.
9951 if (Arith->hasOneUse())
9952 switch (Arith.getOpcode()) {
9959 NeedTruncation = true;
9965 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
9966 // which may be the result of a CAST. We use the variable 'Op', which is the
9967 // non-casted variable when we check for possible users.
9968 switch (ArithOp.getOpcode()) {
9970 // Due to an isel shortcoming, be conservative if this add is likely to be
9971 // selected as part of a load-modify-store instruction. When the root node
9972 // in a match is a store, isel doesn't know how to remap non-chain non-flag
9973 // uses of other nodes in the match, such as the ADD in this case. This
9974 // leads to the ADD being left around and reselected, with the result being
9975 // two adds in the output. Alas, even if none our users are stores, that
9976 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
9977 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
9978 // climbing the DAG back to the root, and it doesn't seem to be worth the
9980 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9981 UE = Op.getNode()->use_end(); UI != UE; ++UI)
9982 if (UI->getOpcode() != ISD::CopyToReg &&
9983 UI->getOpcode() != ISD::SETCC &&
9984 UI->getOpcode() != ISD::STORE)
9987 if (ConstantSDNode *C =
9988 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
9989 // An add of one will be selected as an INC.
9990 if (C->getAPIntValue() == 1) {
9991 Opcode = X86ISD::INC;
9996 // An add of negative one (subtract of one) will be selected as a DEC.
9997 if (C->getAPIntValue().isAllOnesValue()) {
9998 Opcode = X86ISD::DEC;
10004 // Otherwise use a regular EFLAGS-setting add.
10005 Opcode = X86ISD::ADD;
10010 // If we have a constant logical shift that's only used in a comparison
10011 // against zero turn it into an equivalent AND. This allows turning it into
10012 // a TEST instruction later.
10013 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) &&
10014 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
10015 EVT VT = Op.getValueType();
10016 unsigned BitWidth = VT.getSizeInBits();
10017 unsigned ShAmt = Op->getConstantOperandVal(1);
10018 if (ShAmt >= BitWidth) // Avoid undefined shifts.
10020 APInt Mask = ArithOp.getOpcode() == ISD::SRL
10021 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
10022 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
10023 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
10025 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
10026 DAG.getConstant(Mask, VT));
10027 DAG.ReplaceAllUsesWith(Op, New);
10033 // If the primary and result isn't used, don't bother using X86ISD::AND,
10034 // because a TEST instruction will be better.
10035 if (!hasNonFlagsUse(Op))
10041 // Due to the ISEL shortcoming noted above, be conservative if this op is
10042 // likely to be selected as part of a load-modify-store instruction.
10043 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
10044 UE = Op.getNode()->use_end(); UI != UE; ++UI)
10045 if (UI->getOpcode() == ISD::STORE)
10048 // Otherwise use a regular EFLAGS-setting instruction.
10049 switch (ArithOp.getOpcode()) {
10050 default: llvm_unreachable("unexpected operator!");
10051 case ISD::SUB: Opcode = X86ISD::SUB; break;
10052 case ISD::XOR: Opcode = X86ISD::XOR; break;
10053 case ISD::AND: Opcode = X86ISD::AND; break;
10055 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
10056 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
10057 if (EFLAGS.getNode())
10060 Opcode = X86ISD::OR;
10074 return SDValue(Op.getNode(), 1);
10080 // If we found that truncation is beneficial, perform the truncation and
10082 if (NeedTruncation) {
10083 EVT VT = Op.getValueType();
10084 SDValue WideVal = Op->getOperand(0);
10085 EVT WideVT = WideVal.getValueType();
10086 unsigned ConvertedOp = 0;
10087 // Use a target machine opcode to prevent further DAGCombine
10088 // optimizations that may separate the arithmetic operations
10089 // from the setcc node.
10090 switch (WideVal.getOpcode()) {
10092 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
10093 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
10094 case ISD::AND: ConvertedOp = X86ISD::AND; break;
10095 case ISD::OR: ConvertedOp = X86ISD::OR; break;
10096 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
10100 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10101 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
10102 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
10103 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
10104 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
10110 // Emit a CMP with 0, which is the TEST pattern.
10111 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10112 DAG.getConstant(0, Op.getValueType()));
10114 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10115 SmallVector<SDValue, 4> Ops;
10116 for (unsigned i = 0; i != NumOperands; ++i)
10117 Ops.push_back(Op.getOperand(i));
10119 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
10120 DAG.ReplaceAllUsesWith(Op, New);
10121 return SDValue(New.getNode(), 1);
10124 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
10126 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
10127 SDLoc dl, SelectionDAG &DAG) const {
10128 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
10129 if (C->getAPIntValue() == 0)
10130 return EmitTest(Op0, X86CC, dl, DAG);
10132 if (Op0.getValueType() == MVT::i1)
10133 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
10136 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
10137 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
10138 // Do the comparison at i32 if it's smaller, besides the Atom case.
10139 // This avoids subregister aliasing issues. Keep the smaller reference
10140 // if we're optimizing for size, however, as that'll allow better folding
10141 // of memory operations.
10142 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
10143 !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
10144 AttributeSet::FunctionIndex, Attribute::MinSize) &&
10145 !Subtarget->isAtom()) {
10146 unsigned ExtendOp =
10147 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
10148 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
10149 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
10151 // Use SUB instead of CMP to enable CSE between SUB and CMP.
10152 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
10153 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
10155 return SDValue(Sub.getNode(), 1);
10157 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
10160 /// Convert a comparison if required by the subtarget.
10161 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
10162 SelectionDAG &DAG) const {
10163 // If the subtarget does not support the FUCOMI instruction, floating-point
10164 // comparisons have to be converted.
10165 if (Subtarget->hasCMov() ||
10166 Cmp.getOpcode() != X86ISD::CMP ||
10167 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
10168 !Cmp.getOperand(1).getValueType().isFloatingPoint())
10171 // The instruction selector will select an FUCOM instruction instead of
10172 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
10173 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
10174 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
10176 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
10177 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
10178 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
10179 DAG.getConstant(8, MVT::i8));
10180 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
10181 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
10184 static bool isAllOnes(SDValue V) {
10185 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10186 return C && C->isAllOnesValue();
10189 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
10190 /// if it's possible.
10191 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
10192 SDLoc dl, SelectionDAG &DAG) const {
10193 SDValue Op0 = And.getOperand(0);
10194 SDValue Op1 = And.getOperand(1);
10195 if (Op0.getOpcode() == ISD::TRUNCATE)
10196 Op0 = Op0.getOperand(0);
10197 if (Op1.getOpcode() == ISD::TRUNCATE)
10198 Op1 = Op1.getOperand(0);
10201 if (Op1.getOpcode() == ISD::SHL)
10202 std::swap(Op0, Op1);
10203 if (Op0.getOpcode() == ISD::SHL) {
10204 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
10205 if (And00C->getZExtValue() == 1) {
10206 // If we looked past a truncate, check that it's only truncating away
10208 unsigned BitWidth = Op0.getValueSizeInBits();
10209 unsigned AndBitWidth = And.getValueSizeInBits();
10210 if (BitWidth > AndBitWidth) {
10212 DAG.ComputeMaskedBits(Op0, Zeros, Ones);
10213 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
10217 RHS = Op0.getOperand(1);
10219 } else if (Op1.getOpcode() == ISD::Constant) {
10220 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
10221 uint64_t AndRHSVal = AndRHS->getZExtValue();
10222 SDValue AndLHS = Op0;
10224 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
10225 LHS = AndLHS.getOperand(0);
10226 RHS = AndLHS.getOperand(1);
10229 // Use BT if the immediate can't be encoded in a TEST instruction.
10230 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
10232 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
10236 if (LHS.getNode()) {
10237 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
10238 // instruction. Since the shift amount is in-range-or-undefined, we know
10239 // that doing a bittest on the i32 value is ok. We extend to i32 because
10240 // the encoding for the i16 version is larger than the i32 version.
10241 // Also promote i16 to i32 for performance / code size reason.
10242 if (LHS.getValueType() == MVT::i8 ||
10243 LHS.getValueType() == MVT::i16)
10244 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
10246 // If the operand types disagree, extend the shift amount to match. Since
10247 // BT ignores high bits (like shifts) we can use anyextend.
10248 if (LHS.getValueType() != RHS.getValueType())
10249 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
10251 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
10252 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
10253 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10254 DAG.getConstant(Cond, MVT::i8), BT);
10260 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
10262 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
10267 // SSE Condition code mapping:
10276 switch (SetCCOpcode) {
10277 default: llvm_unreachable("Unexpected SETCC condition");
10279 case ISD::SETEQ: SSECC = 0; break;
10281 case ISD::SETGT: Swap = true; // Fallthrough
10283 case ISD::SETOLT: SSECC = 1; break;
10285 case ISD::SETGE: Swap = true; // Fallthrough
10287 case ISD::SETOLE: SSECC = 2; break;
10288 case ISD::SETUO: SSECC = 3; break;
10290 case ISD::SETNE: SSECC = 4; break;
10291 case ISD::SETULE: Swap = true; // Fallthrough
10292 case ISD::SETUGE: SSECC = 5; break;
10293 case ISD::SETULT: Swap = true; // Fallthrough
10294 case ISD::SETUGT: SSECC = 6; break;
10295 case ISD::SETO: SSECC = 7; break;
10297 case ISD::SETONE: SSECC = 8; break;
10300 std::swap(Op0, Op1);
10305 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
10306 // ones, and then concatenate the result back.
10307 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
10308 MVT VT = Op.getSimpleValueType();
10310 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
10311 "Unsupported value type for operation");
10313 unsigned NumElems = VT.getVectorNumElements();
10315 SDValue CC = Op.getOperand(2);
10317 // Extract the LHS vectors
10318 SDValue LHS = Op.getOperand(0);
10319 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10320 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10322 // Extract the RHS vectors
10323 SDValue RHS = Op.getOperand(1);
10324 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10325 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10327 // Issue the operation on the smaller types and concatenate the result back
10328 MVT EltVT = VT.getVectorElementType();
10329 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10330 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10331 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
10332 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
10335 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
10336 const X86Subtarget *Subtarget) {
10337 SDValue Op0 = Op.getOperand(0);
10338 SDValue Op1 = Op.getOperand(1);
10339 SDValue CC = Op.getOperand(2);
10340 MVT VT = Op.getSimpleValueType();
10343 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
10344 Op.getValueType().getScalarType() == MVT::i1 &&
10345 "Cannot set masked compare for this operation");
10347 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10349 bool Unsigned = false;
10352 switch (SetCCOpcode) {
10353 default: llvm_unreachable("Unexpected SETCC condition");
10354 case ISD::SETNE: SSECC = 4; break;
10355 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
10356 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
10357 case ISD::SETLT: Swap = true; //fall-through
10358 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
10359 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
10360 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
10361 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
10362 case ISD::SETULE: Unsigned = true; //fall-through
10363 case ISD::SETLE: SSECC = 2; break;
10367 std::swap(Op0, Op1);
10369 return DAG.getNode(Opc, dl, VT, Op0, Op1);
10370 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
10371 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10372 DAG.getConstant(SSECC, MVT::i8));
10375 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
10376 /// operand \p Op1. If non-trivial (for example because it's not constant)
10377 /// return an empty value.
10378 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
10380 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
10384 MVT VT = Op1.getSimpleValueType();
10385 MVT EVT = VT.getVectorElementType();
10386 unsigned n = VT.getVectorNumElements();
10387 SmallVector<SDValue, 8> ULTOp1;
10389 for (unsigned i = 0; i < n; ++i) {
10390 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
10391 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
10394 // Avoid underflow.
10395 APInt Val = Elt->getAPIntValue();
10399 ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
10402 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
10405 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
10406 SelectionDAG &DAG) {
10407 SDValue Op0 = Op.getOperand(0);
10408 SDValue Op1 = Op.getOperand(1);
10409 SDValue CC = Op.getOperand(2);
10410 MVT VT = Op.getSimpleValueType();
10411 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10412 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10417 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10418 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10421 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10422 unsigned Opc = X86ISD::CMPP;
10423 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10424 assert(VT.getVectorNumElements() <= 16);
10425 Opc = X86ISD::CMPM;
10427 // In the two special cases we can't handle, emit two comparisons.
10430 unsigned CombineOpc;
10431 if (SetCCOpcode == ISD::SETUEQ) {
10432 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10434 assert(SetCCOpcode == ISD::SETONE);
10435 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10438 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10439 DAG.getConstant(CC0, MVT::i8));
10440 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10441 DAG.getConstant(CC1, MVT::i8));
10442 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10444 // Handle all other FP comparisons here.
10445 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10446 DAG.getConstant(SSECC, MVT::i8));
10449 // Break 256-bit integer vector compare into smaller ones.
10450 if (VT.is256BitVector() && !Subtarget->hasInt256())
10451 return Lower256IntVSETCC(Op, DAG);
10453 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10454 EVT OpVT = Op1.getValueType();
10455 if (Subtarget->hasAVX512()) {
10456 if (Op1.getValueType().is512BitVector() ||
10457 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10458 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
10460 // In AVX-512 architecture setcc returns mask with i1 elements,
10461 // But there is no compare instruction for i8 and i16 elements.
10462 // We are not talking about 512-bit operands in this case, these
10463 // types are illegal.
10465 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10466 OpVT.getVectorElementType().getSizeInBits() >= 8))
10467 return DAG.getNode(ISD::TRUNCATE, dl, VT,
10468 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10471 // We are handling one of the integer comparisons here. Since SSE only has
10472 // GT and EQ comparisons for integer, swapping operands and multiple
10473 // operations may be required for some comparisons.
10475 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10476 bool Subus = false;
10478 switch (SetCCOpcode) {
10479 default: llvm_unreachable("Unexpected SETCC condition");
10480 case ISD::SETNE: Invert = true;
10481 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
10482 case ISD::SETLT: Swap = true;
10483 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
10484 case ISD::SETGE: Swap = true;
10485 case ISD::SETLE: Opc = X86ISD::PCMPGT;
10486 Invert = true; break;
10487 case ISD::SETULT: Swap = true;
10488 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
10489 FlipSigns = true; break;
10490 case ISD::SETUGE: Swap = true;
10491 case ISD::SETULE: Opc = X86ISD::PCMPGT;
10492 FlipSigns = true; Invert = true; break;
10495 // Special case: Use min/max operations for SETULE/SETUGE
10496 MVT VET = VT.getVectorElementType();
10498 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10499 || (Subtarget->hasSSE2() && (VET == MVT::i8));
10502 switch (SetCCOpcode) {
10504 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10505 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10508 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10511 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
10512 if (!MinMax && hasSubus) {
10513 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
10515 // t = psubus Op0, Op1
10516 // pcmpeq t, <0..0>
10517 switch (SetCCOpcode) {
10519 case ISD::SETULT: {
10520 // If the comparison is against a constant we can turn this into a
10521 // setule. With psubus, setule does not require a swap. This is
10522 // beneficial because the constant in the register is no longer
10523 // destructed as the destination so it can be hoisted out of a loop.
10524 // Only do this pre-AVX since vpcmp* is no longer destructive.
10525 if (Subtarget->hasAVX())
10527 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
10528 if (ULEOp1.getNode()) {
10530 Subus = true; Invert = false; Swap = false;
10534 // Psubus is better than flip-sign because it requires no inversion.
10535 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
10536 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
10540 Opc = X86ISD::SUBUS;
10546 std::swap(Op0, Op1);
10548 // Check that the operation in question is available (most are plain SSE2,
10549 // but PCMPGTQ and PCMPEQQ have different requirements).
10550 if (VT == MVT::v2i64) {
10551 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10552 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10554 // First cast everything to the right type.
10555 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10556 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10558 // Since SSE has no unsigned integer comparisons, we need to flip the sign
10559 // bits of the inputs before performing those operations. The lower
10560 // compare is always unsigned.
10563 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10565 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10566 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10567 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10568 Sign, Zero, Sign, Zero);
10570 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10571 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10573 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10574 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10575 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10577 // Create masks for only the low parts/high parts of the 64 bit integers.
10578 static const int MaskHi[] = { 1, 1, 3, 3 };
10579 static const int MaskLo[] = { 0, 0, 2, 2 };
10580 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10581 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10582 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10584 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10585 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10588 Result = DAG.getNOT(dl, Result, MVT::v4i32);
10590 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10593 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10594 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10595 // pcmpeqd + pshufd + pand.
10596 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10598 // First cast everything to the right type.
10599 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10600 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10603 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
10605 // Make sure the lower and upper halves are both all-ones.
10606 static const int Mask[] = { 1, 0, 3, 2 };
10607 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
10608 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
10611 Result = DAG.getNOT(dl, Result, MVT::v4i32);
10613 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10617 // Since SSE has no unsigned integer comparisons, we need to flip the sign
10618 // bits of the inputs before performing those operations.
10620 EVT EltVT = VT.getVectorElementType();
10621 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
10622 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
10623 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
10626 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
10628 // If the logical-not of the result is required, perform that now.
10630 Result = DAG.getNOT(dl, Result, VT);
10633 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
10636 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
10637 getZeroVector(VT, Subtarget, DAG, dl));
10642 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
10644 MVT VT = Op.getSimpleValueType();
10646 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
10648 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
10649 && "SetCC type must be 8-bit or 1-bit integer");
10650 SDValue Op0 = Op.getOperand(0);
10651 SDValue Op1 = Op.getOperand(1);
10653 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10655 // Optimize to BT if possible.
10656 // Lower (X & (1 << N)) == 0 to BT(X, N).
10657 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
10658 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
10659 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
10660 Op1.getOpcode() == ISD::Constant &&
10661 cast<ConstantSDNode>(Op1)->isNullValue() &&
10662 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10663 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
10664 if (NewSetCC.getNode())
10668 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
10670 if (Op1.getOpcode() == ISD::Constant &&
10671 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
10672 cast<ConstantSDNode>(Op1)->isNullValue()) &&
10673 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10675 // If the input is a setcc, then reuse the input setcc or use a new one with
10676 // the inverted condition.
10677 if (Op0.getOpcode() == X86ISD::SETCC) {
10678 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
10679 bool Invert = (CC == ISD::SETNE) ^
10680 cast<ConstantSDNode>(Op1)->isNullValue();
10684 CCode = X86::GetOppositeBranchCondition(CCode);
10685 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10686 DAG.getConstant(CCode, MVT::i8),
10687 Op0.getOperand(1));
10689 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10693 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
10694 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
10695 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10697 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
10698 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
10701 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
10702 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
10703 if (X86CC == X86::COND_INVALID)
10706 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
10707 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
10708 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10709 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
10711 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10715 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10716 static bool isX86LogicalCmp(SDValue Op) {
10717 unsigned Opc = Op.getNode()->getOpcode();
10718 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10719 Opc == X86ISD::SAHF)
10721 if (Op.getResNo() == 1 &&
10722 (Opc == X86ISD::ADD ||
10723 Opc == X86ISD::SUB ||
10724 Opc == X86ISD::ADC ||
10725 Opc == X86ISD::SBB ||
10726 Opc == X86ISD::SMUL ||
10727 Opc == X86ISD::UMUL ||
10728 Opc == X86ISD::INC ||
10729 Opc == X86ISD::DEC ||
10730 Opc == X86ISD::OR ||
10731 Opc == X86ISD::XOR ||
10732 Opc == X86ISD::AND))
10735 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
10741 static bool isZero(SDValue V) {
10742 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10743 return C && C->isNullValue();
10746 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
10747 if (V.getOpcode() != ISD::TRUNCATE)
10750 SDValue VOp0 = V.getOperand(0);
10751 unsigned InBits = VOp0.getValueSizeInBits();
10752 unsigned Bits = V.getValueSizeInBits();
10753 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
10756 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
10757 bool addTest = true;
10758 SDValue Cond = Op.getOperand(0);
10759 SDValue Op1 = Op.getOperand(1);
10760 SDValue Op2 = Op.getOperand(2);
10762 EVT VT = Op1.getValueType();
10765 // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
10766 // are available. Otherwise fp cmovs get lowered into a less efficient branch
10767 // sequence later on.
10768 if (Cond.getOpcode() == ISD::SETCC &&
10769 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
10770 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
10771 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
10772 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
10773 int SSECC = translateX86FSETCC(
10774 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
10777 if (Subtarget->hasAVX512()) {
10778 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
10779 DAG.getConstant(SSECC, MVT::i8));
10780 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
10782 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
10783 DAG.getConstant(SSECC, MVT::i8));
10784 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
10785 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
10786 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
10790 if (Cond.getOpcode() == ISD::SETCC) {
10791 SDValue NewCond = LowerSETCC(Cond, DAG);
10792 if (NewCond.getNode())
10796 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
10797 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
10798 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
10799 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
10800 if (Cond.getOpcode() == X86ISD::SETCC &&
10801 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
10802 isZero(Cond.getOperand(1).getOperand(1))) {
10803 SDValue Cmp = Cond.getOperand(1);
10805 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
10807 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
10808 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
10809 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
10811 SDValue CmpOp0 = Cmp.getOperand(0);
10812 // Apply further optimizations for special cases
10813 // (select (x != 0), -1, 0) -> neg & sbb
10814 // (select (x == 0), 0, -1) -> neg & sbb
10815 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
10816 if (YC->isNullValue() &&
10817 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
10818 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
10819 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
10820 DAG.getConstant(0, CmpOp0.getValueType()),
10822 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10823 DAG.getConstant(X86::COND_B, MVT::i8),
10824 SDValue(Neg.getNode(), 1));
10828 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10829 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10830 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10832 SDValue Res = // Res = 0 or -1.
10833 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10834 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
10836 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
10837 Res = DAG.getNOT(DL, Res, Res.getValueType());
10839 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
10840 if (!N2C || !N2C->isNullValue())
10841 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
10846 // Look past (and (setcc_carry (cmp ...)), 1).
10847 if (Cond.getOpcode() == ISD::AND &&
10848 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10849 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10850 if (C && C->getAPIntValue() == 1)
10851 Cond = Cond.getOperand(0);
10854 // If condition flag is set by a X86ISD::CMP, then use it as the condition
10855 // setting operand in place of the X86ISD::SETCC.
10856 unsigned CondOpcode = Cond.getOpcode();
10857 if (CondOpcode == X86ISD::SETCC ||
10858 CondOpcode == X86ISD::SETCC_CARRY) {
10859 CC = Cond.getOperand(0);
10861 SDValue Cmp = Cond.getOperand(1);
10862 unsigned Opc = Cmp.getOpcode();
10863 MVT VT = Op.getSimpleValueType();
10865 bool IllegalFPCMov = false;
10866 if (VT.isFloatingPoint() && !VT.isVector() &&
10867 !isScalarFPTypeInSSEReg(VT)) // FPStack?
10868 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
10870 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
10871 Opc == X86ISD::BT) { // FIXME
10875 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10876 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10877 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10878 Cond.getOperand(0).getValueType() != MVT::i8)) {
10879 SDValue LHS = Cond.getOperand(0);
10880 SDValue RHS = Cond.getOperand(1);
10881 unsigned X86Opcode;
10884 switch (CondOpcode) {
10885 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10886 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10887 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10888 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10889 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10890 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10891 default: llvm_unreachable("unexpected overflowing operator");
10893 if (CondOpcode == ISD::UMULO)
10894 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10897 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10899 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
10901 if (CondOpcode == ISD::UMULO)
10902 Cond = X86Op.getValue(2);
10904 Cond = X86Op.getValue(1);
10906 CC = DAG.getConstant(X86Cond, MVT::i8);
10911 // Look pass the truncate if the high bits are known zero.
10912 if (isTruncWithZeroHighBitsInput(Cond, DAG))
10913 Cond = Cond.getOperand(0);
10915 // We know the result of AND is compared against zero. Try to match
10917 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10918 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
10919 if (NewSetCC.getNode()) {
10920 CC = NewSetCC.getOperand(0);
10921 Cond = NewSetCC.getOperand(1);
10928 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10929 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
10932 // a < b ? -1 : 0 -> RES = ~setcc_carry
10933 // a < b ? 0 : -1 -> RES = setcc_carry
10934 // a >= b ? -1 : 0 -> RES = setcc_carry
10935 // a >= b ? 0 : -1 -> RES = ~setcc_carry
10936 if (Cond.getOpcode() == X86ISD::SUB) {
10937 Cond = ConvertCmpIfNecessary(Cond, DAG);
10938 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
10940 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
10941 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
10942 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10943 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
10944 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
10945 return DAG.getNOT(DL, Res, Res.getValueType());
10950 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
10951 // widen the cmov and push the truncate through. This avoids introducing a new
10952 // branch during isel and doesn't add any extensions.
10953 if (Op.getValueType() == MVT::i8 &&
10954 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
10955 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
10956 if (T1.getValueType() == T2.getValueType() &&
10957 // Blacklist CopyFromReg to avoid partial register stalls.
10958 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
10959 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
10960 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
10961 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
10965 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
10966 // condition is true.
10967 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
10968 SDValue Ops[] = { Op2, Op1, CC, Cond };
10969 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
10972 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
10973 MVT VT = Op->getSimpleValueType(0);
10974 SDValue In = Op->getOperand(0);
10975 MVT InVT = In.getSimpleValueType();
10978 unsigned int NumElts = VT.getVectorNumElements();
10979 if (NumElts != 8 && NumElts != 16)
10982 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
10983 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10985 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10986 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
10988 MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
10989 Constant *C = ConstantInt::get(*DAG.getContext(),
10990 APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
10992 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
10993 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
10994 SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
10995 MachinePointerInfo::getConstantPool(),
10996 false, false, false, Alignment);
10997 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
10998 if (VT.is512BitVector())
11000 return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
11003 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11004 SelectionDAG &DAG) {
11005 MVT VT = Op->getSimpleValueType(0);
11006 SDValue In = Op->getOperand(0);
11007 MVT InVT = In.getSimpleValueType();
11010 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
11011 return LowerSIGN_EXTEND_AVX512(Op, DAG);
11013 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
11014 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
11015 (VT != MVT::v16i16 || InVT != MVT::v16i8))
11018 if (Subtarget->hasInt256())
11019 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
11021 // Optimize vectors in AVX mode
11022 // Sign extend v8i16 to v8i32 and
11025 // Divide input vector into two parts
11026 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
11027 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
11028 // concat the vectors to original VT
11030 unsigned NumElems = InVT.getVectorNumElements();
11031 SDValue Undef = DAG.getUNDEF(InVT);
11033 SmallVector<int,8> ShufMask1(NumElems, -1);
11034 for (unsigned i = 0; i != NumElems/2; ++i)
11037 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
11039 SmallVector<int,8> ShufMask2(NumElems, -1);
11040 for (unsigned i = 0; i != NumElems/2; ++i)
11041 ShufMask2[i] = i + NumElems/2;
11043 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
11045 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
11046 VT.getVectorNumElements()/2);
11048 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
11049 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
11051 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11054 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
11055 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
11056 // from the AND / OR.
11057 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
11058 Opc = Op.getOpcode();
11059 if (Opc != ISD::OR && Opc != ISD::AND)
11061 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
11062 Op.getOperand(0).hasOneUse() &&
11063 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
11064 Op.getOperand(1).hasOneUse());
11067 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
11068 // 1 and that the SETCC node has a single use.
11069 static bool isXor1OfSetCC(SDValue Op) {
11070 if (Op.getOpcode() != ISD::XOR)
11072 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
11073 if (N1C && N1C->getAPIntValue() == 1) {
11074 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
11075 Op.getOperand(0).hasOneUse();
11080 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
11081 bool addTest = true;
11082 SDValue Chain = Op.getOperand(0);
11083 SDValue Cond = Op.getOperand(1);
11084 SDValue Dest = Op.getOperand(2);
11087 bool Inverted = false;
11089 if (Cond.getOpcode() == ISD::SETCC) {
11090 // Check for setcc([su]{add,sub,mul}o == 0).
11091 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
11092 isa<ConstantSDNode>(Cond.getOperand(1)) &&
11093 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
11094 Cond.getOperand(0).getResNo() == 1 &&
11095 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
11096 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
11097 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
11098 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
11099 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
11100 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
11102 Cond = Cond.getOperand(0);
11104 SDValue NewCond = LowerSETCC(Cond, DAG);
11105 if (NewCond.getNode())
11110 // FIXME: LowerXALUO doesn't handle these!!
11111 else if (Cond.getOpcode() == X86ISD::ADD ||
11112 Cond.getOpcode() == X86ISD::SUB ||
11113 Cond.getOpcode() == X86ISD::SMUL ||
11114 Cond.getOpcode() == X86ISD::UMUL)
11115 Cond = LowerXALUO(Cond, DAG);
11118 // Look pass (and (setcc_carry (cmp ...)), 1).
11119 if (Cond.getOpcode() == ISD::AND &&
11120 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
11121 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11122 if (C && C->getAPIntValue() == 1)
11123 Cond = Cond.getOperand(0);
11126 // If condition flag is set by a X86ISD::CMP, then use it as the condition
11127 // setting operand in place of the X86ISD::SETCC.
11128 unsigned CondOpcode = Cond.getOpcode();
11129 if (CondOpcode == X86ISD::SETCC ||
11130 CondOpcode == X86ISD::SETCC_CARRY) {
11131 CC = Cond.getOperand(0);
11133 SDValue Cmp = Cond.getOperand(1);
11134 unsigned Opc = Cmp.getOpcode();
11135 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
11136 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
11140 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
11144 // These can only come from an arithmetic instruction with overflow,
11145 // e.g. SADDO, UADDO.
11146 Cond = Cond.getNode()->getOperand(1);
11152 CondOpcode = Cond.getOpcode();
11153 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11154 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11155 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11156 Cond.getOperand(0).getValueType() != MVT::i8)) {
11157 SDValue LHS = Cond.getOperand(0);
11158 SDValue RHS = Cond.getOperand(1);
11159 unsigned X86Opcode;
11162 // Keep this in sync with LowerXALUO, otherwise we might create redundant
11163 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
11165 switch (CondOpcode) {
11166 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11168 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11170 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
11173 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11174 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11176 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11178 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
11181 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11182 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11183 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11184 default: llvm_unreachable("unexpected overflowing operator");
11187 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
11188 if (CondOpcode == ISD::UMULO)
11189 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11192 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11194 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
11196 if (CondOpcode == ISD::UMULO)
11197 Cond = X86Op.getValue(2);
11199 Cond = X86Op.getValue(1);
11201 CC = DAG.getConstant(X86Cond, MVT::i8);
11205 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
11206 SDValue Cmp = Cond.getOperand(0).getOperand(1);
11207 if (CondOpc == ISD::OR) {
11208 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
11209 // two branches instead of an explicit OR instruction with a
11211 if (Cmp == Cond.getOperand(1).getOperand(1) &&
11212 isX86LogicalCmp(Cmp)) {
11213 CC = Cond.getOperand(0).getOperand(0);
11214 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11215 Chain, Dest, CC, Cmp);
11216 CC = Cond.getOperand(1).getOperand(0);
11220 } else { // ISD::AND
11221 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
11222 // two branches instead of an explicit AND instruction with a
11223 // separate test. However, we only do this if this block doesn't
11224 // have a fall-through edge, because this requires an explicit
11225 // jmp when the condition is false.
11226 if (Cmp == Cond.getOperand(1).getOperand(1) &&
11227 isX86LogicalCmp(Cmp) &&
11228 Op.getNode()->hasOneUse()) {
11229 X86::CondCode CCode =
11230 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11231 CCode = X86::GetOppositeBranchCondition(CCode);
11232 CC = DAG.getConstant(CCode, MVT::i8);
11233 SDNode *User = *Op.getNode()->use_begin();
11234 // Look for an unconditional branch following this conditional branch.
11235 // We need this because we need to reverse the successors in order
11236 // to implement FCMP_OEQ.
11237 if (User->getOpcode() == ISD::BR) {
11238 SDValue FalseBB = User->getOperand(1);
11240 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11241 assert(NewBR == User);
11245 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11246 Chain, Dest, CC, Cmp);
11247 X86::CondCode CCode =
11248 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
11249 CCode = X86::GetOppositeBranchCondition(CCode);
11250 CC = DAG.getConstant(CCode, MVT::i8);
11256 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
11257 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
11258 // It should be transformed during dag combiner except when the condition
11259 // is set by a arithmetics with overflow node.
11260 X86::CondCode CCode =
11261 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11262 CCode = X86::GetOppositeBranchCondition(CCode);
11263 CC = DAG.getConstant(CCode, MVT::i8);
11264 Cond = Cond.getOperand(0).getOperand(1);
11266 } else if (Cond.getOpcode() == ISD::SETCC &&
11267 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
11268 // For FCMP_OEQ, we can emit
11269 // two branches instead of an explicit AND instruction with a
11270 // separate test. However, we only do this if this block doesn't
11271 // have a fall-through edge, because this requires an explicit
11272 // jmp when the condition is false.
11273 if (Op.getNode()->hasOneUse()) {
11274 SDNode *User = *Op.getNode()->use_begin();
11275 // Look for an unconditional branch following this conditional branch.
11276 // We need this because we need to reverse the successors in order
11277 // to implement FCMP_OEQ.
11278 if (User->getOpcode() == ISD::BR) {
11279 SDValue FalseBB = User->getOperand(1);
11281 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11282 assert(NewBR == User);
11286 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11287 Cond.getOperand(0), Cond.getOperand(1));
11288 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11289 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11290 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11291 Chain, Dest, CC, Cmp);
11292 CC = DAG.getConstant(X86::COND_P, MVT::i8);
11297 } else if (Cond.getOpcode() == ISD::SETCC &&
11298 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
11299 // For FCMP_UNE, we can emit
11300 // two branches instead of an explicit AND instruction with a
11301 // separate test. However, we only do this if this block doesn't
11302 // have a fall-through edge, because this requires an explicit
11303 // jmp when the condition is false.
11304 if (Op.getNode()->hasOneUse()) {
11305 SDNode *User = *Op.getNode()->use_begin();
11306 // Look for an unconditional branch following this conditional branch.
11307 // We need this because we need to reverse the successors in order
11308 // to implement FCMP_UNE.
11309 if (User->getOpcode() == ISD::BR) {
11310 SDValue FalseBB = User->getOperand(1);
11312 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11313 assert(NewBR == User);
11316 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11317 Cond.getOperand(0), Cond.getOperand(1));
11318 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11319 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11320 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11321 Chain, Dest, CC, Cmp);
11322 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
11332 // Look pass the truncate if the high bits are known zero.
11333 if (isTruncWithZeroHighBitsInput(Cond, DAG))
11334 Cond = Cond.getOperand(0);
11336 // We know the result of AND is compared against zero. Try to match
11338 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11339 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
11340 if (NewSetCC.getNode()) {
11341 CC = NewSetCC.getOperand(0);
11342 Cond = NewSetCC.getOperand(1);
11349 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11350 Cond = EmitTest(Cond, X86::COND_NE, dl, DAG);
11352 Cond = ConvertCmpIfNecessary(Cond, DAG);
11353 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11354 Chain, Dest, CC, Cond);
11357 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
11358 // Calls to _alloca is needed to probe the stack when allocating more than 4k
11359 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
11360 // that the guard pages used by the OS virtual memory manager are allocated in
11361 // correct sequence.
11363 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
11364 SelectionDAG &DAG) const {
11365 MachineFunction &MF = DAG.getMachineFunction();
11366 bool SplitStack = MF.shouldSplitStack();
11367 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
11372 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11373 SDNode* Node = Op.getNode();
11375 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
11376 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
11377 " not tell us which reg is the stack pointer!");
11378 EVT VT = Node->getValueType(0);
11379 SDValue Tmp1 = SDValue(Node, 0);
11380 SDValue Tmp2 = SDValue(Node, 1);
11381 SDValue Tmp3 = Node->getOperand(2);
11382 SDValue Chain = Tmp1.getOperand(0);
11384 // Chain the dynamic stack allocation so that it doesn't modify the stack
11385 // pointer when other instructions are using the stack.
11386 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
11389 SDValue Size = Tmp2.getOperand(1);
11390 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
11391 Chain = SP.getValue(1);
11392 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
11393 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
11394 unsigned StackAlign = TFI.getStackAlignment();
11395 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
11396 if (Align > StackAlign)
11397 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
11398 DAG.getConstant(-(uint64_t)Align, VT));
11399 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
11401 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
11402 DAG.getIntPtrConstant(0, true), SDValue(),
11405 SDValue Ops[2] = { Tmp1, Tmp2 };
11406 return DAG.getMergeValues(Ops, dl);
11410 SDValue Chain = Op.getOperand(0);
11411 SDValue Size = Op.getOperand(1);
11412 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11413 EVT VT = Op.getNode()->getValueType(0);
11415 bool Is64Bit = Subtarget->is64Bit();
11416 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
11419 MachineRegisterInfo &MRI = MF.getRegInfo();
11422 // The 64 bit implementation of segmented stacks needs to clobber both r10
11423 // r11. This makes it impossible to use it along with nested parameters.
11424 const Function *F = MF.getFunction();
11426 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
11428 if (I->hasNestAttr())
11429 report_fatal_error("Cannot use segmented stacks with functions that "
11430 "have nested arguments.");
11433 const TargetRegisterClass *AddrRegClass =
11434 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
11435 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
11436 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
11437 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
11438 DAG.getRegister(Vreg, SPTy));
11439 SDValue Ops1[2] = { Value, Chain };
11440 return DAG.getMergeValues(Ops1, dl);
11443 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
11445 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
11446 Flag = Chain.getValue(1);
11447 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11449 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
11451 const X86RegisterInfo *RegInfo =
11452 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11453 unsigned SPReg = RegInfo->getStackRegister();
11454 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
11455 Chain = SP.getValue(1);
11458 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11459 DAG.getConstant(-(uint64_t)Align, VT));
11460 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
11463 SDValue Ops1[2] = { SP, Chain };
11464 return DAG.getMergeValues(Ops1, dl);
11468 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
11469 MachineFunction &MF = DAG.getMachineFunction();
11470 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
11472 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11475 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
11476 // vastart just stores the address of the VarArgsFrameIndex slot into the
11477 // memory location argument.
11478 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11480 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
11481 MachinePointerInfo(SV), false, false, 0);
11485 // gp_offset (0 - 6 * 8)
11486 // fp_offset (48 - 48 + 8 * 16)
11487 // overflow_arg_area (point to parameters coming in memory).
11489 SmallVector<SDValue, 8> MemOps;
11490 SDValue FIN = Op.getOperand(1);
11492 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
11493 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
11495 FIN, MachinePointerInfo(SV), false, false, 0);
11496 MemOps.push_back(Store);
11499 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11500 FIN, DAG.getIntPtrConstant(4));
11501 Store = DAG.getStore(Op.getOperand(0), DL,
11502 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
11504 FIN, MachinePointerInfo(SV, 4), false, false, 0);
11505 MemOps.push_back(Store);
11507 // Store ptr to overflow_arg_area
11508 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11509 FIN, DAG.getIntPtrConstant(4));
11510 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11512 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11513 MachinePointerInfo(SV, 8),
11515 MemOps.push_back(Store);
11517 // Store ptr to reg_save_area.
11518 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11519 FIN, DAG.getIntPtrConstant(8));
11520 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11522 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11523 MachinePointerInfo(SV, 16), false, false, 0);
11524 MemOps.push_back(Store);
11525 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
11528 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11529 assert(Subtarget->is64Bit() &&
11530 "LowerVAARG only handles 64-bit va_arg!");
11531 assert((Subtarget->isTargetLinux() ||
11532 Subtarget->isTargetDarwin()) &&
11533 "Unhandled target in LowerVAARG");
11534 assert(Op.getNode()->getNumOperands() == 4);
11535 SDValue Chain = Op.getOperand(0);
11536 SDValue SrcPtr = Op.getOperand(1);
11537 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11538 unsigned Align = Op.getConstantOperandVal(3);
11541 EVT ArgVT = Op.getNode()->getValueType(0);
11542 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11543 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11546 // Decide which area this value should be read from.
11547 // TODO: Implement the AMD64 ABI in its entirety. This simple
11548 // selection mechanism works only for the basic types.
11549 if (ArgVT == MVT::f80) {
11550 llvm_unreachable("va_arg for f80 not yet implemented");
11551 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11552 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
11553 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11554 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
11556 llvm_unreachable("Unhandled argument type in LowerVAARG");
11559 if (ArgMode == 2) {
11560 // Sanity Check: Make sure using fp_offset makes sense.
11561 assert(!getTargetMachine().Options.UseSoftFloat &&
11562 !(DAG.getMachineFunction()
11563 .getFunction()->getAttributes()
11564 .hasAttribute(AttributeSet::FunctionIndex,
11565 Attribute::NoImplicitFloat)) &&
11566 Subtarget->hasSSE1());
11569 // Insert VAARG_64 node into the DAG
11570 // VAARG_64 returns two values: Variable Argument Address, Chain
11571 SmallVector<SDValue, 11> InstOps;
11572 InstOps.push_back(Chain);
11573 InstOps.push_back(SrcPtr);
11574 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11575 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11576 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11577 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11578 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11579 VTs, InstOps, MVT::i64,
11580 MachinePointerInfo(SV),
11582 /*Volatile=*/false,
11584 /*WriteMem=*/true);
11585 Chain = VAARG.getValue(1);
11587 // Load the next argument and return it
11588 return DAG.getLoad(ArgVT, dl,
11591 MachinePointerInfo(),
11592 false, false, false, 0);
11595 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11596 SelectionDAG &DAG) {
11597 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
11598 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
11599 SDValue Chain = Op.getOperand(0);
11600 SDValue DstPtr = Op.getOperand(1);
11601 SDValue SrcPtr = Op.getOperand(2);
11602 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
11603 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11606 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
11607 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
11609 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
11612 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
11613 // amount is a constant. Takes immediate version of shift as input.
11614 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
11615 SDValue SrcOp, uint64_t ShiftAmt,
11616 SelectionDAG &DAG) {
11617 MVT ElementType = VT.getVectorElementType();
11619 // Fold this packed shift into its first operand if ShiftAmt is 0.
11623 // Check for ShiftAmt >= element width
11624 if (ShiftAmt >= ElementType.getSizeInBits()) {
11625 if (Opc == X86ISD::VSRAI)
11626 ShiftAmt = ElementType.getSizeInBits() - 1;
11628 return DAG.getConstant(0, VT);
11631 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
11632 && "Unknown target vector shift-by-constant node");
11634 // Fold this packed vector shift into a build vector if SrcOp is a
11635 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
11636 if (VT == SrcOp.getSimpleValueType() &&
11637 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
11638 SmallVector<SDValue, 8> Elts;
11639 unsigned NumElts = SrcOp->getNumOperands();
11640 ConstantSDNode *ND;
11643 default: llvm_unreachable(nullptr);
11644 case X86ISD::VSHLI:
11645 for (unsigned i=0; i!=NumElts; ++i) {
11646 SDValue CurrentOp = SrcOp->getOperand(i);
11647 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11648 Elts.push_back(CurrentOp);
11651 ND = cast<ConstantSDNode>(CurrentOp);
11652 const APInt &C = ND->getAPIntValue();
11653 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
11656 case X86ISD::VSRLI:
11657 for (unsigned i=0; i!=NumElts; ++i) {
11658 SDValue CurrentOp = SrcOp->getOperand(i);
11659 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11660 Elts.push_back(CurrentOp);
11663 ND = cast<ConstantSDNode>(CurrentOp);
11664 const APInt &C = ND->getAPIntValue();
11665 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
11668 case X86ISD::VSRAI:
11669 for (unsigned i=0; i!=NumElts; ++i) {
11670 SDValue CurrentOp = SrcOp->getOperand(i);
11671 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11672 Elts.push_back(CurrentOp);
11675 ND = cast<ConstantSDNode>(CurrentOp);
11676 const APInt &C = ND->getAPIntValue();
11677 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
11682 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
11685 return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
11688 // getTargetVShiftNode - Handle vector element shifts where the shift amount
11689 // may or may not be a constant. Takes immediate version of shift as input.
11690 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
11691 SDValue SrcOp, SDValue ShAmt,
11692 SelectionDAG &DAG) {
11693 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
11695 // Catch shift-by-constant.
11696 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
11697 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
11698 CShAmt->getZExtValue(), DAG);
11700 // Change opcode to non-immediate version
11702 default: llvm_unreachable("Unknown target vector shift node");
11703 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
11704 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
11705 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
11708 // Need to build a vector containing shift amount
11709 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
11712 ShOps[1] = DAG.getConstant(0, MVT::i32);
11713 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
11714 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
11716 // The return type has to be a 128-bit type with the same element
11717 // type as the input type.
11718 MVT EltVT = VT.getVectorElementType();
11719 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
11721 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
11722 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
11725 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
11727 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11729 default: return SDValue(); // Don't custom lower most intrinsics.
11730 // Comparison intrinsics.
11731 case Intrinsic::x86_sse_comieq_ss:
11732 case Intrinsic::x86_sse_comilt_ss:
11733 case Intrinsic::x86_sse_comile_ss:
11734 case Intrinsic::x86_sse_comigt_ss:
11735 case Intrinsic::x86_sse_comige_ss:
11736 case Intrinsic::x86_sse_comineq_ss:
11737 case Intrinsic::x86_sse_ucomieq_ss:
11738 case Intrinsic::x86_sse_ucomilt_ss:
11739 case Intrinsic::x86_sse_ucomile_ss:
11740 case Intrinsic::x86_sse_ucomigt_ss:
11741 case Intrinsic::x86_sse_ucomige_ss:
11742 case Intrinsic::x86_sse_ucomineq_ss:
11743 case Intrinsic::x86_sse2_comieq_sd:
11744 case Intrinsic::x86_sse2_comilt_sd:
11745 case Intrinsic::x86_sse2_comile_sd:
11746 case Intrinsic::x86_sse2_comigt_sd:
11747 case Intrinsic::x86_sse2_comige_sd:
11748 case Intrinsic::x86_sse2_comineq_sd:
11749 case Intrinsic::x86_sse2_ucomieq_sd:
11750 case Intrinsic::x86_sse2_ucomilt_sd:
11751 case Intrinsic::x86_sse2_ucomile_sd:
11752 case Intrinsic::x86_sse2_ucomigt_sd:
11753 case Intrinsic::x86_sse2_ucomige_sd:
11754 case Intrinsic::x86_sse2_ucomineq_sd: {
11758 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11759 case Intrinsic::x86_sse_comieq_ss:
11760 case Intrinsic::x86_sse2_comieq_sd:
11761 Opc = X86ISD::COMI;
11764 case Intrinsic::x86_sse_comilt_ss:
11765 case Intrinsic::x86_sse2_comilt_sd:
11766 Opc = X86ISD::COMI;
11769 case Intrinsic::x86_sse_comile_ss:
11770 case Intrinsic::x86_sse2_comile_sd:
11771 Opc = X86ISD::COMI;
11774 case Intrinsic::x86_sse_comigt_ss:
11775 case Intrinsic::x86_sse2_comigt_sd:
11776 Opc = X86ISD::COMI;
11779 case Intrinsic::x86_sse_comige_ss:
11780 case Intrinsic::x86_sse2_comige_sd:
11781 Opc = X86ISD::COMI;
11784 case Intrinsic::x86_sse_comineq_ss:
11785 case Intrinsic::x86_sse2_comineq_sd:
11786 Opc = X86ISD::COMI;
11789 case Intrinsic::x86_sse_ucomieq_ss:
11790 case Intrinsic::x86_sse2_ucomieq_sd:
11791 Opc = X86ISD::UCOMI;
11794 case Intrinsic::x86_sse_ucomilt_ss:
11795 case Intrinsic::x86_sse2_ucomilt_sd:
11796 Opc = X86ISD::UCOMI;
11799 case Intrinsic::x86_sse_ucomile_ss:
11800 case Intrinsic::x86_sse2_ucomile_sd:
11801 Opc = X86ISD::UCOMI;
11804 case Intrinsic::x86_sse_ucomigt_ss:
11805 case Intrinsic::x86_sse2_ucomigt_sd:
11806 Opc = X86ISD::UCOMI;
11809 case Intrinsic::x86_sse_ucomige_ss:
11810 case Intrinsic::x86_sse2_ucomige_sd:
11811 Opc = X86ISD::UCOMI;
11814 case Intrinsic::x86_sse_ucomineq_ss:
11815 case Intrinsic::x86_sse2_ucomineq_sd:
11816 Opc = X86ISD::UCOMI;
11821 SDValue LHS = Op.getOperand(1);
11822 SDValue RHS = Op.getOperand(2);
11823 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
11824 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
11825 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
11826 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11827 DAG.getConstant(X86CC, MVT::i8), Cond);
11828 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11831 // Arithmetic intrinsics.
11832 case Intrinsic::x86_sse2_pmulu_dq:
11833 case Intrinsic::x86_avx2_pmulu_dq:
11834 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
11835 Op.getOperand(1), Op.getOperand(2));
11837 case Intrinsic::x86_sse41_pmuldq:
11838 case Intrinsic::x86_avx2_pmul_dq:
11839 return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
11840 Op.getOperand(1), Op.getOperand(2));
11842 case Intrinsic::x86_sse2_pmulhu_w:
11843 case Intrinsic::x86_avx2_pmulhu_w:
11844 return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
11845 Op.getOperand(1), Op.getOperand(2));
11847 case Intrinsic::x86_sse2_pmulh_w:
11848 case Intrinsic::x86_avx2_pmulh_w:
11849 return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
11850 Op.getOperand(1), Op.getOperand(2));
11852 // SSE2/AVX2 sub with unsigned saturation intrinsics
11853 case Intrinsic::x86_sse2_psubus_b:
11854 case Intrinsic::x86_sse2_psubus_w:
11855 case Intrinsic::x86_avx2_psubus_b:
11856 case Intrinsic::x86_avx2_psubus_w:
11857 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
11858 Op.getOperand(1), Op.getOperand(2));
11860 // SSE3/AVX horizontal add/sub intrinsics
11861 case Intrinsic::x86_sse3_hadd_ps:
11862 case Intrinsic::x86_sse3_hadd_pd:
11863 case Intrinsic::x86_avx_hadd_ps_256:
11864 case Intrinsic::x86_avx_hadd_pd_256:
11865 case Intrinsic::x86_sse3_hsub_ps:
11866 case Intrinsic::x86_sse3_hsub_pd:
11867 case Intrinsic::x86_avx_hsub_ps_256:
11868 case Intrinsic::x86_avx_hsub_pd_256:
11869 case Intrinsic::x86_ssse3_phadd_w_128:
11870 case Intrinsic::x86_ssse3_phadd_d_128:
11871 case Intrinsic::x86_avx2_phadd_w:
11872 case Intrinsic::x86_avx2_phadd_d:
11873 case Intrinsic::x86_ssse3_phsub_w_128:
11874 case Intrinsic::x86_ssse3_phsub_d_128:
11875 case Intrinsic::x86_avx2_phsub_w:
11876 case Intrinsic::x86_avx2_phsub_d: {
11879 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11880 case Intrinsic::x86_sse3_hadd_ps:
11881 case Intrinsic::x86_sse3_hadd_pd:
11882 case Intrinsic::x86_avx_hadd_ps_256:
11883 case Intrinsic::x86_avx_hadd_pd_256:
11884 Opcode = X86ISD::FHADD;
11886 case Intrinsic::x86_sse3_hsub_ps:
11887 case Intrinsic::x86_sse3_hsub_pd:
11888 case Intrinsic::x86_avx_hsub_ps_256:
11889 case Intrinsic::x86_avx_hsub_pd_256:
11890 Opcode = X86ISD::FHSUB;
11892 case Intrinsic::x86_ssse3_phadd_w_128:
11893 case Intrinsic::x86_ssse3_phadd_d_128:
11894 case Intrinsic::x86_avx2_phadd_w:
11895 case Intrinsic::x86_avx2_phadd_d:
11896 Opcode = X86ISD::HADD;
11898 case Intrinsic::x86_ssse3_phsub_w_128:
11899 case Intrinsic::x86_ssse3_phsub_d_128:
11900 case Intrinsic::x86_avx2_phsub_w:
11901 case Intrinsic::x86_avx2_phsub_d:
11902 Opcode = X86ISD::HSUB;
11905 return DAG.getNode(Opcode, dl, Op.getValueType(),
11906 Op.getOperand(1), Op.getOperand(2));
11909 // SSE2/SSE41/AVX2 integer max/min intrinsics.
11910 case Intrinsic::x86_sse2_pmaxu_b:
11911 case Intrinsic::x86_sse41_pmaxuw:
11912 case Intrinsic::x86_sse41_pmaxud:
11913 case Intrinsic::x86_avx2_pmaxu_b:
11914 case Intrinsic::x86_avx2_pmaxu_w:
11915 case Intrinsic::x86_avx2_pmaxu_d:
11916 case Intrinsic::x86_sse2_pminu_b:
11917 case Intrinsic::x86_sse41_pminuw:
11918 case Intrinsic::x86_sse41_pminud:
11919 case Intrinsic::x86_avx2_pminu_b:
11920 case Intrinsic::x86_avx2_pminu_w:
11921 case Intrinsic::x86_avx2_pminu_d:
11922 case Intrinsic::x86_sse41_pmaxsb:
11923 case Intrinsic::x86_sse2_pmaxs_w:
11924 case Intrinsic::x86_sse41_pmaxsd:
11925 case Intrinsic::x86_avx2_pmaxs_b:
11926 case Intrinsic::x86_avx2_pmaxs_w:
11927 case Intrinsic::x86_avx2_pmaxs_d:
11928 case Intrinsic::x86_sse41_pminsb:
11929 case Intrinsic::x86_sse2_pmins_w:
11930 case Intrinsic::x86_sse41_pminsd:
11931 case Intrinsic::x86_avx2_pmins_b:
11932 case Intrinsic::x86_avx2_pmins_w:
11933 case Intrinsic::x86_avx2_pmins_d: {
11936 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11937 case Intrinsic::x86_sse2_pmaxu_b:
11938 case Intrinsic::x86_sse41_pmaxuw:
11939 case Intrinsic::x86_sse41_pmaxud:
11940 case Intrinsic::x86_avx2_pmaxu_b:
11941 case Intrinsic::x86_avx2_pmaxu_w:
11942 case Intrinsic::x86_avx2_pmaxu_d:
11943 Opcode = X86ISD::UMAX;
11945 case Intrinsic::x86_sse2_pminu_b:
11946 case Intrinsic::x86_sse41_pminuw:
11947 case Intrinsic::x86_sse41_pminud:
11948 case Intrinsic::x86_avx2_pminu_b:
11949 case Intrinsic::x86_avx2_pminu_w:
11950 case Intrinsic::x86_avx2_pminu_d:
11951 Opcode = X86ISD::UMIN;
11953 case Intrinsic::x86_sse41_pmaxsb:
11954 case Intrinsic::x86_sse2_pmaxs_w:
11955 case Intrinsic::x86_sse41_pmaxsd:
11956 case Intrinsic::x86_avx2_pmaxs_b:
11957 case Intrinsic::x86_avx2_pmaxs_w:
11958 case Intrinsic::x86_avx2_pmaxs_d:
11959 Opcode = X86ISD::SMAX;
11961 case Intrinsic::x86_sse41_pminsb:
11962 case Intrinsic::x86_sse2_pmins_w:
11963 case Intrinsic::x86_sse41_pminsd:
11964 case Intrinsic::x86_avx2_pmins_b:
11965 case Intrinsic::x86_avx2_pmins_w:
11966 case Intrinsic::x86_avx2_pmins_d:
11967 Opcode = X86ISD::SMIN;
11970 return DAG.getNode(Opcode, dl, Op.getValueType(),
11971 Op.getOperand(1), Op.getOperand(2));
11974 // SSE/SSE2/AVX floating point max/min intrinsics.
11975 case Intrinsic::x86_sse_max_ps:
11976 case Intrinsic::x86_sse2_max_pd:
11977 case Intrinsic::x86_avx_max_ps_256:
11978 case Intrinsic::x86_avx_max_pd_256:
11979 case Intrinsic::x86_sse_min_ps:
11980 case Intrinsic::x86_sse2_min_pd:
11981 case Intrinsic::x86_avx_min_ps_256:
11982 case Intrinsic::x86_avx_min_pd_256: {
11985 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11986 case Intrinsic::x86_sse_max_ps:
11987 case Intrinsic::x86_sse2_max_pd:
11988 case Intrinsic::x86_avx_max_ps_256:
11989 case Intrinsic::x86_avx_max_pd_256:
11990 Opcode = X86ISD::FMAX;
11992 case Intrinsic::x86_sse_min_ps:
11993 case Intrinsic::x86_sse2_min_pd:
11994 case Intrinsic::x86_avx_min_ps_256:
11995 case Intrinsic::x86_avx_min_pd_256:
11996 Opcode = X86ISD::FMIN;
11999 return DAG.getNode(Opcode, dl, Op.getValueType(),
12000 Op.getOperand(1), Op.getOperand(2));
12003 // AVX2 variable shift intrinsics
12004 case Intrinsic::x86_avx2_psllv_d:
12005 case Intrinsic::x86_avx2_psllv_q:
12006 case Intrinsic::x86_avx2_psllv_d_256:
12007 case Intrinsic::x86_avx2_psllv_q_256:
12008 case Intrinsic::x86_avx2_psrlv_d:
12009 case Intrinsic::x86_avx2_psrlv_q:
12010 case Intrinsic::x86_avx2_psrlv_d_256:
12011 case Intrinsic::x86_avx2_psrlv_q_256:
12012 case Intrinsic::x86_avx2_psrav_d:
12013 case Intrinsic::x86_avx2_psrav_d_256: {
12016 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12017 case Intrinsic::x86_avx2_psllv_d:
12018 case Intrinsic::x86_avx2_psllv_q:
12019 case Intrinsic::x86_avx2_psllv_d_256:
12020 case Intrinsic::x86_avx2_psllv_q_256:
12023 case Intrinsic::x86_avx2_psrlv_d:
12024 case Intrinsic::x86_avx2_psrlv_q:
12025 case Intrinsic::x86_avx2_psrlv_d_256:
12026 case Intrinsic::x86_avx2_psrlv_q_256:
12029 case Intrinsic::x86_avx2_psrav_d:
12030 case Intrinsic::x86_avx2_psrav_d_256:
12034 return DAG.getNode(Opcode, dl, Op.getValueType(),
12035 Op.getOperand(1), Op.getOperand(2));
12038 case Intrinsic::x86_ssse3_pshuf_b_128:
12039 case Intrinsic::x86_avx2_pshuf_b:
12040 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
12041 Op.getOperand(1), Op.getOperand(2));
12043 case Intrinsic::x86_ssse3_psign_b_128:
12044 case Intrinsic::x86_ssse3_psign_w_128:
12045 case Intrinsic::x86_ssse3_psign_d_128:
12046 case Intrinsic::x86_avx2_psign_b:
12047 case Intrinsic::x86_avx2_psign_w:
12048 case Intrinsic::x86_avx2_psign_d:
12049 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
12050 Op.getOperand(1), Op.getOperand(2));
12052 case Intrinsic::x86_sse41_insertps:
12053 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
12054 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
12056 case Intrinsic::x86_avx_vperm2f128_ps_256:
12057 case Intrinsic::x86_avx_vperm2f128_pd_256:
12058 case Intrinsic::x86_avx_vperm2f128_si_256:
12059 case Intrinsic::x86_avx2_vperm2i128:
12060 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
12061 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
12063 case Intrinsic::x86_avx2_permd:
12064 case Intrinsic::x86_avx2_permps:
12065 // Operands intentionally swapped. Mask is last operand to intrinsic,
12066 // but second operand for node/instruction.
12067 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
12068 Op.getOperand(2), Op.getOperand(1));
12070 case Intrinsic::x86_sse_sqrt_ps:
12071 case Intrinsic::x86_sse2_sqrt_pd:
12072 case Intrinsic::x86_avx_sqrt_ps_256:
12073 case Intrinsic::x86_avx_sqrt_pd_256:
12074 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
12076 // ptest and testp intrinsics. The intrinsic these come from are designed to
12077 // return an integer value, not just an instruction so lower it to the ptest
12078 // or testp pattern and a setcc for the result.
12079 case Intrinsic::x86_sse41_ptestz:
12080 case Intrinsic::x86_sse41_ptestc:
12081 case Intrinsic::x86_sse41_ptestnzc:
12082 case Intrinsic::x86_avx_ptestz_256:
12083 case Intrinsic::x86_avx_ptestc_256:
12084 case Intrinsic::x86_avx_ptestnzc_256:
12085 case Intrinsic::x86_avx_vtestz_ps:
12086 case Intrinsic::x86_avx_vtestc_ps:
12087 case Intrinsic::x86_avx_vtestnzc_ps:
12088 case Intrinsic::x86_avx_vtestz_pd:
12089 case Intrinsic::x86_avx_vtestc_pd:
12090 case Intrinsic::x86_avx_vtestnzc_pd:
12091 case Intrinsic::x86_avx_vtestz_ps_256:
12092 case Intrinsic::x86_avx_vtestc_ps_256:
12093 case Intrinsic::x86_avx_vtestnzc_ps_256:
12094 case Intrinsic::x86_avx_vtestz_pd_256:
12095 case Intrinsic::x86_avx_vtestc_pd_256:
12096 case Intrinsic::x86_avx_vtestnzc_pd_256: {
12097 bool IsTestPacked = false;
12100 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
12101 case Intrinsic::x86_avx_vtestz_ps:
12102 case Intrinsic::x86_avx_vtestz_pd:
12103 case Intrinsic::x86_avx_vtestz_ps_256:
12104 case Intrinsic::x86_avx_vtestz_pd_256:
12105 IsTestPacked = true; // Fallthrough
12106 case Intrinsic::x86_sse41_ptestz:
12107 case Intrinsic::x86_avx_ptestz_256:
12109 X86CC = X86::COND_E;
12111 case Intrinsic::x86_avx_vtestc_ps:
12112 case Intrinsic::x86_avx_vtestc_pd:
12113 case Intrinsic::x86_avx_vtestc_ps_256:
12114 case Intrinsic::x86_avx_vtestc_pd_256:
12115 IsTestPacked = true; // Fallthrough
12116 case Intrinsic::x86_sse41_ptestc:
12117 case Intrinsic::x86_avx_ptestc_256:
12119 X86CC = X86::COND_B;
12121 case Intrinsic::x86_avx_vtestnzc_ps:
12122 case Intrinsic::x86_avx_vtestnzc_pd:
12123 case Intrinsic::x86_avx_vtestnzc_ps_256:
12124 case Intrinsic::x86_avx_vtestnzc_pd_256:
12125 IsTestPacked = true; // Fallthrough
12126 case Intrinsic::x86_sse41_ptestnzc:
12127 case Intrinsic::x86_avx_ptestnzc_256:
12129 X86CC = X86::COND_A;
12133 SDValue LHS = Op.getOperand(1);
12134 SDValue RHS = Op.getOperand(2);
12135 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
12136 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
12137 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12138 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
12139 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12141 case Intrinsic::x86_avx512_kortestz_w:
12142 case Intrinsic::x86_avx512_kortestc_w: {
12143 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
12144 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
12145 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
12146 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12147 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
12148 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
12149 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12152 // SSE/AVX shift intrinsics
12153 case Intrinsic::x86_sse2_psll_w:
12154 case Intrinsic::x86_sse2_psll_d:
12155 case Intrinsic::x86_sse2_psll_q:
12156 case Intrinsic::x86_avx2_psll_w:
12157 case Intrinsic::x86_avx2_psll_d:
12158 case Intrinsic::x86_avx2_psll_q:
12159 case Intrinsic::x86_sse2_psrl_w:
12160 case Intrinsic::x86_sse2_psrl_d:
12161 case Intrinsic::x86_sse2_psrl_q:
12162 case Intrinsic::x86_avx2_psrl_w:
12163 case Intrinsic::x86_avx2_psrl_d:
12164 case Intrinsic::x86_avx2_psrl_q:
12165 case Intrinsic::x86_sse2_psra_w:
12166 case Intrinsic::x86_sse2_psra_d:
12167 case Intrinsic::x86_avx2_psra_w:
12168 case Intrinsic::x86_avx2_psra_d: {
12171 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12172 case Intrinsic::x86_sse2_psll_w:
12173 case Intrinsic::x86_sse2_psll_d:
12174 case Intrinsic::x86_sse2_psll_q:
12175 case Intrinsic::x86_avx2_psll_w:
12176 case Intrinsic::x86_avx2_psll_d:
12177 case Intrinsic::x86_avx2_psll_q:
12178 Opcode = X86ISD::VSHL;
12180 case Intrinsic::x86_sse2_psrl_w:
12181 case Intrinsic::x86_sse2_psrl_d:
12182 case Intrinsic::x86_sse2_psrl_q:
12183 case Intrinsic::x86_avx2_psrl_w:
12184 case Intrinsic::x86_avx2_psrl_d:
12185 case Intrinsic::x86_avx2_psrl_q:
12186 Opcode = X86ISD::VSRL;
12188 case Intrinsic::x86_sse2_psra_w:
12189 case Intrinsic::x86_sse2_psra_d:
12190 case Intrinsic::x86_avx2_psra_w:
12191 case Intrinsic::x86_avx2_psra_d:
12192 Opcode = X86ISD::VSRA;
12195 return DAG.getNode(Opcode, dl, Op.getValueType(),
12196 Op.getOperand(1), Op.getOperand(2));
12199 // SSE/AVX immediate shift intrinsics
12200 case Intrinsic::x86_sse2_pslli_w:
12201 case Intrinsic::x86_sse2_pslli_d:
12202 case Intrinsic::x86_sse2_pslli_q:
12203 case Intrinsic::x86_avx2_pslli_w:
12204 case Intrinsic::x86_avx2_pslli_d:
12205 case Intrinsic::x86_avx2_pslli_q:
12206 case Intrinsic::x86_sse2_psrli_w:
12207 case Intrinsic::x86_sse2_psrli_d:
12208 case Intrinsic::x86_sse2_psrli_q:
12209 case Intrinsic::x86_avx2_psrli_w:
12210 case Intrinsic::x86_avx2_psrli_d:
12211 case Intrinsic::x86_avx2_psrli_q:
12212 case Intrinsic::x86_sse2_psrai_w:
12213 case Intrinsic::x86_sse2_psrai_d:
12214 case Intrinsic::x86_avx2_psrai_w:
12215 case Intrinsic::x86_avx2_psrai_d: {
12218 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12219 case Intrinsic::x86_sse2_pslli_w:
12220 case Intrinsic::x86_sse2_pslli_d:
12221 case Intrinsic::x86_sse2_pslli_q:
12222 case Intrinsic::x86_avx2_pslli_w:
12223 case Intrinsic::x86_avx2_pslli_d:
12224 case Intrinsic::x86_avx2_pslli_q:
12225 Opcode = X86ISD::VSHLI;
12227 case Intrinsic::x86_sse2_psrli_w:
12228 case Intrinsic::x86_sse2_psrli_d:
12229 case Intrinsic::x86_sse2_psrli_q:
12230 case Intrinsic::x86_avx2_psrli_w:
12231 case Intrinsic::x86_avx2_psrli_d:
12232 case Intrinsic::x86_avx2_psrli_q:
12233 Opcode = X86ISD::VSRLI;
12235 case Intrinsic::x86_sse2_psrai_w:
12236 case Intrinsic::x86_sse2_psrai_d:
12237 case Intrinsic::x86_avx2_psrai_w:
12238 case Intrinsic::x86_avx2_psrai_d:
12239 Opcode = X86ISD::VSRAI;
12242 return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
12243 Op.getOperand(1), Op.getOperand(2), DAG);
12246 case Intrinsic::x86_sse42_pcmpistria128:
12247 case Intrinsic::x86_sse42_pcmpestria128:
12248 case Intrinsic::x86_sse42_pcmpistric128:
12249 case Intrinsic::x86_sse42_pcmpestric128:
12250 case Intrinsic::x86_sse42_pcmpistrio128:
12251 case Intrinsic::x86_sse42_pcmpestrio128:
12252 case Intrinsic::x86_sse42_pcmpistris128:
12253 case Intrinsic::x86_sse42_pcmpestris128:
12254 case Intrinsic::x86_sse42_pcmpistriz128:
12255 case Intrinsic::x86_sse42_pcmpestriz128: {
12259 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12260 case Intrinsic::x86_sse42_pcmpistria128:
12261 Opcode = X86ISD::PCMPISTRI;
12262 X86CC = X86::COND_A;
12264 case Intrinsic::x86_sse42_pcmpestria128:
12265 Opcode = X86ISD::PCMPESTRI;
12266 X86CC = X86::COND_A;
12268 case Intrinsic::x86_sse42_pcmpistric128:
12269 Opcode = X86ISD::PCMPISTRI;
12270 X86CC = X86::COND_B;
12272 case Intrinsic::x86_sse42_pcmpestric128:
12273 Opcode = X86ISD::PCMPESTRI;
12274 X86CC = X86::COND_B;
12276 case Intrinsic::x86_sse42_pcmpistrio128:
12277 Opcode = X86ISD::PCMPISTRI;
12278 X86CC = X86::COND_O;
12280 case Intrinsic::x86_sse42_pcmpestrio128:
12281 Opcode = X86ISD::PCMPESTRI;
12282 X86CC = X86::COND_O;
12284 case Intrinsic::x86_sse42_pcmpistris128:
12285 Opcode = X86ISD::PCMPISTRI;
12286 X86CC = X86::COND_S;
12288 case Intrinsic::x86_sse42_pcmpestris128:
12289 Opcode = X86ISD::PCMPESTRI;
12290 X86CC = X86::COND_S;
12292 case Intrinsic::x86_sse42_pcmpistriz128:
12293 Opcode = X86ISD::PCMPISTRI;
12294 X86CC = X86::COND_E;
12296 case Intrinsic::x86_sse42_pcmpestriz128:
12297 Opcode = X86ISD::PCMPESTRI;
12298 X86CC = X86::COND_E;
12301 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12302 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12303 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
12304 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12305 DAG.getConstant(X86CC, MVT::i8),
12306 SDValue(PCMP.getNode(), 1));
12307 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12310 case Intrinsic::x86_sse42_pcmpistri128:
12311 case Intrinsic::x86_sse42_pcmpestri128: {
12313 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
12314 Opcode = X86ISD::PCMPISTRI;
12316 Opcode = X86ISD::PCMPESTRI;
12318 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12319 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12320 return DAG.getNode(Opcode, dl, VTs, NewOps);
12322 case Intrinsic::x86_fma_vfmadd_ps:
12323 case Intrinsic::x86_fma_vfmadd_pd:
12324 case Intrinsic::x86_fma_vfmsub_ps:
12325 case Intrinsic::x86_fma_vfmsub_pd:
12326 case Intrinsic::x86_fma_vfnmadd_ps:
12327 case Intrinsic::x86_fma_vfnmadd_pd:
12328 case Intrinsic::x86_fma_vfnmsub_ps:
12329 case Intrinsic::x86_fma_vfnmsub_pd:
12330 case Intrinsic::x86_fma_vfmaddsub_ps:
12331 case Intrinsic::x86_fma_vfmaddsub_pd:
12332 case Intrinsic::x86_fma_vfmsubadd_ps:
12333 case Intrinsic::x86_fma_vfmsubadd_pd:
12334 case Intrinsic::x86_fma_vfmadd_ps_256:
12335 case Intrinsic::x86_fma_vfmadd_pd_256:
12336 case Intrinsic::x86_fma_vfmsub_ps_256:
12337 case Intrinsic::x86_fma_vfmsub_pd_256:
12338 case Intrinsic::x86_fma_vfnmadd_ps_256:
12339 case Intrinsic::x86_fma_vfnmadd_pd_256:
12340 case Intrinsic::x86_fma_vfnmsub_ps_256:
12341 case Intrinsic::x86_fma_vfnmsub_pd_256:
12342 case Intrinsic::x86_fma_vfmaddsub_ps_256:
12343 case Intrinsic::x86_fma_vfmaddsub_pd_256:
12344 case Intrinsic::x86_fma_vfmsubadd_ps_256:
12345 case Intrinsic::x86_fma_vfmsubadd_pd_256:
12346 case Intrinsic::x86_fma_vfmadd_ps_512:
12347 case Intrinsic::x86_fma_vfmadd_pd_512:
12348 case Intrinsic::x86_fma_vfmsub_ps_512:
12349 case Intrinsic::x86_fma_vfmsub_pd_512:
12350 case Intrinsic::x86_fma_vfnmadd_ps_512:
12351 case Intrinsic::x86_fma_vfnmadd_pd_512:
12352 case Intrinsic::x86_fma_vfnmsub_ps_512:
12353 case Intrinsic::x86_fma_vfnmsub_pd_512:
12354 case Intrinsic::x86_fma_vfmaddsub_ps_512:
12355 case Intrinsic::x86_fma_vfmaddsub_pd_512:
12356 case Intrinsic::x86_fma_vfmsubadd_ps_512:
12357 case Intrinsic::x86_fma_vfmsubadd_pd_512: {
12360 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12361 case Intrinsic::x86_fma_vfmadd_ps:
12362 case Intrinsic::x86_fma_vfmadd_pd:
12363 case Intrinsic::x86_fma_vfmadd_ps_256:
12364 case Intrinsic::x86_fma_vfmadd_pd_256:
12365 case Intrinsic::x86_fma_vfmadd_ps_512:
12366 case Intrinsic::x86_fma_vfmadd_pd_512:
12367 Opc = X86ISD::FMADD;
12369 case Intrinsic::x86_fma_vfmsub_ps:
12370 case Intrinsic::x86_fma_vfmsub_pd:
12371 case Intrinsic::x86_fma_vfmsub_ps_256:
12372 case Intrinsic::x86_fma_vfmsub_pd_256:
12373 case Intrinsic::x86_fma_vfmsub_ps_512:
12374 case Intrinsic::x86_fma_vfmsub_pd_512:
12375 Opc = X86ISD::FMSUB;
12377 case Intrinsic::x86_fma_vfnmadd_ps:
12378 case Intrinsic::x86_fma_vfnmadd_pd:
12379 case Intrinsic::x86_fma_vfnmadd_ps_256:
12380 case Intrinsic::x86_fma_vfnmadd_pd_256:
12381 case Intrinsic::x86_fma_vfnmadd_ps_512:
12382 case Intrinsic::x86_fma_vfnmadd_pd_512:
12383 Opc = X86ISD::FNMADD;
12385 case Intrinsic::x86_fma_vfnmsub_ps:
12386 case Intrinsic::x86_fma_vfnmsub_pd:
12387 case Intrinsic::x86_fma_vfnmsub_ps_256:
12388 case Intrinsic::x86_fma_vfnmsub_pd_256:
12389 case Intrinsic::x86_fma_vfnmsub_ps_512:
12390 case Intrinsic::x86_fma_vfnmsub_pd_512:
12391 Opc = X86ISD::FNMSUB;
12393 case Intrinsic::x86_fma_vfmaddsub_ps:
12394 case Intrinsic::x86_fma_vfmaddsub_pd:
12395 case Intrinsic::x86_fma_vfmaddsub_ps_256:
12396 case Intrinsic::x86_fma_vfmaddsub_pd_256:
12397 case Intrinsic::x86_fma_vfmaddsub_ps_512:
12398 case Intrinsic::x86_fma_vfmaddsub_pd_512:
12399 Opc = X86ISD::FMADDSUB;
12401 case Intrinsic::x86_fma_vfmsubadd_ps:
12402 case Intrinsic::x86_fma_vfmsubadd_pd:
12403 case Intrinsic::x86_fma_vfmsubadd_ps_256:
12404 case Intrinsic::x86_fma_vfmsubadd_pd_256:
12405 case Intrinsic::x86_fma_vfmsubadd_ps_512:
12406 case Intrinsic::x86_fma_vfmsubadd_pd_512:
12407 Opc = X86ISD::FMSUBADD;
12411 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
12412 Op.getOperand(2), Op.getOperand(3));
12417 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12418 SDValue Base, SDValue Index,
12419 SDValue ScaleOp, SDValue Chain,
12420 const X86Subtarget * Subtarget) {
12422 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12423 assert(C && "Invalid scale type");
12424 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12425 SDValue Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12426 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12427 Index.getSimpleValueType().getVectorNumElements());
12428 SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12429 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12430 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12431 SDValue Segment = DAG.getRegister(0, MVT::i32);
12432 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12433 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12434 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12435 return DAG.getMergeValues(RetOps, dl);
12438 static SDValue getMGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12439 SDValue Src, SDValue Mask, SDValue Base,
12440 SDValue Index, SDValue ScaleOp, SDValue Chain,
12441 const X86Subtarget * Subtarget) {
12443 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12444 assert(C && "Invalid scale type");
12445 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12446 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12447 Index.getSimpleValueType().getVectorNumElements());
12448 SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12449 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12450 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12451 SDValue Segment = DAG.getRegister(0, MVT::i32);
12452 if (Src.getOpcode() == ISD::UNDEF)
12453 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12454 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12455 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12456 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12457 return DAG.getMergeValues(RetOps, dl);
12460 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12461 SDValue Src, SDValue Base, SDValue Index,
12462 SDValue ScaleOp, SDValue Chain) {
12464 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12465 assert(C && "Invalid scale type");
12466 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12467 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12468 SDValue Segment = DAG.getRegister(0, MVT::i32);
12469 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12470 Index.getSimpleValueType().getVectorNumElements());
12471 SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12472 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12473 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12474 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12475 return SDValue(Res, 1);
12478 static SDValue getMScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12479 SDValue Src, SDValue Mask, SDValue Base,
12480 SDValue Index, SDValue ScaleOp, SDValue Chain) {
12482 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12483 assert(C && "Invalid scale type");
12484 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12485 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12486 SDValue Segment = DAG.getRegister(0, MVT::i32);
12487 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12488 Index.getSimpleValueType().getVectorNumElements());
12489 SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12490 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12491 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12492 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12493 return SDValue(Res, 1);
12496 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
12497 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
12498 // also used to custom lower READCYCLECOUNTER nodes.
12499 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
12500 SelectionDAG &DAG, const X86Subtarget *Subtarget,
12501 SmallVectorImpl<SDValue> &Results) {
12502 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12503 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
12506 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
12507 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
12508 // and the EAX register is loaded with the low-order 32 bits.
12509 if (Subtarget->is64Bit()) {
12510 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
12511 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
12514 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
12515 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
12518 SDValue Chain = HI.getValue(1);
12520 if (Opcode == X86ISD::RDTSCP_DAG) {
12521 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
12523 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
12524 // the ECX register. Add 'ecx' explicitly to the chain.
12525 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
12527 // Explicitly store the content of ECX at the location passed in input
12528 // to the 'rdtscp' intrinsic.
12529 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
12530 MachinePointerInfo(), false, false, 0);
12533 if (Subtarget->is64Bit()) {
12534 // The EDX register is loaded with the high-order 32 bits of the MSR, and
12535 // the EAX register is loaded with the low-order 32 bits.
12536 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
12537 DAG.getConstant(32, MVT::i8));
12538 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
12539 Results.push_back(Chain);
12543 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12544 SDValue Ops[] = { LO, HI };
12545 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
12546 Results.push_back(Pair);
12547 Results.push_back(Chain);
12550 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12551 SelectionDAG &DAG) {
12552 SmallVector<SDValue, 2> Results;
12554 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
12556 return DAG.getMergeValues(Results, DL);
12559 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
12560 SelectionDAG &DAG) {
12562 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12564 default: return SDValue(); // Don't custom lower most intrinsics.
12566 // RDRAND/RDSEED intrinsics.
12567 case Intrinsic::x86_rdrand_16:
12568 case Intrinsic::x86_rdrand_32:
12569 case Intrinsic::x86_rdrand_64:
12570 case Intrinsic::x86_rdseed_16:
12571 case Intrinsic::x86_rdseed_32:
12572 case Intrinsic::x86_rdseed_64: {
12573 unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
12574 IntNo == Intrinsic::x86_rdseed_32 ||
12575 IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
12577 // Emit the node with the right value type.
12578 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
12579 SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
12581 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
12582 // Otherwise return the value from Rand, which is always 0, casted to i32.
12583 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
12584 DAG.getConstant(1, Op->getValueType(1)),
12585 DAG.getConstant(X86::COND_B, MVT::i32),
12586 SDValue(Result.getNode(), 1) };
12587 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
12588 DAG.getVTList(Op->getValueType(1), MVT::Glue),
12591 // Return { result, isValid, chain }.
12592 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
12593 SDValue(Result.getNode(), 2));
12595 //int_gather(index, base, scale);
12596 case Intrinsic::x86_avx512_gather_qpd_512:
12597 case Intrinsic::x86_avx512_gather_qps_512:
12598 case Intrinsic::x86_avx512_gather_dpd_512:
12599 case Intrinsic::x86_avx512_gather_qpi_512:
12600 case Intrinsic::x86_avx512_gather_qpq_512:
12601 case Intrinsic::x86_avx512_gather_dpq_512:
12602 case Intrinsic::x86_avx512_gather_dps_512:
12603 case Intrinsic::x86_avx512_gather_dpi_512: {
12606 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12607 case Intrinsic::x86_avx512_gather_qps_512: Opc = X86::VGATHERQPSZrm; break;
12608 case Intrinsic::x86_avx512_gather_qpd_512: Opc = X86::VGATHERQPDZrm; break;
12609 case Intrinsic::x86_avx512_gather_dpd_512: Opc = X86::VGATHERDPDZrm; break;
12610 case Intrinsic::x86_avx512_gather_dps_512: Opc = X86::VGATHERDPSZrm; break;
12611 case Intrinsic::x86_avx512_gather_qpi_512: Opc = X86::VPGATHERQDZrm; break;
12612 case Intrinsic::x86_avx512_gather_qpq_512: Opc = X86::VPGATHERQQZrm; break;
12613 case Intrinsic::x86_avx512_gather_dpi_512: Opc = X86::VPGATHERDDZrm; break;
12614 case Intrinsic::x86_avx512_gather_dpq_512: Opc = X86::VPGATHERDQZrm; break;
12616 SDValue Chain = Op.getOperand(0);
12617 SDValue Index = Op.getOperand(2);
12618 SDValue Base = Op.getOperand(3);
12619 SDValue Scale = Op.getOperand(4);
12620 return getGatherNode(Opc, Op, DAG, Base, Index, Scale, Chain, Subtarget);
12622 //int_gather_mask(v1, mask, index, base, scale);
12623 case Intrinsic::x86_avx512_gather_qps_mask_512:
12624 case Intrinsic::x86_avx512_gather_qpd_mask_512:
12625 case Intrinsic::x86_avx512_gather_dpd_mask_512:
12626 case Intrinsic::x86_avx512_gather_dps_mask_512:
12627 case Intrinsic::x86_avx512_gather_qpi_mask_512:
12628 case Intrinsic::x86_avx512_gather_qpq_mask_512:
12629 case Intrinsic::x86_avx512_gather_dpi_mask_512:
12630 case Intrinsic::x86_avx512_gather_dpq_mask_512: {
12633 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12634 case Intrinsic::x86_avx512_gather_qps_mask_512:
12635 Opc = X86::VGATHERQPSZrm; break;
12636 case Intrinsic::x86_avx512_gather_qpd_mask_512:
12637 Opc = X86::VGATHERQPDZrm; break;
12638 case Intrinsic::x86_avx512_gather_dpd_mask_512:
12639 Opc = X86::VGATHERDPDZrm; break;
12640 case Intrinsic::x86_avx512_gather_dps_mask_512:
12641 Opc = X86::VGATHERDPSZrm; break;
12642 case Intrinsic::x86_avx512_gather_qpi_mask_512:
12643 Opc = X86::VPGATHERQDZrm; break;
12644 case Intrinsic::x86_avx512_gather_qpq_mask_512:
12645 Opc = X86::VPGATHERQQZrm; break;
12646 case Intrinsic::x86_avx512_gather_dpi_mask_512:
12647 Opc = X86::VPGATHERDDZrm; break;
12648 case Intrinsic::x86_avx512_gather_dpq_mask_512:
12649 Opc = X86::VPGATHERDQZrm; break;
12651 SDValue Chain = Op.getOperand(0);
12652 SDValue Src = Op.getOperand(2);
12653 SDValue Mask = Op.getOperand(3);
12654 SDValue Index = Op.getOperand(4);
12655 SDValue Base = Op.getOperand(5);
12656 SDValue Scale = Op.getOperand(6);
12657 return getMGatherNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
12660 //int_scatter(base, index, v1, scale);
12661 case Intrinsic::x86_avx512_scatter_qpd_512:
12662 case Intrinsic::x86_avx512_scatter_qps_512:
12663 case Intrinsic::x86_avx512_scatter_dpd_512:
12664 case Intrinsic::x86_avx512_scatter_qpi_512:
12665 case Intrinsic::x86_avx512_scatter_qpq_512:
12666 case Intrinsic::x86_avx512_scatter_dpq_512:
12667 case Intrinsic::x86_avx512_scatter_dps_512:
12668 case Intrinsic::x86_avx512_scatter_dpi_512: {
12671 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12672 case Intrinsic::x86_avx512_scatter_qpd_512:
12673 Opc = X86::VSCATTERQPDZmr; break;
12674 case Intrinsic::x86_avx512_scatter_qps_512:
12675 Opc = X86::VSCATTERQPSZmr; break;
12676 case Intrinsic::x86_avx512_scatter_dpd_512:
12677 Opc = X86::VSCATTERDPDZmr; break;
12678 case Intrinsic::x86_avx512_scatter_dps_512:
12679 Opc = X86::VSCATTERDPSZmr; break;
12680 case Intrinsic::x86_avx512_scatter_qpi_512:
12681 Opc = X86::VPSCATTERQDZmr; break;
12682 case Intrinsic::x86_avx512_scatter_qpq_512:
12683 Opc = X86::VPSCATTERQQZmr; break;
12684 case Intrinsic::x86_avx512_scatter_dpq_512:
12685 Opc = X86::VPSCATTERDQZmr; break;
12686 case Intrinsic::x86_avx512_scatter_dpi_512:
12687 Opc = X86::VPSCATTERDDZmr; break;
12689 SDValue Chain = Op.getOperand(0);
12690 SDValue Base = Op.getOperand(2);
12691 SDValue Index = Op.getOperand(3);
12692 SDValue Src = Op.getOperand(4);
12693 SDValue Scale = Op.getOperand(5);
12694 return getScatterNode(Opc, Op, DAG, Src, Base, Index, Scale, Chain);
12696 //int_scatter_mask(base, mask, index, v1, scale);
12697 case Intrinsic::x86_avx512_scatter_qps_mask_512:
12698 case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12699 case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12700 case Intrinsic::x86_avx512_scatter_dps_mask_512:
12701 case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12702 case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12703 case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12704 case Intrinsic::x86_avx512_scatter_dpq_mask_512: {
12707 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12708 case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12709 Opc = X86::VSCATTERQPDZmr; break;
12710 case Intrinsic::x86_avx512_scatter_qps_mask_512:
12711 Opc = X86::VSCATTERQPSZmr; break;
12712 case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12713 Opc = X86::VSCATTERDPDZmr; break;
12714 case Intrinsic::x86_avx512_scatter_dps_mask_512:
12715 Opc = X86::VSCATTERDPSZmr; break;
12716 case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12717 Opc = X86::VPSCATTERQDZmr; break;
12718 case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12719 Opc = X86::VPSCATTERQQZmr; break;
12720 case Intrinsic::x86_avx512_scatter_dpq_mask_512:
12721 Opc = X86::VPSCATTERDQZmr; break;
12722 case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12723 Opc = X86::VPSCATTERDDZmr; break;
12725 SDValue Chain = Op.getOperand(0);
12726 SDValue Base = Op.getOperand(2);
12727 SDValue Mask = Op.getOperand(3);
12728 SDValue Index = Op.getOperand(4);
12729 SDValue Src = Op.getOperand(5);
12730 SDValue Scale = Op.getOperand(6);
12731 return getMScatterNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
12733 // Read Time Stamp Counter (RDTSC).
12734 case Intrinsic::x86_rdtsc:
12735 // Read Time Stamp Counter and Processor ID (RDTSCP).
12736 case Intrinsic::x86_rdtscp: {
12739 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12740 case Intrinsic::x86_rdtsc:
12741 Opc = X86ISD::RDTSC_DAG; break;
12742 case Intrinsic::x86_rdtscp:
12743 Opc = X86ISD::RDTSCP_DAG; break;
12745 SmallVector<SDValue, 2> Results;
12746 getReadTimeStampCounter(Op.getNode(), dl, Opc, DAG, Subtarget, Results);
12747 return DAG.getMergeValues(Results, dl);
12749 // XTEST intrinsics.
12750 case Intrinsic::x86_xtest: {
12751 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
12752 SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
12753 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12754 DAG.getConstant(X86::COND_NE, MVT::i8),
12756 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
12757 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
12758 Ret, SDValue(InTrans.getNode(), 1));
12763 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
12764 SelectionDAG &DAG) const {
12765 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12766 MFI->setReturnAddressIsTaken(true);
12768 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
12771 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12773 EVT PtrVT = getPointerTy();
12776 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12777 const X86RegisterInfo *RegInfo =
12778 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12779 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
12780 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12781 DAG.getNode(ISD::ADD, dl, PtrVT,
12782 FrameAddr, Offset),
12783 MachinePointerInfo(), false, false, false, 0);
12786 // Just load the return address.
12787 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
12788 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12789 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
12792 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
12793 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12794 MFI->setFrameAddressIsTaken(true);
12796 EVT VT = Op.getValueType();
12797 SDLoc dl(Op); // FIXME probably not meaningful
12798 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12799 const X86RegisterInfo *RegInfo =
12800 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12801 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12802 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
12803 (FrameReg == X86::EBP && VT == MVT::i32)) &&
12804 "Invalid Frame Register!");
12805 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
12807 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
12808 MachinePointerInfo(),
12809 false, false, false, 0);
12813 // FIXME? Maybe this could be a TableGen attribute on some registers and
12814 // this table could be generated automatically from RegInfo.
12815 unsigned X86TargetLowering::getRegisterByName(const char* RegName) const {
12816 unsigned Reg = StringSwitch<unsigned>(RegName)
12817 .Case("esp", X86::ESP)
12818 .Case("rsp", X86::RSP)
12822 report_fatal_error("Invalid register name global variable");
12825 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
12826 SelectionDAG &DAG) const {
12827 const X86RegisterInfo *RegInfo =
12828 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12829 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
12832 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
12833 SDValue Chain = Op.getOperand(0);
12834 SDValue Offset = Op.getOperand(1);
12835 SDValue Handler = Op.getOperand(2);
12838 EVT PtrVT = getPointerTy();
12839 const X86RegisterInfo *RegInfo =
12840 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12841 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12842 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
12843 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
12844 "Invalid Frame Register!");
12845 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
12846 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
12848 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
12849 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
12850 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
12851 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
12853 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
12855 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
12856 DAG.getRegister(StoreAddrReg, PtrVT));
12859 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
12860 SelectionDAG &DAG) const {
12862 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
12863 DAG.getVTList(MVT::i32, MVT::Other),
12864 Op.getOperand(0), Op.getOperand(1));
12867 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
12868 SelectionDAG &DAG) const {
12870 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
12871 Op.getOperand(0), Op.getOperand(1));
12874 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
12875 return Op.getOperand(0);
12878 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
12879 SelectionDAG &DAG) const {
12880 SDValue Root = Op.getOperand(0);
12881 SDValue Trmp = Op.getOperand(1); // trampoline
12882 SDValue FPtr = Op.getOperand(2); // nested function
12883 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
12886 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
12887 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12889 if (Subtarget->is64Bit()) {
12890 SDValue OutChains[6];
12892 // Large code-model.
12893 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
12894 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
12896 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
12897 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
12899 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
12901 // Load the pointer to the nested function into R11.
12902 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
12903 SDValue Addr = Trmp;
12904 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12905 Addr, MachinePointerInfo(TrmpAddr),
12908 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12909 DAG.getConstant(2, MVT::i64));
12910 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
12911 MachinePointerInfo(TrmpAddr, 2),
12914 // Load the 'nest' parameter value into R10.
12915 // R10 is specified in X86CallingConv.td
12916 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
12917 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12918 DAG.getConstant(10, MVT::i64));
12919 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12920 Addr, MachinePointerInfo(TrmpAddr, 10),
12923 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12924 DAG.getConstant(12, MVT::i64));
12925 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
12926 MachinePointerInfo(TrmpAddr, 12),
12929 // Jump to the nested function.
12930 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
12931 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12932 DAG.getConstant(20, MVT::i64));
12933 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12934 Addr, MachinePointerInfo(TrmpAddr, 20),
12937 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
12938 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12939 DAG.getConstant(22, MVT::i64));
12940 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
12941 MachinePointerInfo(TrmpAddr, 22),
12944 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
12946 const Function *Func =
12947 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
12948 CallingConv::ID CC = Func->getCallingConv();
12953 llvm_unreachable("Unsupported calling convention");
12954 case CallingConv::C:
12955 case CallingConv::X86_StdCall: {
12956 // Pass 'nest' parameter in ECX.
12957 // Must be kept in sync with X86CallingConv.td
12958 NestReg = X86::ECX;
12960 // Check that ECX wasn't needed by an 'inreg' parameter.
12961 FunctionType *FTy = Func->getFunctionType();
12962 const AttributeSet &Attrs = Func->getAttributes();
12964 if (!Attrs.isEmpty() && !Func->isVarArg()) {
12965 unsigned InRegCount = 0;
12968 for (FunctionType::param_iterator I = FTy->param_begin(),
12969 E = FTy->param_end(); I != E; ++I, ++Idx)
12970 if (Attrs.hasAttribute(Idx, Attribute::InReg))
12971 // FIXME: should only count parameters that are lowered to integers.
12972 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
12974 if (InRegCount > 2) {
12975 report_fatal_error("Nest register in use - reduce number of inreg"
12981 case CallingConv::X86_FastCall:
12982 case CallingConv::X86_ThisCall:
12983 case CallingConv::Fast:
12984 // Pass 'nest' parameter in EAX.
12985 // Must be kept in sync with X86CallingConv.td
12986 NestReg = X86::EAX;
12990 SDValue OutChains[4];
12991 SDValue Addr, Disp;
12993 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12994 DAG.getConstant(10, MVT::i32));
12995 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
12997 // This is storing the opcode for MOV32ri.
12998 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
12999 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
13000 OutChains[0] = DAG.getStore(Root, dl,
13001 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
13002 Trmp, MachinePointerInfo(TrmpAddr),
13005 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13006 DAG.getConstant(1, MVT::i32));
13007 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
13008 MachinePointerInfo(TrmpAddr, 1),
13011 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
13012 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13013 DAG.getConstant(5, MVT::i32));
13014 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
13015 MachinePointerInfo(TrmpAddr, 5),
13018 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13019 DAG.getConstant(6, MVT::i32));
13020 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
13021 MachinePointerInfo(TrmpAddr, 6),
13024 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
13028 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
13029 SelectionDAG &DAG) const {
13031 The rounding mode is in bits 11:10 of FPSR, and has the following
13033 00 Round to nearest
13038 FLT_ROUNDS, on the other hand, expects the following:
13045 To perform the conversion, we do:
13046 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
13049 MachineFunction &MF = DAG.getMachineFunction();
13050 const TargetMachine &TM = MF.getTarget();
13051 const TargetFrameLowering &TFI = *TM.getFrameLowering();
13052 unsigned StackAlignment = TFI.getStackAlignment();
13053 MVT VT = Op.getSimpleValueType();
13056 // Save FP Control Word to stack slot
13057 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
13058 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
13060 MachineMemOperand *MMO =
13061 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
13062 MachineMemOperand::MOStore, 2, 2);
13064 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
13065 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
13066 DAG.getVTList(MVT::Other),
13067 Ops, MVT::i16, MMO);
13069 // Load FP Control Word from stack slot
13070 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
13071 MachinePointerInfo(), false, false, false, 0);
13073 // Transform as necessary
13075 DAG.getNode(ISD::SRL, DL, MVT::i16,
13076 DAG.getNode(ISD::AND, DL, MVT::i16,
13077 CWD, DAG.getConstant(0x800, MVT::i16)),
13078 DAG.getConstant(11, MVT::i8));
13080 DAG.getNode(ISD::SRL, DL, MVT::i16,
13081 DAG.getNode(ISD::AND, DL, MVT::i16,
13082 CWD, DAG.getConstant(0x400, MVT::i16)),
13083 DAG.getConstant(9, MVT::i8));
13086 DAG.getNode(ISD::AND, DL, MVT::i16,
13087 DAG.getNode(ISD::ADD, DL, MVT::i16,
13088 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
13089 DAG.getConstant(1, MVT::i16)),
13090 DAG.getConstant(3, MVT::i16));
13092 return DAG.getNode((VT.getSizeInBits() < 16 ?
13093 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
13096 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
13097 MVT VT = Op.getSimpleValueType();
13099 unsigned NumBits = VT.getSizeInBits();
13102 Op = Op.getOperand(0);
13103 if (VT == MVT::i8) {
13104 // Zero extend to i32 since there is not an i8 bsr.
13106 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13109 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
13110 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13111 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13113 // If src is zero (i.e. bsr sets ZF), returns NumBits.
13116 DAG.getConstant(NumBits+NumBits-1, OpVT),
13117 DAG.getConstant(X86::COND_E, MVT::i8),
13120 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
13122 // Finally xor with NumBits-1.
13123 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13126 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13130 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
13131 MVT VT = Op.getSimpleValueType();
13133 unsigned NumBits = VT.getSizeInBits();
13136 Op = Op.getOperand(0);
13137 if (VT == MVT::i8) {
13138 // Zero extend to i32 since there is not an i8 bsr.
13140 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13143 // Issue a bsr (scan bits in reverse).
13144 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13145 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13147 // And xor with NumBits-1.
13148 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13151 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13155 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
13156 MVT VT = Op.getSimpleValueType();
13157 unsigned NumBits = VT.getSizeInBits();
13159 Op = Op.getOperand(0);
13161 // Issue a bsf (scan bits forward) which also sets EFLAGS.
13162 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13163 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
13165 // If src is zero (i.e. bsf sets ZF), returns NumBits.
13168 DAG.getConstant(NumBits, VT),
13169 DAG.getConstant(X86::COND_E, MVT::i8),
13172 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
13175 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
13176 // ones, and then concatenate the result back.
13177 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
13178 MVT VT = Op.getSimpleValueType();
13180 assert(VT.is256BitVector() && VT.isInteger() &&
13181 "Unsupported value type for operation");
13183 unsigned NumElems = VT.getVectorNumElements();
13186 // Extract the LHS vectors
13187 SDValue LHS = Op.getOperand(0);
13188 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13189 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13191 // Extract the RHS vectors
13192 SDValue RHS = Op.getOperand(1);
13193 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13194 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13196 MVT EltVT = VT.getVectorElementType();
13197 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13199 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13200 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
13201 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
13204 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
13205 assert(Op.getSimpleValueType().is256BitVector() &&
13206 Op.getSimpleValueType().isInteger() &&
13207 "Only handle AVX 256-bit vector integer operation");
13208 return Lower256IntArith(Op, DAG);
13211 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
13212 assert(Op.getSimpleValueType().is256BitVector() &&
13213 Op.getSimpleValueType().isInteger() &&
13214 "Only handle AVX 256-bit vector integer operation");
13215 return Lower256IntArith(Op, DAG);
13218 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
13219 SelectionDAG &DAG) {
13221 MVT VT = Op.getSimpleValueType();
13223 // Decompose 256-bit ops into smaller 128-bit ops.
13224 if (VT.is256BitVector() && !Subtarget->hasInt256())
13225 return Lower256IntArith(Op, DAG);
13227 SDValue A = Op.getOperand(0);
13228 SDValue B = Op.getOperand(1);
13230 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
13231 if (VT == MVT::v4i32) {
13232 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
13233 "Should not custom lower when pmuldq is available!");
13235 // Extract the odd parts.
13236 static const int UnpackMask[] = { 1, -1, 3, -1 };
13237 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
13238 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
13240 // Multiply the even parts.
13241 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
13242 // Now multiply odd parts.
13243 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
13245 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
13246 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
13248 // Merge the two vectors back together with a shuffle. This expands into 2
13250 static const int ShufMask[] = { 0, 4, 2, 6 };
13251 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
13254 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
13255 "Only know how to lower V2I64/V4I64/V8I64 multiply");
13257 // Ahi = psrlqi(a, 32);
13258 // Bhi = psrlqi(b, 32);
13260 // AloBlo = pmuludq(a, b);
13261 // AloBhi = pmuludq(a, Bhi);
13262 // AhiBlo = pmuludq(Ahi, b);
13264 // AloBhi = psllqi(AloBhi, 32);
13265 // AhiBlo = psllqi(AhiBlo, 32);
13266 // return AloBlo + AloBhi + AhiBlo;
13268 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
13269 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
13271 // Bit cast to 32-bit vectors for MULUDQ
13272 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
13273 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
13274 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
13275 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
13276 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
13277 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
13279 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
13280 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
13281 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
13283 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
13284 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
13286 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
13287 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
13290 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
13291 assert(Subtarget->isTargetWin64() && "Unexpected target");
13292 EVT VT = Op.getValueType();
13293 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
13294 "Unexpected return type for lowering");
13298 switch (Op->getOpcode()) {
13299 default: llvm_unreachable("Unexpected request for libcall!");
13300 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
13301 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
13302 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
13303 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
13304 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
13305 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
13309 SDValue InChain = DAG.getEntryNode();
13311 TargetLowering::ArgListTy Args;
13312 TargetLowering::ArgListEntry Entry;
13313 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
13314 EVT ArgVT = Op->getOperand(i).getValueType();
13315 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
13316 "Unexpected argument type for lowering");
13317 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
13318 Entry.Node = StackPtr;
13319 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
13321 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13322 Entry.Ty = PointerType::get(ArgTy,0);
13323 Entry.isSExt = false;
13324 Entry.isZExt = false;
13325 Args.push_back(Entry);
13328 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
13331 TargetLowering::CallLoweringInfo CLI(
13332 InChain, static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
13333 isSigned, !isSigned, false, true, 0, getLibcallCallingConv(LC),
13334 /*isTailCall=*/false,
13335 /*doesNotReturn=*/false, /*isReturnValueUsed=*/true, Callee, Args, DAG,
13337 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
13339 return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
13342 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
13343 SelectionDAG &DAG) {
13344 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
13345 EVT VT = Op0.getValueType();
13348 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
13349 (VT == MVT::v8i32 && Subtarget->hasInt256()));
13351 // Get the high parts.
13352 const int Mask[] = {1, 2, 3, 4, 5, 6, 7, 8};
13353 SDValue Hi0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
13354 SDValue Hi1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
13356 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
13358 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
13359 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
13361 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
13362 SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
13363 DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
13364 SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
13365 DAG.getNode(Opcode, dl, MulVT, Hi0, Hi1));
13367 // Shuffle it back into the right order.
13368 const int HighMask[] = {1, 5, 3, 7, 9, 13, 11, 15};
13369 SDValue Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
13370 const int LowMask[] = {0, 4, 2, 6, 8, 12, 10, 14};
13371 SDValue Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
13373 // If we have a signed multiply but no PMULDQ fix up the high parts of a
13374 // unsigned multiply.
13375 if (IsSigned && !Subtarget->hasSSE41()) {
13377 DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
13378 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
13379 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
13380 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
13381 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
13383 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
13384 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
13387 return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Highs, Lows);
13390 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
13391 const X86Subtarget *Subtarget) {
13392 MVT VT = Op.getSimpleValueType();
13394 SDValue R = Op.getOperand(0);
13395 SDValue Amt = Op.getOperand(1);
13397 // Optimize shl/srl/sra with constant shift amount.
13398 if (isSplatVector(Amt.getNode())) {
13399 SDValue SclrAmt = Amt->getOperand(0);
13400 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
13401 uint64_t ShiftAmt = C->getZExtValue();
13403 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
13404 (Subtarget->hasInt256() &&
13405 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13406 (Subtarget->hasAVX512() &&
13407 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13408 if (Op.getOpcode() == ISD::SHL)
13409 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13411 if (Op.getOpcode() == ISD::SRL)
13412 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13414 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
13415 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13419 if (VT == MVT::v16i8) {
13420 if (Op.getOpcode() == ISD::SHL) {
13421 // Make a large shift.
13422 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13423 MVT::v8i16, R, ShiftAmt,
13425 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13426 // Zero out the rightmost bits.
13427 SmallVector<SDValue, 16> V(16,
13428 DAG.getConstant(uint8_t(-1U << ShiftAmt),
13430 return DAG.getNode(ISD::AND, dl, VT, SHL,
13431 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13433 if (Op.getOpcode() == ISD::SRL) {
13434 // Make a large shift.
13435 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13436 MVT::v8i16, R, ShiftAmt,
13438 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13439 // Zero out the leftmost bits.
13440 SmallVector<SDValue, 16> V(16,
13441 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13443 return DAG.getNode(ISD::AND, dl, VT, SRL,
13444 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13446 if (Op.getOpcode() == ISD::SRA) {
13447 if (ShiftAmt == 7) {
13448 // R s>> 7 === R s< 0
13449 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13450 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13453 // R s>> a === ((R u>> a) ^ m) - m
13454 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13455 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
13457 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13458 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13459 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13462 llvm_unreachable("Unknown shift opcode.");
13465 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
13466 if (Op.getOpcode() == ISD::SHL) {
13467 // Make a large shift.
13468 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13469 MVT::v16i16, R, ShiftAmt,
13471 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13472 // Zero out the rightmost bits.
13473 SmallVector<SDValue, 32> V(32,
13474 DAG.getConstant(uint8_t(-1U << ShiftAmt),
13476 return DAG.getNode(ISD::AND, dl, VT, SHL,
13477 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13479 if (Op.getOpcode() == ISD::SRL) {
13480 // Make a large shift.
13481 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13482 MVT::v16i16, R, ShiftAmt,
13484 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13485 // Zero out the leftmost bits.
13486 SmallVector<SDValue, 32> V(32,
13487 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13489 return DAG.getNode(ISD::AND, dl, VT, SRL,
13490 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13492 if (Op.getOpcode() == ISD::SRA) {
13493 if (ShiftAmt == 7) {
13494 // R s>> 7 === R s< 0
13495 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13496 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13499 // R s>> a === ((R u>> a) ^ m) - m
13500 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13501 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
13503 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13504 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13505 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13508 llvm_unreachable("Unknown shift opcode.");
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 Amt.getOpcode() == ISD::BITCAST &&
13517 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13518 Amt = Amt.getOperand(0);
13519 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13520 VT.getVectorNumElements();
13521 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
13522 uint64_t ShiftAmt = 0;
13523 for (unsigned i = 0; i != Ratio; ++i) {
13524 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
13528 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
13530 // Check remaining shift amounts.
13531 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13532 uint64_t ShAmt = 0;
13533 for (unsigned j = 0; j != Ratio; ++j) {
13534 ConstantSDNode *C =
13535 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
13539 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
13541 if (ShAmt != ShiftAmt)
13544 switch (Op.getOpcode()) {
13546 llvm_unreachable("Unknown shift opcode!");
13548 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13551 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13554 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13562 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
13563 const X86Subtarget* Subtarget) {
13564 MVT VT = Op.getSimpleValueType();
13566 SDValue R = Op.getOperand(0);
13567 SDValue Amt = Op.getOperand(1);
13569 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
13570 VT == MVT::v4i32 || VT == MVT::v8i16 ||
13571 (Subtarget->hasInt256() &&
13572 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
13573 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13574 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13576 EVT EltVT = VT.getVectorElementType();
13578 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13579 unsigned NumElts = VT.getVectorNumElements();
13581 for (i = 0; i != NumElts; ++i) {
13582 if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
13586 for (j = i; j != NumElts; ++j) {
13587 SDValue Arg = Amt.getOperand(j);
13588 if (Arg.getOpcode() == ISD::UNDEF) continue;
13589 if (Arg != Amt.getOperand(i))
13592 if (i != NumElts && j == NumElts)
13593 BaseShAmt = Amt.getOperand(i);
13595 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13596 Amt = Amt.getOperand(0);
13597 if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
13598 cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
13599 SDValue InVec = Amt.getOperand(0);
13600 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13601 unsigned NumElts = InVec.getValueType().getVectorNumElements();
13603 for (; i != NumElts; ++i) {
13604 SDValue Arg = InVec.getOperand(i);
13605 if (Arg.getOpcode() == ISD::UNDEF) continue;
13609 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13610 if (ConstantSDNode *C =
13611 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13612 unsigned SplatIdx =
13613 cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
13614 if (C->getZExtValue() == SplatIdx)
13615 BaseShAmt = InVec.getOperand(1);
13618 if (!BaseShAmt.getNode())
13619 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
13620 DAG.getIntPtrConstant(0));
13624 if (BaseShAmt.getNode()) {
13625 if (EltVT.bitsGT(MVT::i32))
13626 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
13627 else if (EltVT.bitsLT(MVT::i32))
13628 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
13630 switch (Op.getOpcode()) {
13632 llvm_unreachable("Unknown shift opcode!");
13634 switch (VT.SimpleTy) {
13635 default: return SDValue();
13644 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
13647 switch (VT.SimpleTy) {
13648 default: return SDValue();
13655 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
13658 switch (VT.SimpleTy) {
13659 default: return SDValue();
13668 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
13674 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13675 if (!Subtarget->is64Bit() &&
13676 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
13677 (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
13678 Amt.getOpcode() == ISD::BITCAST &&
13679 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13680 Amt = Amt.getOperand(0);
13681 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13682 VT.getVectorNumElements();
13683 std::vector<SDValue> Vals(Ratio);
13684 for (unsigned i = 0; i != Ratio; ++i)
13685 Vals[i] = Amt.getOperand(i);
13686 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13687 for (unsigned j = 0; j != Ratio; ++j)
13688 if (Vals[j] != Amt.getOperand(i + j))
13691 switch (Op.getOpcode()) {
13693 llvm_unreachable("Unknown shift opcode!");
13695 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
13697 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
13699 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
13706 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
13707 SelectionDAG &DAG) {
13709 MVT VT = Op.getSimpleValueType();
13711 SDValue R = Op.getOperand(0);
13712 SDValue Amt = Op.getOperand(1);
13715 if (!Subtarget->hasSSE2())
13718 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
13722 V = LowerScalarVariableShift(Op, DAG, Subtarget);
13726 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
13728 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
13729 if (Subtarget->hasInt256()) {
13730 if (Op.getOpcode() == ISD::SRL &&
13731 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13732 VT == MVT::v4i64 || VT == MVT::v8i32))
13734 if (Op.getOpcode() == ISD::SHL &&
13735 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13736 VT == MVT::v4i64 || VT == MVT::v8i32))
13738 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
13742 // If possible, lower this packed shift into a vector multiply instead of
13743 // expanding it into a sequence of scalar shifts.
13744 // Do this only if the vector shift count is a constant build_vector.
13745 if (Op.getOpcode() == ISD::SHL &&
13746 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
13747 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
13748 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13749 SmallVector<SDValue, 8> Elts;
13750 EVT SVT = VT.getScalarType();
13751 unsigned SVTBits = SVT.getSizeInBits();
13752 const APInt &One = APInt(SVTBits, 1);
13753 unsigned NumElems = VT.getVectorNumElements();
13755 for (unsigned i=0; i !=NumElems; ++i) {
13756 SDValue Op = Amt->getOperand(i);
13757 if (Op->getOpcode() == ISD::UNDEF) {
13758 Elts.push_back(Op);
13762 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
13763 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
13764 uint64_t ShAmt = C.getZExtValue();
13765 if (ShAmt >= SVTBits) {
13766 Elts.push_back(DAG.getUNDEF(SVT));
13769 Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
13771 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
13772 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
13775 // Lower SHL with variable shift amount.
13776 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
13777 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
13779 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
13780 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
13781 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
13782 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
13785 // If possible, lower this shift as a sequence of two shifts by
13786 // constant plus a MOVSS/MOVSD instead of scalarizing it.
13788 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
13790 // Could be rewritten as:
13791 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
13793 // The advantage is that the two shifts from the example would be
13794 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
13795 // the vector shift into four scalar shifts plus four pairs of vector
13797 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
13798 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13799 unsigned TargetOpcode = X86ISD::MOVSS;
13800 bool CanBeSimplified;
13801 // The splat value for the first packed shift (the 'X' from the example).
13802 SDValue Amt1 = Amt->getOperand(0);
13803 // The splat value for the second packed shift (the 'Y' from the example).
13804 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
13805 Amt->getOperand(2);
13807 // See if it is possible to replace this node with a sequence of
13808 // two shifts followed by a MOVSS/MOVSD
13809 if (VT == MVT::v4i32) {
13810 // Check if it is legal to use a MOVSS.
13811 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
13812 Amt2 == Amt->getOperand(3);
13813 if (!CanBeSimplified) {
13814 // Otherwise, check if we can still simplify this node using a MOVSD.
13815 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
13816 Amt->getOperand(2) == Amt->getOperand(3);
13817 TargetOpcode = X86ISD::MOVSD;
13818 Amt2 = Amt->getOperand(2);
13821 // Do similar checks for the case where the machine value type
13823 CanBeSimplified = Amt1 == Amt->getOperand(1);
13824 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
13825 CanBeSimplified = Amt2 == Amt->getOperand(i);
13827 if (!CanBeSimplified) {
13828 TargetOpcode = X86ISD::MOVSD;
13829 CanBeSimplified = true;
13830 Amt2 = Amt->getOperand(4);
13831 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
13832 CanBeSimplified = Amt1 == Amt->getOperand(i);
13833 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
13834 CanBeSimplified = Amt2 == Amt->getOperand(j);
13838 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
13839 isa<ConstantSDNode>(Amt2)) {
13840 // Replace this node with two shifts followed by a MOVSS/MOVSD.
13841 EVT CastVT = MVT::v4i32;
13843 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
13844 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
13846 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
13847 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
13848 if (TargetOpcode == X86ISD::MOVSD)
13849 CastVT = MVT::v2i64;
13850 SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
13851 SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
13852 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
13854 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13858 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
13859 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
13862 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
13863 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
13865 // Turn 'a' into a mask suitable for VSELECT
13866 SDValue VSelM = DAG.getConstant(0x80, VT);
13867 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13868 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13870 SDValue CM1 = DAG.getConstant(0x0f, VT);
13871 SDValue CM2 = DAG.getConstant(0x3f, VT);
13873 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
13874 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
13875 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
13876 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13877 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13880 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13881 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13882 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13884 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
13885 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
13886 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
13887 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13888 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13891 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13892 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13893 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13895 // return VSELECT(r, r+r, a);
13896 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
13897 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
13901 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
13902 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
13903 // solution better.
13904 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
13905 MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
13907 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
13908 R = DAG.getNode(ExtOpc, dl, NewVT, R);
13909 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
13910 return DAG.getNode(ISD::TRUNCATE, dl, VT,
13911 DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
13914 // Decompose 256-bit shifts into smaller 128-bit shifts.
13915 if (VT.is256BitVector()) {
13916 unsigned NumElems = VT.getVectorNumElements();
13917 MVT EltVT = VT.getVectorElementType();
13918 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13920 // Extract the two vectors
13921 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
13922 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
13924 // Recreate the shift amount vectors
13925 SDValue Amt1, Amt2;
13926 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13927 // Constant shift amount
13928 SmallVector<SDValue, 4> Amt1Csts;
13929 SmallVector<SDValue, 4> Amt2Csts;
13930 for (unsigned i = 0; i != NumElems/2; ++i)
13931 Amt1Csts.push_back(Amt->getOperand(i));
13932 for (unsigned i = NumElems/2; i != NumElems; ++i)
13933 Amt2Csts.push_back(Amt->getOperand(i));
13935 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
13936 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
13938 // Variable shift amount
13939 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
13940 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
13943 // Issue new vector shifts for the smaller types
13944 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
13945 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
13947 // Concatenate the result back
13948 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
13954 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
13955 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
13956 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
13957 // looks for this combo and may remove the "setcc" instruction if the "setcc"
13958 // has only one use.
13959 SDNode *N = Op.getNode();
13960 SDValue LHS = N->getOperand(0);
13961 SDValue RHS = N->getOperand(1);
13962 unsigned BaseOp = 0;
13965 switch (Op.getOpcode()) {
13966 default: llvm_unreachable("Unknown ovf instruction!");
13968 // A subtract of one will be selected as a INC. Note that INC doesn't
13969 // set CF, so we can't do this for UADDO.
13970 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13972 BaseOp = X86ISD::INC;
13973 Cond = X86::COND_O;
13976 BaseOp = X86ISD::ADD;
13977 Cond = X86::COND_O;
13980 BaseOp = X86ISD::ADD;
13981 Cond = X86::COND_B;
13984 // A subtract of one will be selected as a DEC. Note that DEC doesn't
13985 // set CF, so we can't do this for USUBO.
13986 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13988 BaseOp = X86ISD::DEC;
13989 Cond = X86::COND_O;
13992 BaseOp = X86ISD::SUB;
13993 Cond = X86::COND_O;
13996 BaseOp = X86ISD::SUB;
13997 Cond = X86::COND_B;
14000 BaseOp = X86ISD::SMUL;
14001 Cond = X86::COND_O;
14003 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
14004 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
14006 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
14009 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14010 DAG.getConstant(X86::COND_O, MVT::i32),
14011 SDValue(Sum.getNode(), 2));
14013 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
14017 // Also sets EFLAGS.
14018 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
14019 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
14022 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
14023 DAG.getConstant(Cond, MVT::i32),
14024 SDValue(Sum.getNode(), 1));
14026 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
14029 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
14030 SelectionDAG &DAG) const {
14032 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
14033 MVT VT = Op.getSimpleValueType();
14035 if (!Subtarget->hasSSE2() || !VT.isVector())
14038 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
14039 ExtraVT.getScalarType().getSizeInBits();
14041 switch (VT.SimpleTy) {
14042 default: return SDValue();
14045 if (!Subtarget->hasFp256())
14047 if (!Subtarget->hasInt256()) {
14048 // needs to be split
14049 unsigned NumElems = VT.getVectorNumElements();
14051 // Extract the LHS vectors
14052 SDValue LHS = Op.getOperand(0);
14053 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14054 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14056 MVT EltVT = VT.getVectorElementType();
14057 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14059 EVT ExtraEltVT = ExtraVT.getVectorElementType();
14060 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
14061 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
14063 SDValue Extra = DAG.getValueType(ExtraVT);
14065 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
14066 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
14068 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
14073 SDValue Op0 = Op.getOperand(0);
14074 SDValue Op00 = Op0.getOperand(0);
14076 // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
14077 if (Op0.getOpcode() == ISD::BITCAST &&
14078 Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
14079 // (sext (vzext x)) -> (vsext x)
14080 Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
14081 if (Tmp1.getNode()) {
14082 EVT ExtraEltVT = ExtraVT.getVectorElementType();
14083 // This folding is only valid when the in-reg type is a vector of i8,
14085 if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
14086 ExtraEltVT == MVT::i32) {
14087 SDValue Tmp1Op0 = Tmp1.getOperand(0);
14088 assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
14089 "This optimization is invalid without a VZEXT.");
14090 return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
14096 // If the above didn't work, then just use Shift-Left + Shift-Right.
14097 Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
14099 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
14105 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
14106 SelectionDAG &DAG) {
14108 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
14109 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
14110 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
14111 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
14113 // The only fence that needs an instruction is a sequentially-consistent
14114 // cross-thread fence.
14115 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
14116 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
14117 // no-sse2). There isn't any reason to disable it if the target processor
14119 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
14120 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
14122 SDValue Chain = Op.getOperand(0);
14123 SDValue Zero = DAG.getConstant(0, MVT::i32);
14125 DAG.getRegister(X86::ESP, MVT::i32), // Base
14126 DAG.getTargetConstant(1, MVT::i8), // Scale
14127 DAG.getRegister(0, MVT::i32), // Index
14128 DAG.getTargetConstant(0, MVT::i32), // Disp
14129 DAG.getRegister(0, MVT::i32), // Segment.
14133 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
14134 return SDValue(Res, 0);
14137 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
14138 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
14141 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
14142 SelectionDAG &DAG) {
14143 MVT T = Op.getSimpleValueType();
14147 switch(T.SimpleTy) {
14148 default: llvm_unreachable("Invalid value type!");
14149 case MVT::i8: Reg = X86::AL; size = 1; break;
14150 case MVT::i16: Reg = X86::AX; size = 2; break;
14151 case MVT::i32: Reg = X86::EAX; size = 4; break;
14153 assert(Subtarget->is64Bit() && "Node not type legal!");
14154 Reg = X86::RAX; size = 8;
14157 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
14158 Op.getOperand(2), SDValue());
14159 SDValue Ops[] = { cpIn.getValue(0),
14162 DAG.getTargetConstant(size, MVT::i8),
14163 cpIn.getValue(1) };
14164 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14165 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
14166 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
14169 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
14173 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
14174 SelectionDAG &DAG) {
14175 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
14176 MVT DstVT = Op.getSimpleValueType();
14178 if (SrcVT == MVT::v2i32) {
14179 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14180 if (DstVT != MVT::f64)
14181 // This conversion needs to be expanded.
14185 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
14186 Op->getOperand(0), DAG.getIntPtrConstant(0));
14187 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
14188 Op->getOperand(0), DAG.getIntPtrConstant(1));
14189 SDValue Elts[] = {Elt0, Elt1, Elt0, Elt0};
14190 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Elts);
14191 SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
14192 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
14193 DAG.getIntPtrConstant(0));
14196 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
14197 Subtarget->hasMMX() && "Unexpected custom BITCAST");
14198 assert((DstVT == MVT::i64 ||
14199 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
14200 "Unexpected custom BITCAST");
14201 // i64 <=> MMX conversions are Legal.
14202 if (SrcVT==MVT::i64 && DstVT.isVector())
14204 if (DstVT==MVT::i64 && SrcVT.isVector())
14206 // MMX <=> MMX conversions are Legal.
14207 if (SrcVT.isVector() && DstVT.isVector())
14209 // All other conversions need to be expanded.
14213 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
14214 SDNode *Node = Op.getNode();
14216 EVT T = Node->getValueType(0);
14217 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
14218 DAG.getConstant(0, T), Node->getOperand(2));
14219 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
14220 cast<AtomicSDNode>(Node)->getMemoryVT(),
14221 Node->getOperand(0),
14222 Node->getOperand(1), negOp,
14223 cast<AtomicSDNode>(Node)->getMemOperand(),
14224 cast<AtomicSDNode>(Node)->getOrdering(),
14225 cast<AtomicSDNode>(Node)->getSynchScope());
14228 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
14229 SDNode *Node = Op.getNode();
14231 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14233 // Convert seq_cst store -> xchg
14234 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
14235 // FIXME: On 32-bit, store -> fist or movq would be more efficient
14236 // (The only way to get a 16-byte store is cmpxchg16b)
14237 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
14238 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
14239 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14240 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
14241 cast<AtomicSDNode>(Node)->getMemoryVT(),
14242 Node->getOperand(0),
14243 Node->getOperand(1), Node->getOperand(2),
14244 cast<AtomicSDNode>(Node)->getMemOperand(),
14245 cast<AtomicSDNode>(Node)->getOrdering(),
14246 cast<AtomicSDNode>(Node)->getSynchScope());
14247 return Swap.getValue(1);
14249 // Other atomic stores have a simple pattern.
14253 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
14254 EVT VT = Op.getNode()->getSimpleValueType(0);
14256 // Let legalize expand this if it isn't a legal type yet.
14257 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14260 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14263 bool ExtraOp = false;
14264 switch (Op.getOpcode()) {
14265 default: llvm_unreachable("Invalid code");
14266 case ISD::ADDC: Opc = X86ISD::ADD; break;
14267 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
14268 case ISD::SUBC: Opc = X86ISD::SUB; break;
14269 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
14273 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14275 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14276 Op.getOperand(1), Op.getOperand(2));
14279 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
14280 SelectionDAG &DAG) {
14281 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
14283 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
14284 // which returns the values as { float, float } (in XMM0) or
14285 // { double, double } (which is returned in XMM0, XMM1).
14287 SDValue Arg = Op.getOperand(0);
14288 EVT ArgVT = Arg.getValueType();
14289 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14291 TargetLowering::ArgListTy Args;
14292 TargetLowering::ArgListEntry Entry;
14296 Entry.isSExt = false;
14297 Entry.isZExt = false;
14298 Args.push_back(Entry);
14300 bool isF64 = ArgVT == MVT::f64;
14301 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
14302 // the small struct {f32, f32} is returned in (eax, edx). For f64,
14303 // the results are returned via SRet in memory.
14304 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
14305 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14306 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
14308 Type *RetTy = isF64
14309 ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
14310 : (Type*)VectorType::get(ArgTy, 4);
14312 CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
14313 false, false, false, false, 0,
14314 CallingConv::C, /*isTaillCall=*/false,
14315 /*doesNotRet=*/false, /*isReturnValueUsed*/true,
14316 Callee, Args, DAG, dl);
14317 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
14320 // Returned in xmm0 and xmm1.
14321 return CallResult.first;
14323 // Returned in bits 0:31 and 32:64 xmm0.
14324 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14325 CallResult.first, DAG.getIntPtrConstant(0));
14326 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14327 CallResult.first, DAG.getIntPtrConstant(1));
14328 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
14329 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
14332 /// LowerOperation - Provide custom lowering hooks for some operations.
14334 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
14335 switch (Op.getOpcode()) {
14336 default: llvm_unreachable("Should not custom lower this!");
14337 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
14338 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
14339 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op, Subtarget, DAG);
14340 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
14341 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
14342 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
14343 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
14344 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
14345 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
14346 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
14347 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
14348 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
14349 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
14350 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
14351 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
14352 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
14353 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
14354 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
14355 case ISD::SHL_PARTS:
14356 case ISD::SRA_PARTS:
14357 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
14358 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
14359 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
14360 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
14361 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
14362 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
14363 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
14364 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
14365 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
14366 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
14367 case ISD::FABS: return LowerFABS(Op, DAG);
14368 case ISD::FNEG: return LowerFNEG(Op, DAG);
14369 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
14370 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
14371 case ISD::SETCC: return LowerSETCC(Op, DAG);
14372 case ISD::SELECT: return LowerSELECT(Op, DAG);
14373 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
14374 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
14375 case ISD::VASTART: return LowerVASTART(Op, DAG);
14376 case ISD::VAARG: return LowerVAARG(Op, DAG);
14377 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
14378 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
14379 case ISD::INTRINSIC_VOID:
14380 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
14381 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
14382 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
14383 case ISD::FRAME_TO_ARGS_OFFSET:
14384 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
14385 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
14386 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
14387 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
14388 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
14389 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
14390 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
14391 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
14392 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
14393 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
14394 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
14395 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
14396 case ISD::UMUL_LOHI:
14397 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
14400 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
14406 case ISD::UMULO: return LowerXALUO(Op, DAG);
14407 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
14408 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
14412 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
14413 case ISD::ADD: return LowerADD(Op, DAG);
14414 case ISD::SUB: return LowerSUB(Op, DAG);
14415 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
14419 static void ReplaceATOMIC_LOAD(SDNode *Node,
14420 SmallVectorImpl<SDValue> &Results,
14421 SelectionDAG &DAG) {
14423 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14425 // Convert wide load -> cmpxchg8b/cmpxchg16b
14426 // FIXME: On 32-bit, load -> fild or movq would be more efficient
14427 // (The only way to get a 16-byte load is cmpxchg16b)
14428 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
14429 SDValue Zero = DAG.getConstant(0, VT);
14430 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
14431 Node->getOperand(0),
14432 Node->getOperand(1), Zero, Zero,
14433 cast<AtomicSDNode>(Node)->getMemOperand(),
14434 cast<AtomicSDNode>(Node)->getOrdering(),
14435 cast<AtomicSDNode>(Node)->getOrdering(),
14436 cast<AtomicSDNode>(Node)->getSynchScope());
14437 Results.push_back(Swap.getValue(0));
14438 Results.push_back(Swap.getValue(1));
14442 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
14443 SelectionDAG &DAG, unsigned NewOp) {
14445 assert (Node->getValueType(0) == MVT::i64 &&
14446 "Only know how to expand i64 atomics");
14448 SDValue Chain = Node->getOperand(0);
14449 SDValue In1 = Node->getOperand(1);
14450 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14451 Node->getOperand(2), DAG.getIntPtrConstant(0));
14452 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14453 Node->getOperand(2), DAG.getIntPtrConstant(1));
14454 SDValue Ops[] = { Chain, In1, In2L, In2H };
14455 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
14457 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, MVT::i64,
14458 cast<MemSDNode>(Node)->getMemOperand());
14459 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
14460 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF));
14461 Results.push_back(Result.getValue(2));
14464 /// ReplaceNodeResults - Replace a node with an illegal result type
14465 /// with a new node built out of custom code.
14466 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
14467 SmallVectorImpl<SDValue>&Results,
14468 SelectionDAG &DAG) const {
14470 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14471 switch (N->getOpcode()) {
14473 llvm_unreachable("Do not know how to custom type legalize this operation!");
14474 case ISD::SIGN_EXTEND_INREG:
14479 // We don't want to expand or promote these.
14486 case ISD::UDIVREM: {
14487 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
14488 Results.push_back(V);
14491 case ISD::FP_TO_SINT:
14492 case ISD::FP_TO_UINT: {
14493 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
14495 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
14498 std::pair<SDValue,SDValue> Vals =
14499 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
14500 SDValue FIST = Vals.first, StackSlot = Vals.second;
14501 if (FIST.getNode()) {
14502 EVT VT = N->getValueType(0);
14503 // Return a load from the stack slot.
14504 if (StackSlot.getNode())
14505 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
14506 MachinePointerInfo(),
14507 false, false, false, 0));
14509 Results.push_back(FIST);
14513 case ISD::UINT_TO_FP: {
14514 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14515 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
14516 N->getValueType(0) != MVT::v2f32)
14518 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
14520 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
14522 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
14523 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
14524 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
14525 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
14526 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
14527 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
14530 case ISD::FP_ROUND: {
14531 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
14533 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
14534 Results.push_back(V);
14537 case ISD::INTRINSIC_W_CHAIN: {
14538 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
14540 default : llvm_unreachable("Do not know how to custom type "
14541 "legalize this intrinsic operation!");
14542 case Intrinsic::x86_rdtsc:
14543 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14545 case Intrinsic::x86_rdtscp:
14546 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
14550 case ISD::READCYCLECOUNTER: {
14551 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14554 case ISD::ATOMIC_CMP_SWAP: {
14555 EVT T = N->getValueType(0);
14556 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
14557 bool Regs64bit = T == MVT::i128;
14558 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
14559 SDValue cpInL, cpInH;
14560 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14561 DAG.getConstant(0, HalfT));
14562 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14563 DAG.getConstant(1, HalfT));
14564 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
14565 Regs64bit ? X86::RAX : X86::EAX,
14567 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
14568 Regs64bit ? X86::RDX : X86::EDX,
14569 cpInH, cpInL.getValue(1));
14570 SDValue swapInL, swapInH;
14571 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14572 DAG.getConstant(0, HalfT));
14573 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14574 DAG.getConstant(1, HalfT));
14575 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
14576 Regs64bit ? X86::RBX : X86::EBX,
14577 swapInL, cpInH.getValue(1));
14578 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
14579 Regs64bit ? X86::RCX : X86::ECX,
14580 swapInH, swapInL.getValue(1));
14581 SDValue Ops[] = { swapInH.getValue(0),
14583 swapInH.getValue(1) };
14584 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14585 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
14586 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
14587 X86ISD::LCMPXCHG8_DAG;
14588 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
14589 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
14590 Regs64bit ? X86::RAX : X86::EAX,
14591 HalfT, Result.getValue(1));
14592 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
14593 Regs64bit ? X86::RDX : X86::EDX,
14594 HalfT, cpOutL.getValue(2));
14595 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
14596 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
14597 Results.push_back(cpOutH.getValue(1));
14600 case ISD::ATOMIC_LOAD_ADD:
14601 case ISD::ATOMIC_LOAD_AND:
14602 case ISD::ATOMIC_LOAD_NAND:
14603 case ISD::ATOMIC_LOAD_OR:
14604 case ISD::ATOMIC_LOAD_SUB:
14605 case ISD::ATOMIC_LOAD_XOR:
14606 case ISD::ATOMIC_LOAD_MAX:
14607 case ISD::ATOMIC_LOAD_MIN:
14608 case ISD::ATOMIC_LOAD_UMAX:
14609 case ISD::ATOMIC_LOAD_UMIN:
14610 case ISD::ATOMIC_SWAP: {
14612 switch (N->getOpcode()) {
14613 default: llvm_unreachable("Unexpected opcode");
14614 case ISD::ATOMIC_LOAD_ADD:
14615 Opc = X86ISD::ATOMADD64_DAG;
14617 case ISD::ATOMIC_LOAD_AND:
14618 Opc = X86ISD::ATOMAND64_DAG;
14620 case ISD::ATOMIC_LOAD_NAND:
14621 Opc = X86ISD::ATOMNAND64_DAG;
14623 case ISD::ATOMIC_LOAD_OR:
14624 Opc = X86ISD::ATOMOR64_DAG;
14626 case ISD::ATOMIC_LOAD_SUB:
14627 Opc = X86ISD::ATOMSUB64_DAG;
14629 case ISD::ATOMIC_LOAD_XOR:
14630 Opc = X86ISD::ATOMXOR64_DAG;
14632 case ISD::ATOMIC_LOAD_MAX:
14633 Opc = X86ISD::ATOMMAX64_DAG;
14635 case ISD::ATOMIC_LOAD_MIN:
14636 Opc = X86ISD::ATOMMIN64_DAG;
14638 case ISD::ATOMIC_LOAD_UMAX:
14639 Opc = X86ISD::ATOMUMAX64_DAG;
14641 case ISD::ATOMIC_LOAD_UMIN:
14642 Opc = X86ISD::ATOMUMIN64_DAG;
14644 case ISD::ATOMIC_SWAP:
14645 Opc = X86ISD::ATOMSWAP64_DAG;
14648 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
14651 case ISD::ATOMIC_LOAD: {
14652 ReplaceATOMIC_LOAD(N, Results, DAG);
14655 case ISD::BITCAST: {
14656 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14657 EVT DstVT = N->getValueType(0);
14658 EVT SrcVT = N->getOperand(0)->getValueType(0);
14660 if (SrcVT == MVT::f64 && DstVT == MVT::v2i32) {
14661 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
14662 MVT::v2f64, N->getOperand(0));
14663 SDValue ToV4I32 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Expanded);
14664 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
14665 ToV4I32, DAG.getIntPtrConstant(0));
14666 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
14667 ToV4I32, DAG.getIntPtrConstant(1));
14668 SDValue Elts[] = {Elt0, Elt1};
14669 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Elts));
14675 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
14677 default: return nullptr;
14678 case X86ISD::BSF: return "X86ISD::BSF";
14679 case X86ISD::BSR: return "X86ISD::BSR";
14680 case X86ISD::SHLD: return "X86ISD::SHLD";
14681 case X86ISD::SHRD: return "X86ISD::SHRD";
14682 case X86ISD::FAND: return "X86ISD::FAND";
14683 case X86ISD::FANDN: return "X86ISD::FANDN";
14684 case X86ISD::FOR: return "X86ISD::FOR";
14685 case X86ISD::FXOR: return "X86ISD::FXOR";
14686 case X86ISD::FSRL: return "X86ISD::FSRL";
14687 case X86ISD::FILD: return "X86ISD::FILD";
14688 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
14689 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
14690 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
14691 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
14692 case X86ISD::FLD: return "X86ISD::FLD";
14693 case X86ISD::FST: return "X86ISD::FST";
14694 case X86ISD::CALL: return "X86ISD::CALL";
14695 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
14696 case X86ISD::BT: return "X86ISD::BT";
14697 case X86ISD::CMP: return "X86ISD::CMP";
14698 case X86ISD::COMI: return "X86ISD::COMI";
14699 case X86ISD::UCOMI: return "X86ISD::UCOMI";
14700 case X86ISD::CMPM: return "X86ISD::CMPM";
14701 case X86ISD::CMPMU: return "X86ISD::CMPMU";
14702 case X86ISD::SETCC: return "X86ISD::SETCC";
14703 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
14704 case X86ISD::FSETCC: return "X86ISD::FSETCC";
14705 case X86ISD::CMOV: return "X86ISD::CMOV";
14706 case X86ISD::BRCOND: return "X86ISD::BRCOND";
14707 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
14708 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
14709 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
14710 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
14711 case X86ISD::Wrapper: return "X86ISD::Wrapper";
14712 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
14713 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
14714 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
14715 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
14716 case X86ISD::PINSRB: return "X86ISD::PINSRB";
14717 case X86ISD::PINSRW: return "X86ISD::PINSRW";
14718 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
14719 case X86ISD::ANDNP: return "X86ISD::ANDNP";
14720 case X86ISD::PSIGN: return "X86ISD::PSIGN";
14721 case X86ISD::BLENDV: return "X86ISD::BLENDV";
14722 case X86ISD::BLENDI: return "X86ISD::BLENDI";
14723 case X86ISD::SUBUS: return "X86ISD::SUBUS";
14724 case X86ISD::HADD: return "X86ISD::HADD";
14725 case X86ISD::HSUB: return "X86ISD::HSUB";
14726 case X86ISD::FHADD: return "X86ISD::FHADD";
14727 case X86ISD::FHSUB: return "X86ISD::FHSUB";
14728 case X86ISD::UMAX: return "X86ISD::UMAX";
14729 case X86ISD::UMIN: return "X86ISD::UMIN";
14730 case X86ISD::SMAX: return "X86ISD::SMAX";
14731 case X86ISD::SMIN: return "X86ISD::SMIN";
14732 case X86ISD::FMAX: return "X86ISD::FMAX";
14733 case X86ISD::FMIN: return "X86ISD::FMIN";
14734 case X86ISD::FMAXC: return "X86ISD::FMAXC";
14735 case X86ISD::FMINC: return "X86ISD::FMINC";
14736 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
14737 case X86ISD::FRCP: return "X86ISD::FRCP";
14738 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
14739 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
14740 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
14741 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
14742 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
14743 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
14744 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
14745 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
14746 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
14747 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
14748 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
14749 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
14750 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
14751 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
14752 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
14753 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
14754 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
14755 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
14756 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
14757 case X86ISD::VZEXT: return "X86ISD::VZEXT";
14758 case X86ISD::VSEXT: return "X86ISD::VSEXT";
14759 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
14760 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
14761 case X86ISD::VINSERT: return "X86ISD::VINSERT";
14762 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
14763 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
14764 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
14765 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
14766 case X86ISD::VSHL: return "X86ISD::VSHL";
14767 case X86ISD::VSRL: return "X86ISD::VSRL";
14768 case X86ISD::VSRA: return "X86ISD::VSRA";
14769 case X86ISD::VSHLI: return "X86ISD::VSHLI";
14770 case X86ISD::VSRLI: return "X86ISD::VSRLI";
14771 case X86ISD::VSRAI: return "X86ISD::VSRAI";
14772 case X86ISD::CMPP: return "X86ISD::CMPP";
14773 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
14774 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
14775 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
14776 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
14777 case X86ISD::ADD: return "X86ISD::ADD";
14778 case X86ISD::SUB: return "X86ISD::SUB";
14779 case X86ISD::ADC: return "X86ISD::ADC";
14780 case X86ISD::SBB: return "X86ISD::SBB";
14781 case X86ISD::SMUL: return "X86ISD::SMUL";
14782 case X86ISD::UMUL: return "X86ISD::UMUL";
14783 case X86ISD::INC: return "X86ISD::INC";
14784 case X86ISD::DEC: return "X86ISD::DEC";
14785 case X86ISD::OR: return "X86ISD::OR";
14786 case X86ISD::XOR: return "X86ISD::XOR";
14787 case X86ISD::AND: return "X86ISD::AND";
14788 case X86ISD::BEXTR: return "X86ISD::BEXTR";
14789 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
14790 case X86ISD::PTEST: return "X86ISD::PTEST";
14791 case X86ISD::TESTP: return "X86ISD::TESTP";
14792 case X86ISD::TESTM: return "X86ISD::TESTM";
14793 case X86ISD::TESTNM: return "X86ISD::TESTNM";
14794 case X86ISD::KORTEST: return "X86ISD::KORTEST";
14795 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
14796 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
14797 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
14798 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
14799 case X86ISD::SHUFP: return "X86ISD::SHUFP";
14800 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
14801 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
14802 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
14803 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
14804 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
14805 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
14806 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
14807 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
14808 case X86ISD::MOVSD: return "X86ISD::MOVSD";
14809 case X86ISD::MOVSS: return "X86ISD::MOVSS";
14810 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
14811 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
14812 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
14813 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
14814 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
14815 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
14816 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
14817 case X86ISD::VPERMV: return "X86ISD::VPERMV";
14818 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
14819 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
14820 case X86ISD::VPERMI: return "X86ISD::VPERMI";
14821 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
14822 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
14823 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
14824 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
14825 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
14826 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
14827 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
14828 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
14829 case X86ISD::SAHF: return "X86ISD::SAHF";
14830 case X86ISD::RDRAND: return "X86ISD::RDRAND";
14831 case X86ISD::RDSEED: return "X86ISD::RDSEED";
14832 case X86ISD::FMADD: return "X86ISD::FMADD";
14833 case X86ISD::FMSUB: return "X86ISD::FMSUB";
14834 case X86ISD::FNMADD: return "X86ISD::FNMADD";
14835 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
14836 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
14837 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
14838 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
14839 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
14840 case X86ISD::XTEST: return "X86ISD::XTEST";
14844 // isLegalAddressingMode - Return true if the addressing mode represented
14845 // by AM is legal for this target, for a load/store of the specified type.
14846 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
14848 // X86 supports extremely general addressing modes.
14849 CodeModel::Model M = getTargetMachine().getCodeModel();
14850 Reloc::Model R = getTargetMachine().getRelocationModel();
14852 // X86 allows a sign-extended 32-bit immediate field as a displacement.
14853 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
14858 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
14860 // If a reference to this global requires an extra load, we can't fold it.
14861 if (isGlobalStubReference(GVFlags))
14864 // If BaseGV requires a register for the PIC base, we cannot also have a
14865 // BaseReg specified.
14866 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
14869 // If lower 4G is not available, then we must use rip-relative addressing.
14870 if ((M != CodeModel::Small || R != Reloc::Static) &&
14871 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
14875 switch (AM.Scale) {
14881 // These scales always work.
14886 // These scales are formed with basereg+scalereg. Only accept if there is
14891 default: // Other stuff never works.
14898 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
14899 unsigned Bits = Ty->getScalarSizeInBits();
14901 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
14902 // particularly cheaper than those without.
14906 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
14907 // variable shifts just as cheap as scalar ones.
14908 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
14911 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
14912 // fully general vector.
14916 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
14917 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14919 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
14920 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
14921 return NumBits1 > NumBits2;
14924 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
14925 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14928 if (!isTypeLegal(EVT::getEVT(Ty1)))
14931 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
14933 // Assuming the caller doesn't have a zeroext or signext return parameter,
14934 // truncation all the way down to i1 is valid.
14938 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
14939 return isInt<32>(Imm);
14942 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
14943 // Can also use sub to handle negated immediates.
14944 return isInt<32>(Imm);
14947 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
14948 if (!VT1.isInteger() || !VT2.isInteger())
14950 unsigned NumBits1 = VT1.getSizeInBits();
14951 unsigned NumBits2 = VT2.getSizeInBits();
14952 return NumBits1 > NumBits2;
14955 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
14956 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14957 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
14960 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
14961 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14962 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
14965 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14966 EVT VT1 = Val.getValueType();
14967 if (isZExtFree(VT1, VT2))
14970 if (Val.getOpcode() != ISD::LOAD)
14973 if (!VT1.isSimple() || !VT1.isInteger() ||
14974 !VT2.isSimple() || !VT2.isInteger())
14977 switch (VT1.getSimpleVT().SimpleTy) {
14982 // X86 has 8, 16, and 32-bit zero-extending loads.
14990 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
14991 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
14994 VT = VT.getScalarType();
14996 if (!VT.isSimple())
14999 switch (VT.getSimpleVT().SimpleTy) {
15010 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
15011 // i16 instructions are longer (0x66 prefix) and potentially slower.
15012 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
15015 /// isShuffleMaskLegal - Targets can use this to indicate that they only
15016 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
15017 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
15018 /// are assumed to be legal.
15020 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
15022 if (!VT.isSimple())
15025 MVT SVT = VT.getSimpleVT();
15027 // Very little shuffling can be done for 64-bit vectors right now.
15028 if (VT.getSizeInBits() == 64)
15031 // FIXME: pshufb, blends, shifts.
15032 return (SVT.getVectorNumElements() == 2 ||
15033 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
15034 isMOVLMask(M, SVT) ||
15035 isSHUFPMask(M, SVT) ||
15036 isPSHUFDMask(M, SVT) ||
15037 isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
15038 isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
15039 isPALIGNRMask(M, SVT, Subtarget) ||
15040 isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
15041 isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
15042 isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
15043 isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()));
15047 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
15049 if (!VT.isSimple())
15052 MVT SVT = VT.getSimpleVT();
15053 unsigned NumElts = SVT.getVectorNumElements();
15054 // FIXME: This collection of masks seems suspect.
15057 if (NumElts == 4 && SVT.is128BitVector()) {
15058 return (isMOVLMask(Mask, SVT) ||
15059 isCommutedMOVLMask(Mask, SVT, true) ||
15060 isSHUFPMask(Mask, SVT) ||
15061 isSHUFPMask(Mask, SVT, /* Commuted */ true));
15066 //===----------------------------------------------------------------------===//
15067 // X86 Scheduler Hooks
15068 //===----------------------------------------------------------------------===//
15070 /// Utility function to emit xbegin specifying the start of an RTM region.
15071 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
15072 const TargetInstrInfo *TII) {
15073 DebugLoc DL = MI->getDebugLoc();
15075 const BasicBlock *BB = MBB->getBasicBlock();
15076 MachineFunction::iterator I = MBB;
15079 // For the v = xbegin(), we generate
15090 MachineBasicBlock *thisMBB = MBB;
15091 MachineFunction *MF = MBB->getParent();
15092 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15093 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15094 MF->insert(I, mainMBB);
15095 MF->insert(I, sinkMBB);
15097 // Transfer the remainder of BB and its successor edges to sinkMBB.
15098 sinkMBB->splice(sinkMBB->begin(), MBB,
15099 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15100 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15104 // # fallthrough to mainMBB
15105 // # abortion to sinkMBB
15106 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
15107 thisMBB->addSuccessor(mainMBB);
15108 thisMBB->addSuccessor(sinkMBB);
15112 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
15113 mainMBB->addSuccessor(sinkMBB);
15116 // EAX is live into the sinkMBB
15117 sinkMBB->addLiveIn(X86::EAX);
15118 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15119 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15122 MI->eraseFromParent();
15126 // Get CMPXCHG opcode for the specified data type.
15127 static unsigned getCmpXChgOpcode(EVT VT) {
15128 switch (VT.getSimpleVT().SimpleTy) {
15129 case MVT::i8: return X86::LCMPXCHG8;
15130 case MVT::i16: return X86::LCMPXCHG16;
15131 case MVT::i32: return X86::LCMPXCHG32;
15132 case MVT::i64: return X86::LCMPXCHG64;
15136 llvm_unreachable("Invalid operand size!");
15139 // Get LOAD opcode for the specified data type.
15140 static unsigned getLoadOpcode(EVT VT) {
15141 switch (VT.getSimpleVT().SimpleTy) {
15142 case MVT::i8: return X86::MOV8rm;
15143 case MVT::i16: return X86::MOV16rm;
15144 case MVT::i32: return X86::MOV32rm;
15145 case MVT::i64: return X86::MOV64rm;
15149 llvm_unreachable("Invalid operand size!");
15152 // Get opcode of the non-atomic one from the specified atomic instruction.
15153 static unsigned getNonAtomicOpcode(unsigned Opc) {
15155 case X86::ATOMAND8: return X86::AND8rr;
15156 case X86::ATOMAND16: return X86::AND16rr;
15157 case X86::ATOMAND32: return X86::AND32rr;
15158 case X86::ATOMAND64: return X86::AND64rr;
15159 case X86::ATOMOR8: return X86::OR8rr;
15160 case X86::ATOMOR16: return X86::OR16rr;
15161 case X86::ATOMOR32: return X86::OR32rr;
15162 case X86::ATOMOR64: return X86::OR64rr;
15163 case X86::ATOMXOR8: return X86::XOR8rr;
15164 case X86::ATOMXOR16: return X86::XOR16rr;
15165 case X86::ATOMXOR32: return X86::XOR32rr;
15166 case X86::ATOMXOR64: return X86::XOR64rr;
15168 llvm_unreachable("Unhandled atomic-load-op opcode!");
15171 // Get opcode of the non-atomic one from the specified atomic instruction with
15173 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
15174 unsigned &ExtraOpc) {
15176 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr;
15177 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr;
15178 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr;
15179 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr;
15180 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr;
15181 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
15182 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
15183 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
15184 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr;
15185 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
15186 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
15187 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
15188 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr;
15189 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
15190 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
15191 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
15192 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr;
15193 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
15194 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
15195 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
15197 llvm_unreachable("Unhandled atomic-load-op opcode!");
15200 // Get opcode of the non-atomic one from the specified atomic instruction for
15201 // 64-bit data type on 32-bit target.
15202 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
15204 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr;
15205 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr;
15206 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr;
15207 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr;
15208 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr;
15209 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
15210 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr;
15211 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr;
15212 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr;
15213 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr;
15215 llvm_unreachable("Unhandled atomic-load-op opcode!");
15218 // Get opcode of the non-atomic one from the specified atomic instruction for
15219 // 64-bit data type on 32-bit target with extra opcode.
15220 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
15222 unsigned &ExtraOpc) {
15224 case X86::ATOMNAND6432:
15225 ExtraOpc = X86::NOT32r;
15226 HiOpc = X86::AND32rr;
15227 return X86::AND32rr;
15229 llvm_unreachable("Unhandled atomic-load-op opcode!");
15232 // Get pseudo CMOV opcode from the specified data type.
15233 static unsigned getPseudoCMOVOpc(EVT VT) {
15234 switch (VT.getSimpleVT().SimpleTy) {
15235 case MVT::i8: return X86::CMOV_GR8;
15236 case MVT::i16: return X86::CMOV_GR16;
15237 case MVT::i32: return X86::CMOV_GR32;
15241 llvm_unreachable("Unknown CMOV opcode!");
15244 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
15245 // They will be translated into a spin-loop or compare-exchange loop from
15248 // dst = atomic-fetch-op MI.addr, MI.val
15254 // t1 = LOAD MI.addr
15256 // t4 = phi(t1, t3 / loop)
15257 // t2 = OP MI.val, t4
15259 // LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
15265 MachineBasicBlock *
15266 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
15267 MachineBasicBlock *MBB) const {
15268 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15269 DebugLoc DL = MI->getDebugLoc();
15271 MachineFunction *MF = MBB->getParent();
15272 MachineRegisterInfo &MRI = MF->getRegInfo();
15274 const BasicBlock *BB = MBB->getBasicBlock();
15275 MachineFunction::iterator I = MBB;
15278 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
15279 "Unexpected number of operands");
15281 assert(MI->hasOneMemOperand() &&
15282 "Expected atomic-load-op to have one memoperand");
15284 // Memory Reference
15285 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15286 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15288 unsigned DstReg, SrcReg;
15289 unsigned MemOpndSlot;
15291 unsigned CurOp = 0;
15293 DstReg = MI->getOperand(CurOp++).getReg();
15294 MemOpndSlot = CurOp;
15295 CurOp += X86::AddrNumOperands;
15296 SrcReg = MI->getOperand(CurOp++).getReg();
15298 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15299 MVT::SimpleValueType VT = *RC->vt_begin();
15300 unsigned t1 = MRI.createVirtualRegister(RC);
15301 unsigned t2 = MRI.createVirtualRegister(RC);
15302 unsigned t3 = MRI.createVirtualRegister(RC);
15303 unsigned t4 = MRI.createVirtualRegister(RC);
15304 unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
15306 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
15307 unsigned LOADOpc = getLoadOpcode(VT);
15309 // For the atomic load-arith operator, we generate
15312 // t1 = LOAD [MI.addr]
15314 // t4 = phi(t1 / thisMBB, t3 / mainMBB)
15315 // t1 = OP MI.val, EAX
15317 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
15323 MachineBasicBlock *thisMBB = MBB;
15324 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15325 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15326 MF->insert(I, mainMBB);
15327 MF->insert(I, sinkMBB);
15329 MachineInstrBuilder MIB;
15331 // Transfer the remainder of BB and its successor edges to sinkMBB.
15332 sinkMBB->splice(sinkMBB->begin(), MBB,
15333 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15334 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15337 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
15338 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15339 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15341 NewMO.setIsKill(false);
15342 MIB.addOperand(NewMO);
15344 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15345 unsigned flags = (*MMOI)->getFlags();
15346 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15347 MachineMemOperand *MMO =
15348 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15349 (*MMOI)->getSize(),
15350 (*MMOI)->getBaseAlignment(),
15351 (*MMOI)->getTBAAInfo(),
15352 (*MMOI)->getRanges());
15353 MIB.addMemOperand(MMO);
15356 thisMBB->addSuccessor(mainMBB);
15359 MachineBasicBlock *origMainMBB = mainMBB;
15362 MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
15363 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15365 unsigned Opc = MI->getOpcode();
15368 llvm_unreachable("Unhandled atomic-load-op opcode!");
15369 case X86::ATOMAND8:
15370 case X86::ATOMAND16:
15371 case X86::ATOMAND32:
15372 case X86::ATOMAND64:
15374 case X86::ATOMOR16:
15375 case X86::ATOMOR32:
15376 case X86::ATOMOR64:
15377 case X86::ATOMXOR8:
15378 case X86::ATOMXOR16:
15379 case X86::ATOMXOR32:
15380 case X86::ATOMXOR64: {
15381 unsigned ARITHOpc = getNonAtomicOpcode(Opc);
15382 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
15386 case X86::ATOMNAND8:
15387 case X86::ATOMNAND16:
15388 case X86::ATOMNAND32:
15389 case X86::ATOMNAND64: {
15390 unsigned Tmp = MRI.createVirtualRegister(RC);
15392 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
15393 BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
15395 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
15398 case X86::ATOMMAX8:
15399 case X86::ATOMMAX16:
15400 case X86::ATOMMAX32:
15401 case X86::ATOMMAX64:
15402 case X86::ATOMMIN8:
15403 case X86::ATOMMIN16:
15404 case X86::ATOMMIN32:
15405 case X86::ATOMMIN64:
15406 case X86::ATOMUMAX8:
15407 case X86::ATOMUMAX16:
15408 case X86::ATOMUMAX32:
15409 case X86::ATOMUMAX64:
15410 case X86::ATOMUMIN8:
15411 case X86::ATOMUMIN16:
15412 case X86::ATOMUMIN32:
15413 case X86::ATOMUMIN64: {
15415 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
15417 BuildMI(mainMBB, DL, TII->get(CMPOpc))
15421 if (Subtarget->hasCMov()) {
15422 if (VT != MVT::i8) {
15424 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
15428 // Promote i8 to i32 to use CMOV32
15429 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15430 const TargetRegisterClass *RC32 =
15431 TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
15432 unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
15433 unsigned AccReg32 = MRI.createVirtualRegister(RC32);
15434 unsigned Tmp = MRI.createVirtualRegister(RC32);
15436 unsigned Undef = MRI.createVirtualRegister(RC32);
15437 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
15439 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
15442 .addImm(X86::sub_8bit);
15443 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
15446 .addImm(X86::sub_8bit);
15448 BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
15452 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
15453 .addReg(Tmp, 0, X86::sub_8bit);
15456 // Use pseudo select and lower them.
15457 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
15458 "Invalid atomic-load-op transformation!");
15459 unsigned SelOpc = getPseudoCMOVOpc(VT);
15460 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
15461 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
15462 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
15463 .addReg(SrcReg).addReg(t4)
15465 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15466 // Replace the original PHI node as mainMBB is changed after CMOV
15468 BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
15469 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15470 Phi->eraseFromParent();
15476 // Copy PhyReg back from virtual register.
15477 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
15480 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15481 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15482 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15484 NewMO.setIsKill(false);
15485 MIB.addOperand(NewMO);
15488 MIB.setMemRefs(MMOBegin, MMOEnd);
15490 // Copy PhyReg back to virtual register.
15491 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
15494 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15496 mainMBB->addSuccessor(origMainMBB);
15497 mainMBB->addSuccessor(sinkMBB);
15500 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15501 TII->get(TargetOpcode::COPY), DstReg)
15504 MI->eraseFromParent();
15508 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
15509 // instructions. They will be translated into a spin-loop or compare-exchange
15513 // dst = atomic-fetch-op MI.addr, MI.val
15519 // t1L = LOAD [MI.addr + 0]
15520 // t1H = LOAD [MI.addr + 4]
15522 // t4L = phi(t1L, t3L / loop)
15523 // t4H = phi(t1H, t3H / loop)
15524 // t2L = OP MI.val.lo, t4L
15525 // t2H = OP MI.val.hi, t4H
15530 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15538 MachineBasicBlock *
15539 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
15540 MachineBasicBlock *MBB) const {
15541 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15542 DebugLoc DL = MI->getDebugLoc();
15544 MachineFunction *MF = MBB->getParent();
15545 MachineRegisterInfo &MRI = MF->getRegInfo();
15547 const BasicBlock *BB = MBB->getBasicBlock();
15548 MachineFunction::iterator I = MBB;
15551 assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
15552 "Unexpected number of operands");
15554 assert(MI->hasOneMemOperand() &&
15555 "Expected atomic-load-op32 to have one memoperand");
15557 // Memory Reference
15558 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15559 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15561 unsigned DstLoReg, DstHiReg;
15562 unsigned SrcLoReg, SrcHiReg;
15563 unsigned MemOpndSlot;
15565 unsigned CurOp = 0;
15567 DstLoReg = MI->getOperand(CurOp++).getReg();
15568 DstHiReg = MI->getOperand(CurOp++).getReg();
15569 MemOpndSlot = CurOp;
15570 CurOp += X86::AddrNumOperands;
15571 SrcLoReg = MI->getOperand(CurOp++).getReg();
15572 SrcHiReg = MI->getOperand(CurOp++).getReg();
15574 const TargetRegisterClass *RC = &X86::GR32RegClass;
15575 const TargetRegisterClass *RC8 = &X86::GR8RegClass;
15577 unsigned t1L = MRI.createVirtualRegister(RC);
15578 unsigned t1H = MRI.createVirtualRegister(RC);
15579 unsigned t2L = MRI.createVirtualRegister(RC);
15580 unsigned t2H = MRI.createVirtualRegister(RC);
15581 unsigned t3L = MRI.createVirtualRegister(RC);
15582 unsigned t3H = MRI.createVirtualRegister(RC);
15583 unsigned t4L = MRI.createVirtualRegister(RC);
15584 unsigned t4H = MRI.createVirtualRegister(RC);
15586 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
15587 unsigned LOADOpc = X86::MOV32rm;
15589 // For the atomic load-arith operator, we generate
15592 // t1L = LOAD [MI.addr + 0]
15593 // t1H = LOAD [MI.addr + 4]
15595 // t4L = phi(t1L / thisMBB, t3L / mainMBB)
15596 // t4H = phi(t1H / thisMBB, t3H / mainMBB)
15597 // t2L = OP MI.val.lo, t4L
15598 // t2H = OP MI.val.hi, t4H
15601 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15609 MachineBasicBlock *thisMBB = MBB;
15610 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15611 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15612 MF->insert(I, mainMBB);
15613 MF->insert(I, sinkMBB);
15615 MachineInstrBuilder MIB;
15617 // Transfer the remainder of BB and its successor edges to sinkMBB.
15618 sinkMBB->splice(sinkMBB->begin(), MBB,
15619 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15620 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15624 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
15625 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15626 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15628 NewMO.setIsKill(false);
15629 MIB.addOperand(NewMO);
15631 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15632 unsigned flags = (*MMOI)->getFlags();
15633 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15634 MachineMemOperand *MMO =
15635 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15636 (*MMOI)->getSize(),
15637 (*MMOI)->getBaseAlignment(),
15638 (*MMOI)->getTBAAInfo(),
15639 (*MMOI)->getRanges());
15640 MIB.addMemOperand(MMO);
15642 MachineInstr *LowMI = MIB;
15645 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
15646 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15647 if (i == X86::AddrDisp) {
15648 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
15650 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15652 NewMO.setIsKill(false);
15653 MIB.addOperand(NewMO);
15656 MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
15658 thisMBB->addSuccessor(mainMBB);
15661 MachineBasicBlock *origMainMBB = mainMBB;
15664 MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
15665 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15666 MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
15667 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15669 unsigned Opc = MI->getOpcode();
15672 llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
15673 case X86::ATOMAND6432:
15674 case X86::ATOMOR6432:
15675 case X86::ATOMXOR6432:
15676 case X86::ATOMADD6432:
15677 case X86::ATOMSUB6432: {
15679 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15680 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
15682 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
15686 case X86::ATOMNAND6432: {
15687 unsigned HiOpc, NOTOpc;
15688 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
15689 unsigned TmpL = MRI.createVirtualRegister(RC);
15690 unsigned TmpH = MRI.createVirtualRegister(RC);
15691 BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
15693 BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
15695 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
15696 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
15699 case X86::ATOMMAX6432:
15700 case X86::ATOMMIN6432:
15701 case X86::ATOMUMAX6432:
15702 case X86::ATOMUMIN6432: {
15704 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15705 unsigned cL = MRI.createVirtualRegister(RC8);
15706 unsigned cH = MRI.createVirtualRegister(RC8);
15707 unsigned cL32 = MRI.createVirtualRegister(RC);
15708 unsigned cH32 = MRI.createVirtualRegister(RC);
15709 unsigned cc = MRI.createVirtualRegister(RC);
15710 // cl := cmp src_lo, lo
15711 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15712 .addReg(SrcLoReg).addReg(t4L);
15713 BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
15714 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
15715 // ch := cmp src_hi, hi
15716 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15717 .addReg(SrcHiReg).addReg(t4H);
15718 BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
15719 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
15720 // cc := if (src_hi == hi) ? cl : ch;
15721 if (Subtarget->hasCMov()) {
15722 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
15723 .addReg(cH32).addReg(cL32);
15725 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
15726 .addReg(cH32).addReg(cL32)
15727 .addImm(X86::COND_E);
15728 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15730 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
15731 if (Subtarget->hasCMov()) {
15732 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
15733 .addReg(SrcLoReg).addReg(t4L);
15734 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
15735 .addReg(SrcHiReg).addReg(t4H);
15737 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
15738 .addReg(SrcLoReg).addReg(t4L)
15739 .addImm(X86::COND_NE);
15740 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15741 // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
15742 // 2nd CMOV lowering.
15743 mainMBB->addLiveIn(X86::EFLAGS);
15744 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
15745 .addReg(SrcHiReg).addReg(t4H)
15746 .addImm(X86::COND_NE);
15747 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15748 // Replace the original PHI node as mainMBB is changed after CMOV
15750 BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
15751 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15752 BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
15753 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15754 PhiL->eraseFromParent();
15755 PhiH->eraseFromParent();
15759 case X86::ATOMSWAP6432: {
15761 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15762 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
15763 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
15768 // Copy EDX:EAX back from HiReg:LoReg
15769 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
15770 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
15771 // Copy ECX:EBX from t1H:t1L
15772 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
15773 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
15775 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15776 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15777 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15779 NewMO.setIsKill(false);
15780 MIB.addOperand(NewMO);
15782 MIB.setMemRefs(MMOBegin, MMOEnd);
15784 // Copy EDX:EAX back to t3H:t3L
15785 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
15786 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
15788 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15790 mainMBB->addSuccessor(origMainMBB);
15791 mainMBB->addSuccessor(sinkMBB);
15794 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15795 TII->get(TargetOpcode::COPY), DstLoReg)
15797 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15798 TII->get(TargetOpcode::COPY), DstHiReg)
15801 MI->eraseFromParent();
15805 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
15806 // or XMM0_V32I8 in AVX all of this code can be replaced with that
15807 // in the .td file.
15808 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
15809 const TargetInstrInfo *TII) {
15811 switch (MI->getOpcode()) {
15812 default: llvm_unreachable("illegal opcode!");
15813 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
15814 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
15815 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
15816 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
15817 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
15818 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
15819 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
15820 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
15823 DebugLoc dl = MI->getDebugLoc();
15824 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15826 unsigned NumArgs = MI->getNumOperands();
15827 for (unsigned i = 1; i < NumArgs; ++i) {
15828 MachineOperand &Op = MI->getOperand(i);
15829 if (!(Op.isReg() && Op.isImplicit()))
15830 MIB.addOperand(Op);
15832 if (MI->hasOneMemOperand())
15833 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15835 BuildMI(*BB, MI, dl,
15836 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15837 .addReg(X86::XMM0);
15839 MI->eraseFromParent();
15843 // FIXME: Custom handling because TableGen doesn't support multiple implicit
15844 // defs in an instruction pattern
15845 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
15846 const TargetInstrInfo *TII) {
15848 switch (MI->getOpcode()) {
15849 default: llvm_unreachable("illegal opcode!");
15850 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
15851 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
15852 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
15853 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
15854 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
15855 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
15856 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
15857 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
15860 DebugLoc dl = MI->getDebugLoc();
15861 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15863 unsigned NumArgs = MI->getNumOperands(); // remove the results
15864 for (unsigned i = 1; i < NumArgs; ++i) {
15865 MachineOperand &Op = MI->getOperand(i);
15866 if (!(Op.isReg() && Op.isImplicit()))
15867 MIB.addOperand(Op);
15869 if (MI->hasOneMemOperand())
15870 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15872 BuildMI(*BB, MI, dl,
15873 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15876 MI->eraseFromParent();
15880 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
15881 const TargetInstrInfo *TII,
15882 const X86Subtarget* Subtarget) {
15883 DebugLoc dl = MI->getDebugLoc();
15885 // Address into RAX/EAX, other two args into ECX, EDX.
15886 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
15887 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
15888 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
15889 for (int i = 0; i < X86::AddrNumOperands; ++i)
15890 MIB.addOperand(MI->getOperand(i));
15892 unsigned ValOps = X86::AddrNumOperands;
15893 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
15894 .addReg(MI->getOperand(ValOps).getReg());
15895 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
15896 .addReg(MI->getOperand(ValOps+1).getReg());
15898 // The instruction doesn't actually take any operands though.
15899 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
15901 MI->eraseFromParent(); // The pseudo is gone now.
15905 MachineBasicBlock *
15906 X86TargetLowering::EmitVAARG64WithCustomInserter(
15908 MachineBasicBlock *MBB) const {
15909 // Emit va_arg instruction on X86-64.
15911 // Operands to this pseudo-instruction:
15912 // 0 ) Output : destination address (reg)
15913 // 1-5) Input : va_list address (addr, i64mem)
15914 // 6 ) ArgSize : Size (in bytes) of vararg type
15915 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
15916 // 8 ) Align : Alignment of type
15917 // 9 ) EFLAGS (implicit-def)
15919 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
15920 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
15922 unsigned DestReg = MI->getOperand(0).getReg();
15923 MachineOperand &Base = MI->getOperand(1);
15924 MachineOperand &Scale = MI->getOperand(2);
15925 MachineOperand &Index = MI->getOperand(3);
15926 MachineOperand &Disp = MI->getOperand(4);
15927 MachineOperand &Segment = MI->getOperand(5);
15928 unsigned ArgSize = MI->getOperand(6).getImm();
15929 unsigned ArgMode = MI->getOperand(7).getImm();
15930 unsigned Align = MI->getOperand(8).getImm();
15932 // Memory Reference
15933 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
15934 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15935 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15937 // Machine Information
15938 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15939 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
15940 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
15941 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
15942 DebugLoc DL = MI->getDebugLoc();
15944 // struct va_list {
15947 // i64 overflow_area (address)
15948 // i64 reg_save_area (address)
15950 // sizeof(va_list) = 24
15951 // alignment(va_list) = 8
15953 unsigned TotalNumIntRegs = 6;
15954 unsigned TotalNumXMMRegs = 8;
15955 bool UseGPOffset = (ArgMode == 1);
15956 bool UseFPOffset = (ArgMode == 2);
15957 unsigned MaxOffset = TotalNumIntRegs * 8 +
15958 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
15960 /* Align ArgSize to a multiple of 8 */
15961 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
15962 bool NeedsAlign = (Align > 8);
15964 MachineBasicBlock *thisMBB = MBB;
15965 MachineBasicBlock *overflowMBB;
15966 MachineBasicBlock *offsetMBB;
15967 MachineBasicBlock *endMBB;
15969 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
15970 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
15971 unsigned OffsetReg = 0;
15973 if (!UseGPOffset && !UseFPOffset) {
15974 // If we only pull from the overflow region, we don't create a branch.
15975 // We don't need to alter control flow.
15976 OffsetDestReg = 0; // unused
15977 OverflowDestReg = DestReg;
15979 offsetMBB = nullptr;
15980 overflowMBB = thisMBB;
15983 // First emit code to check if gp_offset (or fp_offset) is below the bound.
15984 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
15985 // If not, pull from overflow_area. (branch to overflowMBB)
15990 // offsetMBB overflowMBB
15995 // Registers for the PHI in endMBB
15996 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
15997 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
15999 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
16000 MachineFunction *MF = MBB->getParent();
16001 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16002 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16003 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16005 MachineFunction::iterator MBBIter = MBB;
16008 // Insert the new basic blocks
16009 MF->insert(MBBIter, offsetMBB);
16010 MF->insert(MBBIter, overflowMBB);
16011 MF->insert(MBBIter, endMBB);
16013 // Transfer the remainder of MBB and its successor edges to endMBB.
16014 endMBB->splice(endMBB->begin(), thisMBB,
16015 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
16016 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
16018 // Make offsetMBB and overflowMBB successors of thisMBB
16019 thisMBB->addSuccessor(offsetMBB);
16020 thisMBB->addSuccessor(overflowMBB);
16022 // endMBB is a successor of both offsetMBB and overflowMBB
16023 offsetMBB->addSuccessor(endMBB);
16024 overflowMBB->addSuccessor(endMBB);
16026 // Load the offset value into a register
16027 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
16028 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
16032 .addDisp(Disp, UseFPOffset ? 4 : 0)
16033 .addOperand(Segment)
16034 .setMemRefs(MMOBegin, MMOEnd);
16036 // Check if there is enough room left to pull this argument.
16037 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
16039 .addImm(MaxOffset + 8 - ArgSizeA8);
16041 // Branch to "overflowMBB" if offset >= max
16042 // Fall through to "offsetMBB" otherwise
16043 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
16044 .addMBB(overflowMBB);
16047 // In offsetMBB, emit code to use the reg_save_area.
16049 assert(OffsetReg != 0);
16051 // Read the reg_save_area address.
16052 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
16053 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
16058 .addOperand(Segment)
16059 .setMemRefs(MMOBegin, MMOEnd);
16061 // Zero-extend the offset
16062 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
16063 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
16066 .addImm(X86::sub_32bit);
16068 // Add the offset to the reg_save_area to get the final address.
16069 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
16070 .addReg(OffsetReg64)
16071 .addReg(RegSaveReg);
16073 // Compute the offset for the next argument
16074 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
16075 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
16077 .addImm(UseFPOffset ? 16 : 8);
16079 // Store it back into the va_list.
16080 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
16084 .addDisp(Disp, UseFPOffset ? 4 : 0)
16085 .addOperand(Segment)
16086 .addReg(NextOffsetReg)
16087 .setMemRefs(MMOBegin, MMOEnd);
16090 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
16095 // Emit code to use overflow area
16098 // Load the overflow_area address into a register.
16099 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
16100 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
16105 .addOperand(Segment)
16106 .setMemRefs(MMOBegin, MMOEnd);
16108 // If we need to align it, do so. Otherwise, just copy the address
16109 // to OverflowDestReg.
16111 // Align the overflow address
16112 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
16113 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
16115 // aligned_addr = (addr + (align-1)) & ~(align-1)
16116 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
16117 .addReg(OverflowAddrReg)
16120 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
16122 .addImm(~(uint64_t)(Align-1));
16124 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
16125 .addReg(OverflowAddrReg);
16128 // Compute the next overflow address after this argument.
16129 // (the overflow address should be kept 8-byte aligned)
16130 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
16131 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
16132 .addReg(OverflowDestReg)
16133 .addImm(ArgSizeA8);
16135 // Store the new overflow address.
16136 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
16141 .addOperand(Segment)
16142 .addReg(NextAddrReg)
16143 .setMemRefs(MMOBegin, MMOEnd);
16145 // If we branched, emit the PHI to the front of endMBB.
16147 BuildMI(*endMBB, endMBB->begin(), DL,
16148 TII->get(X86::PHI), DestReg)
16149 .addReg(OffsetDestReg).addMBB(offsetMBB)
16150 .addReg(OverflowDestReg).addMBB(overflowMBB);
16153 // Erase the pseudo instruction
16154 MI->eraseFromParent();
16159 MachineBasicBlock *
16160 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
16162 MachineBasicBlock *MBB) const {
16163 // Emit code to save XMM registers to the stack. The ABI says that the
16164 // number of registers to save is given in %al, so it's theoretically
16165 // possible to do an indirect jump trick to avoid saving all of them,
16166 // however this code takes a simpler approach and just executes all
16167 // of the stores if %al is non-zero. It's less code, and it's probably
16168 // easier on the hardware branch predictor, and stores aren't all that
16169 // expensive anyway.
16171 // Create the new basic blocks. One block contains all the XMM stores,
16172 // and one block is the final destination regardless of whether any
16173 // stores were performed.
16174 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
16175 MachineFunction *F = MBB->getParent();
16176 MachineFunction::iterator MBBIter = MBB;
16178 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
16179 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
16180 F->insert(MBBIter, XMMSaveMBB);
16181 F->insert(MBBIter, EndMBB);
16183 // Transfer the remainder of MBB and its successor edges to EndMBB.
16184 EndMBB->splice(EndMBB->begin(), MBB,
16185 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16186 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
16188 // The original block will now fall through to the XMM save block.
16189 MBB->addSuccessor(XMMSaveMBB);
16190 // The XMMSaveMBB will fall through to the end block.
16191 XMMSaveMBB->addSuccessor(EndMBB);
16193 // Now add the instructions.
16194 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16195 DebugLoc DL = MI->getDebugLoc();
16197 unsigned CountReg = MI->getOperand(0).getReg();
16198 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
16199 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
16201 if (!Subtarget->isTargetWin64()) {
16202 // If %al is 0, branch around the XMM save block.
16203 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
16204 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
16205 MBB->addSuccessor(EndMBB);
16208 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
16209 // that was just emitted, but clearly shouldn't be "saved".
16210 assert((MI->getNumOperands() <= 3 ||
16211 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
16212 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
16213 && "Expected last argument to be EFLAGS");
16214 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
16215 // In the XMM save block, save all the XMM argument registers.
16216 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
16217 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
16218 MachineMemOperand *MMO =
16219 F->getMachineMemOperand(
16220 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
16221 MachineMemOperand::MOStore,
16222 /*Size=*/16, /*Align=*/16);
16223 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
16224 .addFrameIndex(RegSaveFrameIndex)
16225 .addImm(/*Scale=*/1)
16226 .addReg(/*IndexReg=*/0)
16227 .addImm(/*Disp=*/Offset)
16228 .addReg(/*Segment=*/0)
16229 .addReg(MI->getOperand(i).getReg())
16230 .addMemOperand(MMO);
16233 MI->eraseFromParent(); // The pseudo instruction is gone now.
16238 // The EFLAGS operand of SelectItr might be missing a kill marker
16239 // because there were multiple uses of EFLAGS, and ISel didn't know
16240 // which to mark. Figure out whether SelectItr should have had a
16241 // kill marker, and set it if it should. Returns the correct kill
16243 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
16244 MachineBasicBlock* BB,
16245 const TargetRegisterInfo* TRI) {
16246 // Scan forward through BB for a use/def of EFLAGS.
16247 MachineBasicBlock::iterator miI(std::next(SelectItr));
16248 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
16249 const MachineInstr& mi = *miI;
16250 if (mi.readsRegister(X86::EFLAGS))
16252 if (mi.definesRegister(X86::EFLAGS))
16253 break; // Should have kill-flag - update below.
16256 // If we hit the end of the block, check whether EFLAGS is live into a
16258 if (miI == BB->end()) {
16259 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
16260 sEnd = BB->succ_end();
16261 sItr != sEnd; ++sItr) {
16262 MachineBasicBlock* succ = *sItr;
16263 if (succ->isLiveIn(X86::EFLAGS))
16268 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
16269 // out. SelectMI should have a kill flag on EFLAGS.
16270 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
16274 MachineBasicBlock *
16275 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
16276 MachineBasicBlock *BB) const {
16277 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16278 DebugLoc DL = MI->getDebugLoc();
16280 // To "insert" a SELECT_CC instruction, we actually have to insert the
16281 // diamond control-flow pattern. The incoming instruction knows the
16282 // destination vreg to set, the condition code register to branch on, the
16283 // true/false values to select between, and a branch opcode to use.
16284 const BasicBlock *LLVM_BB = BB->getBasicBlock();
16285 MachineFunction::iterator It = BB;
16291 // cmpTY ccX, r1, r2
16293 // fallthrough --> copy0MBB
16294 MachineBasicBlock *thisMBB = BB;
16295 MachineFunction *F = BB->getParent();
16296 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
16297 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
16298 F->insert(It, copy0MBB);
16299 F->insert(It, sinkMBB);
16301 // If the EFLAGS register isn't dead in the terminator, then claim that it's
16302 // live into the sink and copy blocks.
16303 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
16304 if (!MI->killsRegister(X86::EFLAGS) &&
16305 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
16306 copy0MBB->addLiveIn(X86::EFLAGS);
16307 sinkMBB->addLiveIn(X86::EFLAGS);
16310 // Transfer the remainder of BB and its successor edges to sinkMBB.
16311 sinkMBB->splice(sinkMBB->begin(), BB,
16312 std::next(MachineBasicBlock::iterator(MI)), BB->end());
16313 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
16315 // Add the true and fallthrough blocks as its successors.
16316 BB->addSuccessor(copy0MBB);
16317 BB->addSuccessor(sinkMBB);
16319 // Create the conditional branch instruction.
16321 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
16322 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
16325 // %FalseValue = ...
16326 // # fallthrough to sinkMBB
16327 copy0MBB->addSuccessor(sinkMBB);
16330 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
16332 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16333 TII->get(X86::PHI), MI->getOperand(0).getReg())
16334 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
16335 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
16337 MI->eraseFromParent(); // The pseudo instruction is gone now.
16341 MachineBasicBlock *
16342 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
16343 bool Is64Bit) const {
16344 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16345 DebugLoc DL = MI->getDebugLoc();
16346 MachineFunction *MF = BB->getParent();
16347 const BasicBlock *LLVM_BB = BB->getBasicBlock();
16349 assert(MF->shouldSplitStack());
16351 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
16352 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
16355 // ... [Till the alloca]
16356 // If stacklet is not large enough, jump to mallocMBB
16359 // Allocate by subtracting from RSP
16360 // Jump to continueMBB
16363 // Allocate by call to runtime
16367 // [rest of original BB]
16370 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16371 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16372 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16374 MachineRegisterInfo &MRI = MF->getRegInfo();
16375 const TargetRegisterClass *AddrRegClass =
16376 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
16378 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16379 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16380 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
16381 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
16382 sizeVReg = MI->getOperand(1).getReg(),
16383 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
16385 MachineFunction::iterator MBBIter = BB;
16388 MF->insert(MBBIter, bumpMBB);
16389 MF->insert(MBBIter, mallocMBB);
16390 MF->insert(MBBIter, continueMBB);
16392 continueMBB->splice(continueMBB->begin(), BB,
16393 std::next(MachineBasicBlock::iterator(MI)), BB->end());
16394 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
16396 // Add code to the main basic block to check if the stack limit has been hit,
16397 // and if so, jump to mallocMBB otherwise to bumpMBB.
16398 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
16399 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
16400 .addReg(tmpSPVReg).addReg(sizeVReg);
16401 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
16402 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
16403 .addReg(SPLimitVReg);
16404 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
16406 // bumpMBB simply decreases the stack pointer, since we know the current
16407 // stacklet has enough space.
16408 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
16409 .addReg(SPLimitVReg);
16410 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
16411 .addReg(SPLimitVReg);
16412 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16414 // Calls into a routine in libgcc to allocate more space from the heap.
16415 const uint32_t *RegMask =
16416 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16418 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
16420 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
16421 .addExternalSymbol("__morestack_allocate_stack_space")
16422 .addRegMask(RegMask)
16423 .addReg(X86::RDI, RegState::Implicit)
16424 .addReg(X86::RAX, RegState::ImplicitDefine);
16426 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
16428 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
16429 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
16430 .addExternalSymbol("__morestack_allocate_stack_space")
16431 .addRegMask(RegMask)
16432 .addReg(X86::EAX, RegState::ImplicitDefine);
16436 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
16439 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
16440 .addReg(Is64Bit ? X86::RAX : X86::EAX);
16441 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16443 // Set up the CFG correctly.
16444 BB->addSuccessor(bumpMBB);
16445 BB->addSuccessor(mallocMBB);
16446 mallocMBB->addSuccessor(continueMBB);
16447 bumpMBB->addSuccessor(continueMBB);
16449 // Take care of the PHI nodes.
16450 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
16451 MI->getOperand(0).getReg())
16452 .addReg(mallocPtrVReg).addMBB(mallocMBB)
16453 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
16455 // Delete the original pseudo instruction.
16456 MI->eraseFromParent();
16459 return continueMBB;
16462 MachineBasicBlock *
16463 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
16464 MachineBasicBlock *BB) const {
16465 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16466 DebugLoc DL = MI->getDebugLoc();
16468 assert(!Subtarget->isTargetMacho());
16470 // The lowering is pretty easy: we're just emitting the call to _alloca. The
16471 // non-trivial part is impdef of ESP.
16473 if (Subtarget->isTargetWin64()) {
16474 if (Subtarget->isTargetCygMing()) {
16475 // ___chkstk(Mingw64):
16476 // Clobbers R10, R11, RAX and EFLAGS.
16478 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16479 .addExternalSymbol("___chkstk")
16480 .addReg(X86::RAX, RegState::Implicit)
16481 .addReg(X86::RSP, RegState::Implicit)
16482 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
16483 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
16484 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16486 // __chkstk(MSVCRT): does not update stack pointer.
16487 // Clobbers R10, R11 and EFLAGS.
16488 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16489 .addExternalSymbol("__chkstk")
16490 .addReg(X86::RAX, RegState::Implicit)
16491 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16492 // RAX has the offset to be subtracted from RSP.
16493 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
16498 const char *StackProbeSymbol =
16499 Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
16501 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
16502 .addExternalSymbol(StackProbeSymbol)
16503 .addReg(X86::EAX, RegState::Implicit)
16504 .addReg(X86::ESP, RegState::Implicit)
16505 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
16506 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
16507 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16510 MI->eraseFromParent(); // The pseudo instruction is gone now.
16514 MachineBasicBlock *
16515 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
16516 MachineBasicBlock *BB) const {
16517 // This is pretty easy. We're taking the value that we received from
16518 // our load from the relocation, sticking it in either RDI (x86-64)
16519 // or EAX and doing an indirect call. The return value will then
16520 // be in the normal return register.
16521 const X86InstrInfo *TII
16522 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
16523 DebugLoc DL = MI->getDebugLoc();
16524 MachineFunction *F = BB->getParent();
16526 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
16527 assert(MI->getOperand(3).isGlobal() && "This should be a global");
16529 // Get a register mask for the lowered call.
16530 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
16531 // proper register mask.
16532 const uint32_t *RegMask =
16533 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16534 if (Subtarget->is64Bit()) {
16535 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16536 TII->get(X86::MOV64rm), X86::RDI)
16538 .addImm(0).addReg(0)
16539 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16540 MI->getOperand(3).getTargetFlags())
16542 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
16543 addDirectMem(MIB, X86::RDI);
16544 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
16545 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
16546 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16547 TII->get(X86::MOV32rm), X86::EAX)
16549 .addImm(0).addReg(0)
16550 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16551 MI->getOperand(3).getTargetFlags())
16553 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16554 addDirectMem(MIB, X86::EAX);
16555 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16557 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16558 TII->get(X86::MOV32rm), X86::EAX)
16559 .addReg(TII->getGlobalBaseReg(F))
16560 .addImm(0).addReg(0)
16561 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16562 MI->getOperand(3).getTargetFlags())
16564 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16565 addDirectMem(MIB, X86::EAX);
16566 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16569 MI->eraseFromParent(); // The pseudo instruction is gone now.
16573 MachineBasicBlock *
16574 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
16575 MachineBasicBlock *MBB) const {
16576 DebugLoc DL = MI->getDebugLoc();
16577 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16579 MachineFunction *MF = MBB->getParent();
16580 MachineRegisterInfo &MRI = MF->getRegInfo();
16582 const BasicBlock *BB = MBB->getBasicBlock();
16583 MachineFunction::iterator I = MBB;
16586 // Memory Reference
16587 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16588 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16591 unsigned MemOpndSlot = 0;
16593 unsigned CurOp = 0;
16595 DstReg = MI->getOperand(CurOp++).getReg();
16596 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
16597 assert(RC->hasType(MVT::i32) && "Invalid destination!");
16598 unsigned mainDstReg = MRI.createVirtualRegister(RC);
16599 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
16601 MemOpndSlot = CurOp;
16603 MVT PVT = getPointerTy();
16604 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16605 "Invalid Pointer Size!");
16607 // For v = setjmp(buf), we generate
16610 // buf[LabelOffset] = restoreMBB
16611 // SjLjSetup restoreMBB
16617 // v = phi(main, restore)
16622 MachineBasicBlock *thisMBB = MBB;
16623 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16624 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16625 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
16626 MF->insert(I, mainMBB);
16627 MF->insert(I, sinkMBB);
16628 MF->push_back(restoreMBB);
16630 MachineInstrBuilder MIB;
16632 // Transfer the remainder of BB and its successor edges to sinkMBB.
16633 sinkMBB->splice(sinkMBB->begin(), MBB,
16634 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16635 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16638 unsigned PtrStoreOpc = 0;
16639 unsigned LabelReg = 0;
16640 const int64_t LabelOffset = 1 * PVT.getStoreSize();
16641 Reloc::Model RM = getTargetMachine().getRelocationModel();
16642 bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
16643 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
16645 // Prepare IP either in reg or imm.
16646 if (!UseImmLabel) {
16647 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
16648 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
16649 LabelReg = MRI.createVirtualRegister(PtrRC);
16650 if (Subtarget->is64Bit()) {
16651 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
16655 .addMBB(restoreMBB)
16658 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
16659 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
16660 .addReg(XII->getGlobalBaseReg(MF))
16663 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
16667 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
16669 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
16670 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16671 if (i == X86::AddrDisp)
16672 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
16674 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
16677 MIB.addReg(LabelReg);
16679 MIB.addMBB(restoreMBB);
16680 MIB.setMemRefs(MMOBegin, MMOEnd);
16682 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
16683 .addMBB(restoreMBB);
16685 const X86RegisterInfo *RegInfo =
16686 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16687 MIB.addRegMask(RegInfo->getNoPreservedMask());
16688 thisMBB->addSuccessor(mainMBB);
16689 thisMBB->addSuccessor(restoreMBB);
16693 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
16694 mainMBB->addSuccessor(sinkMBB);
16697 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16698 TII->get(X86::PHI), DstReg)
16699 .addReg(mainDstReg).addMBB(mainMBB)
16700 .addReg(restoreDstReg).addMBB(restoreMBB);
16703 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
16704 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
16705 restoreMBB->addSuccessor(sinkMBB);
16707 MI->eraseFromParent();
16711 MachineBasicBlock *
16712 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
16713 MachineBasicBlock *MBB) const {
16714 DebugLoc DL = MI->getDebugLoc();
16715 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16717 MachineFunction *MF = MBB->getParent();
16718 MachineRegisterInfo &MRI = MF->getRegInfo();
16720 // Memory Reference
16721 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16722 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16724 MVT PVT = getPointerTy();
16725 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16726 "Invalid Pointer Size!");
16728 const TargetRegisterClass *RC =
16729 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
16730 unsigned Tmp = MRI.createVirtualRegister(RC);
16731 // Since FP is only updated here but NOT referenced, it's treated as GPR.
16732 const X86RegisterInfo *RegInfo =
16733 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16734 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
16735 unsigned SP = RegInfo->getStackRegister();
16737 MachineInstrBuilder MIB;
16739 const int64_t LabelOffset = 1 * PVT.getStoreSize();
16740 const int64_t SPOffset = 2 * PVT.getStoreSize();
16742 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
16743 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
16746 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
16747 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
16748 MIB.addOperand(MI->getOperand(i));
16749 MIB.setMemRefs(MMOBegin, MMOEnd);
16751 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
16752 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16753 if (i == X86::AddrDisp)
16754 MIB.addDisp(MI->getOperand(i), LabelOffset);
16756 MIB.addOperand(MI->getOperand(i));
16758 MIB.setMemRefs(MMOBegin, MMOEnd);
16760 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
16761 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16762 if (i == X86::AddrDisp)
16763 MIB.addDisp(MI->getOperand(i), SPOffset);
16765 MIB.addOperand(MI->getOperand(i));
16767 MIB.setMemRefs(MMOBegin, MMOEnd);
16769 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
16771 MI->eraseFromParent();
16775 // Replace 213-type (isel default) FMA3 instructions with 231-type for
16776 // accumulator loops. Writing back to the accumulator allows the coalescer
16777 // to remove extra copies in the loop.
16778 MachineBasicBlock *
16779 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
16780 MachineBasicBlock *MBB) const {
16781 MachineOperand &AddendOp = MI->getOperand(3);
16783 // Bail out early if the addend isn't a register - we can't switch these.
16784 if (!AddendOp.isReg())
16787 MachineFunction &MF = *MBB->getParent();
16788 MachineRegisterInfo &MRI = MF.getRegInfo();
16790 // Check whether the addend is defined by a PHI:
16791 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
16792 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
16793 if (!AddendDef.isPHI())
16796 // Look for the following pattern:
16798 // %addend = phi [%entry, 0], [%loop, %result]
16800 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
16804 // %addend = phi [%entry, 0], [%loop, %result]
16806 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
16808 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
16809 assert(AddendDef.getOperand(i).isReg());
16810 MachineOperand PHISrcOp = AddendDef.getOperand(i);
16811 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
16812 if (&PHISrcInst == MI) {
16813 // Found a matching instruction.
16814 unsigned NewFMAOpc = 0;
16815 switch (MI->getOpcode()) {
16816 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
16817 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
16818 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
16819 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
16820 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
16821 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
16822 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
16823 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
16824 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
16825 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
16826 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
16827 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
16828 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
16829 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
16830 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
16831 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
16832 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
16833 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
16834 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
16835 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
16836 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
16837 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
16838 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
16839 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
16840 default: llvm_unreachable("Unrecognized FMA variant.");
16843 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
16844 MachineInstrBuilder MIB =
16845 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
16846 .addOperand(MI->getOperand(0))
16847 .addOperand(MI->getOperand(3))
16848 .addOperand(MI->getOperand(2))
16849 .addOperand(MI->getOperand(1));
16850 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
16851 MI->eraseFromParent();
16858 MachineBasicBlock *
16859 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
16860 MachineBasicBlock *BB) const {
16861 switch (MI->getOpcode()) {
16862 default: llvm_unreachable("Unexpected instr type to insert");
16863 case X86::TAILJMPd64:
16864 case X86::TAILJMPr64:
16865 case X86::TAILJMPm64:
16866 llvm_unreachable("TAILJMP64 would not be touched here.");
16867 case X86::TCRETURNdi64:
16868 case X86::TCRETURNri64:
16869 case X86::TCRETURNmi64:
16871 case X86::WIN_ALLOCA:
16872 return EmitLoweredWinAlloca(MI, BB);
16873 case X86::SEG_ALLOCA_32:
16874 return EmitLoweredSegAlloca(MI, BB, false);
16875 case X86::SEG_ALLOCA_64:
16876 return EmitLoweredSegAlloca(MI, BB, true);
16877 case X86::TLSCall_32:
16878 case X86::TLSCall_64:
16879 return EmitLoweredTLSCall(MI, BB);
16880 case X86::CMOV_GR8:
16881 case X86::CMOV_FR32:
16882 case X86::CMOV_FR64:
16883 case X86::CMOV_V4F32:
16884 case X86::CMOV_V2F64:
16885 case X86::CMOV_V2I64:
16886 case X86::CMOV_V8F32:
16887 case X86::CMOV_V4F64:
16888 case X86::CMOV_V4I64:
16889 case X86::CMOV_V16F32:
16890 case X86::CMOV_V8F64:
16891 case X86::CMOV_V8I64:
16892 case X86::CMOV_GR16:
16893 case X86::CMOV_GR32:
16894 case X86::CMOV_RFP32:
16895 case X86::CMOV_RFP64:
16896 case X86::CMOV_RFP80:
16897 return EmitLoweredSelect(MI, BB);
16899 case X86::FP32_TO_INT16_IN_MEM:
16900 case X86::FP32_TO_INT32_IN_MEM:
16901 case X86::FP32_TO_INT64_IN_MEM:
16902 case X86::FP64_TO_INT16_IN_MEM:
16903 case X86::FP64_TO_INT32_IN_MEM:
16904 case X86::FP64_TO_INT64_IN_MEM:
16905 case X86::FP80_TO_INT16_IN_MEM:
16906 case X86::FP80_TO_INT32_IN_MEM:
16907 case X86::FP80_TO_INT64_IN_MEM: {
16908 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16909 DebugLoc DL = MI->getDebugLoc();
16911 // Change the floating point control register to use "round towards zero"
16912 // mode when truncating to an integer value.
16913 MachineFunction *F = BB->getParent();
16914 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
16915 addFrameReference(BuildMI(*BB, MI, DL,
16916 TII->get(X86::FNSTCW16m)), CWFrameIdx);
16918 // Load the old value of the high byte of the control word...
16920 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
16921 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
16924 // Set the high part to be round to zero...
16925 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
16928 // Reload the modified control word now...
16929 addFrameReference(BuildMI(*BB, MI, DL,
16930 TII->get(X86::FLDCW16m)), CWFrameIdx);
16932 // Restore the memory image of control word to original value
16933 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
16936 // Get the X86 opcode to use.
16938 switch (MI->getOpcode()) {
16939 default: llvm_unreachable("illegal opcode!");
16940 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
16941 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
16942 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
16943 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
16944 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
16945 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
16946 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
16947 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
16948 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
16952 MachineOperand &Op = MI->getOperand(0);
16954 AM.BaseType = X86AddressMode::RegBase;
16955 AM.Base.Reg = Op.getReg();
16957 AM.BaseType = X86AddressMode::FrameIndexBase;
16958 AM.Base.FrameIndex = Op.getIndex();
16960 Op = MI->getOperand(1);
16962 AM.Scale = Op.getImm();
16963 Op = MI->getOperand(2);
16965 AM.IndexReg = Op.getImm();
16966 Op = MI->getOperand(3);
16967 if (Op.isGlobal()) {
16968 AM.GV = Op.getGlobal();
16970 AM.Disp = Op.getImm();
16972 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
16973 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
16975 // Reload the original control word now.
16976 addFrameReference(BuildMI(*BB, MI, DL,
16977 TII->get(X86::FLDCW16m)), CWFrameIdx);
16979 MI->eraseFromParent(); // The pseudo instruction is gone now.
16982 // String/text processing lowering.
16983 case X86::PCMPISTRM128REG:
16984 case X86::VPCMPISTRM128REG:
16985 case X86::PCMPISTRM128MEM:
16986 case X86::VPCMPISTRM128MEM:
16987 case X86::PCMPESTRM128REG:
16988 case X86::VPCMPESTRM128REG:
16989 case X86::PCMPESTRM128MEM:
16990 case X86::VPCMPESTRM128MEM:
16991 assert(Subtarget->hasSSE42() &&
16992 "Target must have SSE4.2 or AVX features enabled");
16993 return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
16995 // String/text processing lowering.
16996 case X86::PCMPISTRIREG:
16997 case X86::VPCMPISTRIREG:
16998 case X86::PCMPISTRIMEM:
16999 case X86::VPCMPISTRIMEM:
17000 case X86::PCMPESTRIREG:
17001 case X86::VPCMPESTRIREG:
17002 case X86::PCMPESTRIMEM:
17003 case X86::VPCMPESTRIMEM:
17004 assert(Subtarget->hasSSE42() &&
17005 "Target must have SSE4.2 or AVX features enabled");
17006 return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
17008 // Thread synchronization.
17010 return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
17014 return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
17016 // Atomic Lowering.
17017 case X86::ATOMAND8:
17018 case X86::ATOMAND16:
17019 case X86::ATOMAND32:
17020 case X86::ATOMAND64:
17023 case X86::ATOMOR16:
17024 case X86::ATOMOR32:
17025 case X86::ATOMOR64:
17027 case X86::ATOMXOR16:
17028 case X86::ATOMXOR8:
17029 case X86::ATOMXOR32:
17030 case X86::ATOMXOR64:
17032 case X86::ATOMNAND8:
17033 case X86::ATOMNAND16:
17034 case X86::ATOMNAND32:
17035 case X86::ATOMNAND64:
17037 case X86::ATOMMAX8:
17038 case X86::ATOMMAX16:
17039 case X86::ATOMMAX32:
17040 case X86::ATOMMAX64:
17042 case X86::ATOMMIN8:
17043 case X86::ATOMMIN16:
17044 case X86::ATOMMIN32:
17045 case X86::ATOMMIN64:
17047 case X86::ATOMUMAX8:
17048 case X86::ATOMUMAX16:
17049 case X86::ATOMUMAX32:
17050 case X86::ATOMUMAX64:
17052 case X86::ATOMUMIN8:
17053 case X86::ATOMUMIN16:
17054 case X86::ATOMUMIN32:
17055 case X86::ATOMUMIN64:
17056 return EmitAtomicLoadArith(MI, BB);
17058 // This group does 64-bit operations on a 32-bit host.
17059 case X86::ATOMAND6432:
17060 case X86::ATOMOR6432:
17061 case X86::ATOMXOR6432:
17062 case X86::ATOMNAND6432:
17063 case X86::ATOMADD6432:
17064 case X86::ATOMSUB6432:
17065 case X86::ATOMMAX6432:
17066 case X86::ATOMMIN6432:
17067 case X86::ATOMUMAX6432:
17068 case X86::ATOMUMIN6432:
17069 case X86::ATOMSWAP6432:
17070 return EmitAtomicLoadArith6432(MI, BB);
17072 case X86::VASTART_SAVE_XMM_REGS:
17073 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
17075 case X86::VAARG_64:
17076 return EmitVAARG64WithCustomInserter(MI, BB);
17078 case X86::EH_SjLj_SetJmp32:
17079 case X86::EH_SjLj_SetJmp64:
17080 return emitEHSjLjSetJmp(MI, BB);
17082 case X86::EH_SjLj_LongJmp32:
17083 case X86::EH_SjLj_LongJmp64:
17084 return emitEHSjLjLongJmp(MI, BB);
17086 case TargetOpcode::STACKMAP:
17087 case TargetOpcode::PATCHPOINT:
17088 return emitPatchPoint(MI, BB);
17090 case X86::VFMADDPDr213r:
17091 case X86::VFMADDPSr213r:
17092 case X86::VFMADDSDr213r:
17093 case X86::VFMADDSSr213r:
17094 case X86::VFMSUBPDr213r:
17095 case X86::VFMSUBPSr213r:
17096 case X86::VFMSUBSDr213r:
17097 case X86::VFMSUBSSr213r:
17098 case X86::VFNMADDPDr213r:
17099 case X86::VFNMADDPSr213r:
17100 case X86::VFNMADDSDr213r:
17101 case X86::VFNMADDSSr213r:
17102 case X86::VFNMSUBPDr213r:
17103 case X86::VFNMSUBPSr213r:
17104 case X86::VFNMSUBSDr213r:
17105 case X86::VFNMSUBSSr213r:
17106 case X86::VFMADDPDr213rY:
17107 case X86::VFMADDPSr213rY:
17108 case X86::VFMSUBPDr213rY:
17109 case X86::VFMSUBPSr213rY:
17110 case X86::VFNMADDPDr213rY:
17111 case X86::VFNMADDPSr213rY:
17112 case X86::VFNMSUBPDr213rY:
17113 case X86::VFNMSUBPSr213rY:
17114 return emitFMA3Instr(MI, BB);
17118 //===----------------------------------------------------------------------===//
17119 // X86 Optimization Hooks
17120 //===----------------------------------------------------------------------===//
17122 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
17125 const SelectionDAG &DAG,
17126 unsigned Depth) const {
17127 unsigned BitWidth = KnownZero.getBitWidth();
17128 unsigned Opc = Op.getOpcode();
17129 assert((Opc >= ISD::BUILTIN_OP_END ||
17130 Opc == ISD::INTRINSIC_WO_CHAIN ||
17131 Opc == ISD::INTRINSIC_W_CHAIN ||
17132 Opc == ISD::INTRINSIC_VOID) &&
17133 "Should use MaskedValueIsZero if you don't know whether Op"
17134 " is a target node!");
17136 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
17150 // These nodes' second result is a boolean.
17151 if (Op.getResNo() == 0)
17154 case X86ISD::SETCC:
17155 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
17157 case ISD::INTRINSIC_WO_CHAIN: {
17158 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17159 unsigned NumLoBits = 0;
17162 case Intrinsic::x86_sse_movmsk_ps:
17163 case Intrinsic::x86_avx_movmsk_ps_256:
17164 case Intrinsic::x86_sse2_movmsk_pd:
17165 case Intrinsic::x86_avx_movmsk_pd_256:
17166 case Intrinsic::x86_mmx_pmovmskb:
17167 case Intrinsic::x86_sse2_pmovmskb_128:
17168 case Intrinsic::x86_avx2_pmovmskb: {
17169 // High bits of movmskp{s|d}, pmovmskb are known zero.
17171 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
17172 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
17173 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
17174 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
17175 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
17176 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
17177 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
17178 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
17180 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
17189 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
17191 const SelectionDAG &,
17192 unsigned Depth) const {
17193 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
17194 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
17195 return Op.getValueType().getScalarType().getSizeInBits();
17201 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
17202 /// node is a GlobalAddress + offset.
17203 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
17204 const GlobalValue* &GA,
17205 int64_t &Offset) const {
17206 if (N->getOpcode() == X86ISD::Wrapper) {
17207 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
17208 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
17209 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
17213 return TargetLowering::isGAPlusOffset(N, GA, Offset);
17216 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
17217 /// same as extracting the high 128-bit part of 256-bit vector and then
17218 /// inserting the result into the low part of a new 256-bit vector
17219 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
17220 EVT VT = SVOp->getValueType(0);
17221 unsigned NumElems = VT.getVectorNumElements();
17223 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17224 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
17225 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17226 SVOp->getMaskElt(j) >= 0)
17232 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
17233 /// same as extracting the low 128-bit part of 256-bit vector and then
17234 /// inserting the result into the high part of a new 256-bit vector
17235 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
17236 EVT VT = SVOp->getValueType(0);
17237 unsigned NumElems = VT.getVectorNumElements();
17239 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17240 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
17241 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17242 SVOp->getMaskElt(j) >= 0)
17248 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
17249 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
17250 TargetLowering::DAGCombinerInfo &DCI,
17251 const X86Subtarget* Subtarget) {
17253 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17254 SDValue V1 = SVOp->getOperand(0);
17255 SDValue V2 = SVOp->getOperand(1);
17256 EVT VT = SVOp->getValueType(0);
17257 unsigned NumElems = VT.getVectorNumElements();
17259 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
17260 V2.getOpcode() == ISD::CONCAT_VECTORS) {
17264 // V UNDEF BUILD_VECTOR UNDEF
17266 // CONCAT_VECTOR CONCAT_VECTOR
17269 // RESULT: V + zero extended
17271 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
17272 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
17273 V1.getOperand(1).getOpcode() != ISD::UNDEF)
17276 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
17279 // To match the shuffle mask, the first half of the mask should
17280 // be exactly the first vector, and all the rest a splat with the
17281 // first element of the second one.
17282 for (unsigned i = 0; i != NumElems/2; ++i)
17283 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
17284 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
17287 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
17288 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
17289 if (Ld->hasNUsesOfValue(1, 0)) {
17290 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
17291 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
17293 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
17295 Ld->getPointerInfo(),
17296 Ld->getAlignment(),
17297 false/*isVolatile*/, true/*ReadMem*/,
17298 false/*WriteMem*/);
17300 // Make sure the newly-created LOAD is in the same position as Ld in
17301 // terms of dependency. We create a TokenFactor for Ld and ResNode,
17302 // and update uses of Ld's output chain to use the TokenFactor.
17303 if (Ld->hasAnyUseOfValue(1)) {
17304 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17305 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
17306 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
17307 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
17308 SDValue(ResNode.getNode(), 1));
17311 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
17315 // Emit a zeroed vector and insert the desired subvector on its
17317 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17318 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
17319 return DCI.CombineTo(N, InsV);
17322 //===--------------------------------------------------------------------===//
17323 // Combine some shuffles into subvector extracts and inserts:
17326 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17327 if (isShuffleHigh128VectorInsertLow(SVOp)) {
17328 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
17329 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
17330 return DCI.CombineTo(N, InsV);
17333 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17334 if (isShuffleLow128VectorInsertHigh(SVOp)) {
17335 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
17336 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
17337 return DCI.CombineTo(N, InsV);
17343 /// PerformShuffleCombine - Performs several different shuffle combines.
17344 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
17345 TargetLowering::DAGCombinerInfo &DCI,
17346 const X86Subtarget *Subtarget) {
17348 EVT VT = N->getValueType(0);
17350 // Don't create instructions with illegal types after legalize types has run.
17351 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17352 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
17355 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
17356 if (Subtarget->hasFp256() && VT.is256BitVector() &&
17357 N->getOpcode() == ISD::VECTOR_SHUFFLE)
17358 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
17360 // Only handle 128 wide vector from here on.
17361 if (!VT.is128BitVector())
17364 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
17365 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
17366 // consecutive, non-overlapping, and in the right order.
17367 SmallVector<SDValue, 16> Elts;
17368 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
17369 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
17371 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
17374 /// PerformTruncateCombine - Converts truncate operation to
17375 /// a sequence of vector shuffle operations.
17376 /// It is possible when we truncate 256-bit vector to 128-bit vector
17377 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
17378 TargetLowering::DAGCombinerInfo &DCI,
17379 const X86Subtarget *Subtarget) {
17383 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
17384 /// specific shuffle of a load can be folded into a single element load.
17385 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
17386 /// shuffles have been customed lowered so we need to handle those here.
17387 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
17388 TargetLowering::DAGCombinerInfo &DCI) {
17389 if (DCI.isBeforeLegalizeOps())
17392 SDValue InVec = N->getOperand(0);
17393 SDValue EltNo = N->getOperand(1);
17395 if (!isa<ConstantSDNode>(EltNo))
17398 EVT VT = InVec.getValueType();
17400 bool HasShuffleIntoBitcast = false;
17401 if (InVec.getOpcode() == ISD::BITCAST) {
17402 // Don't duplicate a load with other uses.
17403 if (!InVec.hasOneUse())
17405 EVT BCVT = InVec.getOperand(0).getValueType();
17406 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
17408 InVec = InVec.getOperand(0);
17409 HasShuffleIntoBitcast = true;
17412 if (!isTargetShuffle(InVec.getOpcode()))
17415 // Don't duplicate a load with other uses.
17416 if (!InVec.hasOneUse())
17419 SmallVector<int, 16> ShuffleMask;
17421 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
17425 // Select the input vector, guarding against out of range extract vector.
17426 unsigned NumElems = VT.getVectorNumElements();
17427 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
17428 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
17429 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
17430 : InVec.getOperand(1);
17432 // If inputs to shuffle are the same for both ops, then allow 2 uses
17433 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
17435 if (LdNode.getOpcode() == ISD::BITCAST) {
17436 // Don't duplicate a load with other uses.
17437 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
17440 AllowedUses = 1; // only allow 1 load use if we have a bitcast
17441 LdNode = LdNode.getOperand(0);
17444 if (!ISD::isNormalLoad(LdNode.getNode()))
17447 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
17449 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
17452 if (HasShuffleIntoBitcast) {
17453 // If there's a bitcast before the shuffle, check if the load type and
17454 // alignment is valid.
17455 unsigned Align = LN0->getAlignment();
17456 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17457 unsigned NewAlign = TLI.getDataLayout()->
17458 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
17460 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
17464 // All checks match so transform back to vector_shuffle so that DAG combiner
17465 // can finish the job
17468 // Create shuffle node taking into account the case that its a unary shuffle
17469 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
17470 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
17471 InVec.getOperand(0), Shuffle,
17473 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
17474 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
17478 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
17479 /// generation and convert it from being a bunch of shuffles and extracts
17480 /// to a simple store and scalar loads to extract the elements.
17481 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
17482 TargetLowering::DAGCombinerInfo &DCI) {
17483 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
17484 if (NewOp.getNode())
17487 SDValue InputVector = N->getOperand(0);
17489 // Detect whether we are trying to convert from mmx to i32 and the bitcast
17490 // from mmx to v2i32 has a single usage.
17491 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
17492 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
17493 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
17494 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
17495 N->getValueType(0),
17496 InputVector.getNode()->getOperand(0));
17498 // Only operate on vectors of 4 elements, where the alternative shuffling
17499 // gets to be more expensive.
17500 if (InputVector.getValueType() != MVT::v4i32)
17503 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
17504 // single use which is a sign-extend or zero-extend, and all elements are
17506 SmallVector<SDNode *, 4> Uses;
17507 unsigned ExtractedElements = 0;
17508 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
17509 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
17510 if (UI.getUse().getResNo() != InputVector.getResNo())
17513 SDNode *Extract = *UI;
17514 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
17517 if (Extract->getValueType(0) != MVT::i32)
17519 if (!Extract->hasOneUse())
17521 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
17522 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
17524 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
17527 // Record which element was extracted.
17528 ExtractedElements |=
17529 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
17531 Uses.push_back(Extract);
17534 // If not all the elements were used, this may not be worthwhile.
17535 if (ExtractedElements != 15)
17538 // Ok, we've now decided to do the transformation.
17539 SDLoc dl(InputVector);
17541 // Store the value to a temporary stack slot.
17542 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
17543 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
17544 MachinePointerInfo(), false, false, 0);
17546 // Replace each use (extract) with a load of the appropriate element.
17547 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
17548 UE = Uses.end(); UI != UE; ++UI) {
17549 SDNode *Extract = *UI;
17551 // cOMpute the element's address.
17552 SDValue Idx = Extract->getOperand(1);
17554 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
17555 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
17556 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17557 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
17559 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
17560 StackPtr, OffsetVal);
17562 // Load the scalar.
17563 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
17564 ScalarAddr, MachinePointerInfo(),
17565 false, false, false, 0);
17567 // Replace the exact with the load.
17568 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
17571 // The replacement was made in place; don't return anything.
17575 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
17576 static std::pair<unsigned, bool>
17577 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
17578 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
17579 if (!VT.isVector())
17580 return std::make_pair(0, false);
17582 bool NeedSplit = false;
17583 switch (VT.getSimpleVT().SimpleTy) {
17584 default: return std::make_pair(0, false);
17588 if (!Subtarget->hasAVX2())
17590 if (!Subtarget->hasAVX())
17591 return std::make_pair(0, false);
17596 if (!Subtarget->hasSSE2())
17597 return std::make_pair(0, false);
17600 // SSE2 has only a small subset of the operations.
17601 bool hasUnsigned = Subtarget->hasSSE41() ||
17602 (Subtarget->hasSSE2() && VT == MVT::v16i8);
17603 bool hasSigned = Subtarget->hasSSE41() ||
17604 (Subtarget->hasSSE2() && VT == MVT::v8i16);
17606 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17609 // Check for x CC y ? x : y.
17610 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17611 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17616 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17619 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17622 Opc = hasSigned ? X86ISD::SMIN : 0; break;
17625 Opc = hasSigned ? X86ISD::SMAX : 0; break;
17627 // Check for x CC y ? y : x -- a min/max with reversed arms.
17628 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17629 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17634 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17637 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17640 Opc = hasSigned ? X86ISD::SMAX : 0; break;
17643 Opc = hasSigned ? X86ISD::SMIN : 0; break;
17647 return std::make_pair(Opc, NeedSplit);
17650 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
17652 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
17653 TargetLowering::DAGCombinerInfo &DCI,
17654 const X86Subtarget *Subtarget) {
17656 SDValue Cond = N->getOperand(0);
17657 // Get the LHS/RHS of the select.
17658 SDValue LHS = N->getOperand(1);
17659 SDValue RHS = N->getOperand(2);
17660 EVT VT = LHS.getValueType();
17661 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17663 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
17664 // instructions match the semantics of the common C idiom x<y?x:y but not
17665 // x<=y?x:y, because of how they handle negative zero (which can be
17666 // ignored in unsafe-math mode).
17667 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
17668 VT != MVT::f80 && TLI.isTypeLegal(VT) &&
17669 (Subtarget->hasSSE2() ||
17670 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
17671 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17673 unsigned Opcode = 0;
17674 // Check for x CC y ? x : y.
17675 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17676 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17680 // Converting this to a min would handle NaNs incorrectly, and swapping
17681 // the operands would cause it to handle comparisons between positive
17682 // and negative zero incorrectly.
17683 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17684 if (!DAG.getTarget().Options.UnsafeFPMath &&
17685 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17687 std::swap(LHS, RHS);
17689 Opcode = X86ISD::FMIN;
17692 // Converting this to a min would handle comparisons between positive
17693 // and negative zero incorrectly.
17694 if (!DAG.getTarget().Options.UnsafeFPMath &&
17695 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17697 Opcode = X86ISD::FMIN;
17700 // Converting this to a min would handle both negative zeros and NaNs
17701 // incorrectly, but we can swap the operands to fix both.
17702 std::swap(LHS, RHS);
17706 Opcode = X86ISD::FMIN;
17710 // Converting this to a max would handle comparisons between positive
17711 // and negative zero incorrectly.
17712 if (!DAG.getTarget().Options.UnsafeFPMath &&
17713 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17715 Opcode = X86ISD::FMAX;
17718 // Converting this to a max would handle NaNs incorrectly, and swapping
17719 // the operands would cause it to handle comparisons between positive
17720 // and negative zero incorrectly.
17721 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17722 if (!DAG.getTarget().Options.UnsafeFPMath &&
17723 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17725 std::swap(LHS, RHS);
17727 Opcode = X86ISD::FMAX;
17730 // Converting this to a max would handle both negative zeros and NaNs
17731 // incorrectly, but we can swap the operands to fix both.
17732 std::swap(LHS, RHS);
17736 Opcode = X86ISD::FMAX;
17739 // Check for x CC y ? y : x -- a min/max with reversed arms.
17740 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17741 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17745 // Converting this to a min would handle comparisons between positive
17746 // and negative zero incorrectly, and swapping the operands would
17747 // cause it to handle NaNs incorrectly.
17748 if (!DAG.getTarget().Options.UnsafeFPMath &&
17749 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
17750 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17752 std::swap(LHS, RHS);
17754 Opcode = X86ISD::FMIN;
17757 // Converting this to a min would handle NaNs incorrectly.
17758 if (!DAG.getTarget().Options.UnsafeFPMath &&
17759 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
17761 Opcode = X86ISD::FMIN;
17764 // Converting this to a min would handle both negative zeros and NaNs
17765 // incorrectly, but we can swap the operands to fix both.
17766 std::swap(LHS, RHS);
17770 Opcode = X86ISD::FMIN;
17774 // Converting this to a max would handle NaNs incorrectly.
17775 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17777 Opcode = X86ISD::FMAX;
17780 // Converting this to a max would handle comparisons between positive
17781 // and negative zero incorrectly, and swapping the operands would
17782 // cause it to handle NaNs incorrectly.
17783 if (!DAG.getTarget().Options.UnsafeFPMath &&
17784 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
17785 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17787 std::swap(LHS, RHS);
17789 Opcode = X86ISD::FMAX;
17792 // Converting this to a max would handle both negative zeros and NaNs
17793 // incorrectly, but we can swap the operands to fix both.
17794 std::swap(LHS, RHS);
17798 Opcode = X86ISD::FMAX;
17804 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
17807 EVT CondVT = Cond.getValueType();
17808 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
17809 CondVT.getVectorElementType() == MVT::i1) {
17810 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
17811 // lowering on AVX-512. In this case we convert it to
17812 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
17813 // The same situation for all 128 and 256-bit vectors of i8 and i16
17814 EVT OpVT = LHS.getValueType();
17815 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
17816 (OpVT.getVectorElementType() == MVT::i8 ||
17817 OpVT.getVectorElementType() == MVT::i16)) {
17818 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
17819 DCI.AddToWorklist(Cond.getNode());
17820 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
17823 // If this is a select between two integer constants, try to do some
17825 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
17826 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
17827 // Don't do this for crazy integer types.
17828 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
17829 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
17830 // so that TrueC (the true value) is larger than FalseC.
17831 bool NeedsCondInvert = false;
17833 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
17834 // Efficiently invertible.
17835 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
17836 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
17837 isa<ConstantSDNode>(Cond.getOperand(1))))) {
17838 NeedsCondInvert = true;
17839 std::swap(TrueC, FalseC);
17842 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
17843 if (FalseC->getAPIntValue() == 0 &&
17844 TrueC->getAPIntValue().isPowerOf2()) {
17845 if (NeedsCondInvert) // Invert the condition if needed.
17846 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17847 DAG.getConstant(1, Cond.getValueType()));
17849 // Zero extend the condition if needed.
17850 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
17852 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17853 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
17854 DAG.getConstant(ShAmt, MVT::i8));
17857 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
17858 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17859 if (NeedsCondInvert) // Invert the condition if needed.
17860 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17861 DAG.getConstant(1, Cond.getValueType()));
17863 // Zero extend the condition if needed.
17864 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17865 FalseC->getValueType(0), Cond);
17866 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17867 SDValue(FalseC, 0));
17870 // Optimize cases that will turn into an LEA instruction. This requires
17871 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17872 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17873 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17874 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17876 bool isFastMultiplier = false;
17878 switch ((unsigned char)Diff) {
17880 case 1: // result = add base, cond
17881 case 2: // result = lea base( , cond*2)
17882 case 3: // result = lea base(cond, cond*2)
17883 case 4: // result = lea base( , cond*4)
17884 case 5: // result = lea base(cond, cond*4)
17885 case 8: // result = lea base( , cond*8)
17886 case 9: // result = lea base(cond, cond*8)
17887 isFastMultiplier = true;
17892 if (isFastMultiplier) {
17893 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
17894 if (NeedsCondInvert) // Invert the condition if needed.
17895 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17896 DAG.getConstant(1, Cond.getValueType()));
17898 // Zero extend the condition if needed.
17899 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
17901 // Scale the condition by the difference.
17903 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
17904 DAG.getConstant(Diff, Cond.getValueType()));
17906 // Add the base if non-zero.
17907 if (FalseC->getAPIntValue() != 0)
17908 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17909 SDValue(FalseC, 0));
17916 // Canonicalize max and min:
17917 // (x > y) ? x : y -> (x >= y) ? x : y
17918 // (x < y) ? x : y -> (x <= y) ? x : y
17919 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
17920 // the need for an extra compare
17921 // against zero. e.g.
17922 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
17924 // testl %edi, %edi
17926 // cmovgl %edi, %eax
17930 // cmovsl %eax, %edi
17931 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
17932 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17933 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17934 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17939 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
17940 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
17941 Cond.getOperand(0), Cond.getOperand(1), NewCC);
17942 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
17947 // Early exit check
17948 if (!TLI.isTypeLegal(VT))
17951 // Match VSELECTs into subs with unsigned saturation.
17952 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17953 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
17954 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
17955 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
17956 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17958 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
17959 // left side invert the predicate to simplify logic below.
17961 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
17963 CC = ISD::getSetCCInverse(CC, true);
17964 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
17968 if (Other.getNode() && Other->getNumOperands() == 2 &&
17969 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
17970 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
17971 SDValue CondRHS = Cond->getOperand(1);
17973 // Look for a general sub with unsigned saturation first.
17974 // x >= y ? x-y : 0 --> subus x, y
17975 // x > y ? x-y : 0 --> subus x, y
17976 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
17977 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
17978 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17980 // If the RHS is a constant we have to reverse the const canonicalization.
17981 // x > C-1 ? x+-C : 0 --> subus x, C
17982 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
17983 isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
17984 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17985 if (CondRHS.getConstantOperandVal(0) == -A-1)
17986 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
17987 DAG.getConstant(-A, VT));
17990 // Another special case: If C was a sign bit, the sub has been
17991 // canonicalized into a xor.
17992 // FIXME: Would it be better to use ComputeMaskedBits to determine whether
17993 // it's safe to decanonicalize the xor?
17994 // x s< 0 ? x^C : 0 --> subus x, C
17995 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
17996 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
17997 isSplatVector(OpRHS.getNode())) {
17998 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
18000 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
18005 // Try to match a min/max vector operation.
18006 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
18007 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
18008 unsigned Opc = ret.first;
18009 bool NeedSplit = ret.second;
18011 if (Opc && NeedSplit) {
18012 unsigned NumElems = VT.getVectorNumElements();
18013 // Extract the LHS vectors
18014 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
18015 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
18017 // Extract the RHS vectors
18018 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
18019 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
18021 // Create min/max for each subvector
18022 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
18023 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
18025 // Merge the result
18026 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
18028 return DAG.getNode(Opc, DL, VT, LHS, RHS);
18031 // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
18032 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
18033 // Check if SETCC has already been promoted
18034 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
18035 // Check that condition value type matches vselect operand type
18038 assert(Cond.getValueType().isVector() &&
18039 "vector select expects a vector selector!");
18041 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
18042 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
18044 if (!TValIsAllOnes && !FValIsAllZeros) {
18045 // Try invert the condition if true value is not all 1s and false value
18047 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
18048 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
18050 if (TValIsAllZeros || FValIsAllOnes) {
18051 SDValue CC = Cond.getOperand(2);
18052 ISD::CondCode NewCC =
18053 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
18054 Cond.getOperand(0).getValueType().isInteger());
18055 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
18056 std::swap(LHS, RHS);
18057 TValIsAllOnes = FValIsAllOnes;
18058 FValIsAllZeros = TValIsAllZeros;
18062 if (TValIsAllOnes || FValIsAllZeros) {
18065 if (TValIsAllOnes && FValIsAllZeros)
18067 else if (TValIsAllOnes)
18068 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
18069 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
18070 else if (FValIsAllZeros)
18071 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
18072 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
18074 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
18078 // Try to fold this VSELECT into a MOVSS/MOVSD
18079 if (N->getOpcode() == ISD::VSELECT &&
18080 Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
18081 if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
18082 (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
18083 bool CanFold = false;
18084 unsigned NumElems = Cond.getNumOperands();
18088 if (isZero(Cond.getOperand(0))) {
18091 // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
18092 // fold (vselect <0,-1> -> (movsd A, B)
18093 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
18094 CanFold = isAllOnes(Cond.getOperand(i));
18095 } else if (isAllOnes(Cond.getOperand(0))) {
18099 // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
18100 // fold (vselect <-1,0> -> (movsd B, A)
18101 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
18102 CanFold = isZero(Cond.getOperand(i));
18106 if (VT == MVT::v4i32 || VT == MVT::v4f32)
18107 return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
18108 return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
18111 if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
18112 // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
18113 // (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
18114 // (v2i64 (bitcast B)))))
18116 // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
18117 // (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
18118 // (v2f64 (bitcast B)))))
18120 // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
18121 // (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
18122 // (v2i64 (bitcast A)))))
18124 // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
18125 // (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
18126 // (v2f64 (bitcast A)))))
18128 CanFold = (isZero(Cond.getOperand(0)) &&
18129 isZero(Cond.getOperand(1)) &&
18130 isAllOnes(Cond.getOperand(2)) &&
18131 isAllOnes(Cond.getOperand(3)));
18133 if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
18134 isAllOnes(Cond.getOperand(1)) &&
18135 isZero(Cond.getOperand(2)) &&
18136 isZero(Cond.getOperand(3))) {
18138 std::swap(LHS, RHS);
18142 EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
18143 SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
18144 SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
18145 SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
18147 return DAG.getNode(ISD::BITCAST, DL, VT, Select);
18153 // If we know that this node is legal then we know that it is going to be
18154 // matched by one of the SSE/AVX BLEND instructions. These instructions only
18155 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
18156 // to simplify previous instructions.
18157 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
18158 !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
18159 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
18161 // Don't optimize vector selects that map to mask-registers.
18165 // Check all uses of that condition operand to check whether it will be
18166 // consumed by non-BLEND instructions, which may depend on all bits are set
18168 for (SDNode::use_iterator I = Cond->use_begin(),
18169 E = Cond->use_end(); I != E; ++I)
18170 if (I->getOpcode() != ISD::VSELECT)
18171 // TODO: Add other opcodes eventually lowered into BLEND.
18174 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
18175 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
18177 APInt KnownZero, KnownOne;
18178 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
18179 DCI.isBeforeLegalizeOps());
18180 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
18181 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
18182 DCI.CommitTargetLoweringOpt(TLO);
18188 // Check whether a boolean test is testing a boolean value generated by
18189 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
18192 // Simplify the following patterns:
18193 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
18194 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
18195 // to (Op EFLAGS Cond)
18197 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
18198 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
18199 // to (Op EFLAGS !Cond)
18201 // where Op could be BRCOND or CMOV.
18203 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
18204 // Quit if not CMP and SUB with its value result used.
18205 if (Cmp.getOpcode() != X86ISD::CMP &&
18206 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
18209 // Quit if not used as a boolean value.
18210 if (CC != X86::COND_E && CC != X86::COND_NE)
18213 // Check CMP operands. One of them should be 0 or 1 and the other should be
18214 // an SetCC or extended from it.
18215 SDValue Op1 = Cmp.getOperand(0);
18216 SDValue Op2 = Cmp.getOperand(1);
18219 const ConstantSDNode* C = nullptr;
18220 bool needOppositeCond = (CC == X86::COND_E);
18221 bool checkAgainstTrue = false; // Is it a comparison against 1?
18223 if ((C = dyn_cast<ConstantSDNode>(Op1)))
18225 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
18227 else // Quit if all operands are not constants.
18230 if (C->getZExtValue() == 1) {
18231 needOppositeCond = !needOppositeCond;
18232 checkAgainstTrue = true;
18233 } else if (C->getZExtValue() != 0)
18234 // Quit if the constant is neither 0 or 1.
18237 bool truncatedToBoolWithAnd = false;
18238 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
18239 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
18240 SetCC.getOpcode() == ISD::TRUNCATE ||
18241 SetCC.getOpcode() == ISD::AND) {
18242 if (SetCC.getOpcode() == ISD::AND) {
18244 ConstantSDNode *CS;
18245 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
18246 CS->getZExtValue() == 1)
18248 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
18249 CS->getZExtValue() == 1)
18253 SetCC = SetCC.getOperand(OpIdx);
18254 truncatedToBoolWithAnd = true;
18256 SetCC = SetCC.getOperand(0);
18259 switch (SetCC.getOpcode()) {
18260 case X86ISD::SETCC_CARRY:
18261 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
18262 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
18263 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
18264 // truncated to i1 using 'and'.
18265 if (checkAgainstTrue && !truncatedToBoolWithAnd)
18267 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
18268 "Invalid use of SETCC_CARRY!");
18270 case X86ISD::SETCC:
18271 // Set the condition code or opposite one if necessary.
18272 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
18273 if (needOppositeCond)
18274 CC = X86::GetOppositeBranchCondition(CC);
18275 return SetCC.getOperand(1);
18276 case X86ISD::CMOV: {
18277 // Check whether false/true value has canonical one, i.e. 0 or 1.
18278 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
18279 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
18280 // Quit if true value is not a constant.
18283 // Quit if false value is not a constant.
18285 SDValue Op = SetCC.getOperand(0);
18286 // Skip 'zext' or 'trunc' node.
18287 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
18288 Op.getOpcode() == ISD::TRUNCATE)
18289 Op = Op.getOperand(0);
18290 // A special case for rdrand/rdseed, where 0 is set if false cond is
18292 if ((Op.getOpcode() != X86ISD::RDRAND &&
18293 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
18296 // Quit if false value is not the constant 0 or 1.
18297 bool FValIsFalse = true;
18298 if (FVal && FVal->getZExtValue() != 0) {
18299 if (FVal->getZExtValue() != 1)
18301 // If FVal is 1, opposite cond is needed.
18302 needOppositeCond = !needOppositeCond;
18303 FValIsFalse = false;
18305 // Quit if TVal is not the constant opposite of FVal.
18306 if (FValIsFalse && TVal->getZExtValue() != 1)
18308 if (!FValIsFalse && TVal->getZExtValue() != 0)
18310 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
18311 if (needOppositeCond)
18312 CC = X86::GetOppositeBranchCondition(CC);
18313 return SetCC.getOperand(3);
18320 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
18321 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
18322 TargetLowering::DAGCombinerInfo &DCI,
18323 const X86Subtarget *Subtarget) {
18326 // If the flag operand isn't dead, don't touch this CMOV.
18327 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
18330 SDValue FalseOp = N->getOperand(0);
18331 SDValue TrueOp = N->getOperand(1);
18332 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
18333 SDValue Cond = N->getOperand(3);
18335 if (CC == X86::COND_E || CC == X86::COND_NE) {
18336 switch (Cond.getOpcode()) {
18340 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
18341 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
18342 return (CC == X86::COND_E) ? FalseOp : TrueOp;
18348 Flags = checkBoolTestSetCCCombine(Cond, CC);
18349 if (Flags.getNode() &&
18350 // Extra check as FCMOV only supports a subset of X86 cond.
18351 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
18352 SDValue Ops[] = { FalseOp, TrueOp,
18353 DAG.getConstant(CC, MVT::i8), Flags };
18354 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
18357 // If this is a select between two integer constants, try to do some
18358 // optimizations. Note that the operands are ordered the opposite of SELECT
18360 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
18361 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
18362 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
18363 // larger than FalseC (the false value).
18364 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
18365 CC = X86::GetOppositeBranchCondition(CC);
18366 std::swap(TrueC, FalseC);
18367 std::swap(TrueOp, FalseOp);
18370 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
18371 // This is efficient for any integer data type (including i8/i16) and
18373 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
18374 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18375 DAG.getConstant(CC, MVT::i8), Cond);
18377 // Zero extend the condition if needed.
18378 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
18380 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18381 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
18382 DAG.getConstant(ShAmt, MVT::i8));
18383 if (N->getNumValues() == 2) // Dead flag value?
18384 return DCI.CombineTo(N, Cond, SDValue());
18388 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
18389 // for any integer data type, including i8/i16.
18390 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18391 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18392 DAG.getConstant(CC, MVT::i8), Cond);
18394 // Zero extend the condition if needed.
18395 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18396 FalseC->getValueType(0), Cond);
18397 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18398 SDValue(FalseC, 0));
18400 if (N->getNumValues() == 2) // Dead flag value?
18401 return DCI.CombineTo(N, Cond, SDValue());
18405 // Optimize cases that will turn into an LEA instruction. This requires
18406 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18407 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18408 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18409 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18411 bool isFastMultiplier = false;
18413 switch ((unsigned char)Diff) {
18415 case 1: // result = add base, cond
18416 case 2: // result = lea base( , cond*2)
18417 case 3: // result = lea base(cond, cond*2)
18418 case 4: // result = lea base( , cond*4)
18419 case 5: // result = lea base(cond, cond*4)
18420 case 8: // result = lea base( , cond*8)
18421 case 9: // result = lea base(cond, cond*8)
18422 isFastMultiplier = true;
18427 if (isFastMultiplier) {
18428 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18429 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18430 DAG.getConstant(CC, MVT::i8), Cond);
18431 // Zero extend the condition if needed.
18432 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18434 // Scale the condition by the difference.
18436 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18437 DAG.getConstant(Diff, Cond.getValueType()));
18439 // Add the base if non-zero.
18440 if (FalseC->getAPIntValue() != 0)
18441 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18442 SDValue(FalseC, 0));
18443 if (N->getNumValues() == 2) // Dead flag value?
18444 return DCI.CombineTo(N, Cond, SDValue());
18451 // Handle these cases:
18452 // (select (x != c), e, c) -> select (x != c), e, x),
18453 // (select (x == c), c, e) -> select (x == c), x, e)
18454 // where the c is an integer constant, and the "select" is the combination
18455 // of CMOV and CMP.
18457 // The rationale for this change is that the conditional-move from a constant
18458 // needs two instructions, however, conditional-move from a register needs
18459 // only one instruction.
18461 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
18462 // some instruction-combining opportunities. This opt needs to be
18463 // postponed as late as possible.
18465 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
18466 // the DCI.xxxx conditions are provided to postpone the optimization as
18467 // late as possible.
18469 ConstantSDNode *CmpAgainst = nullptr;
18470 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
18471 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
18472 !isa<ConstantSDNode>(Cond.getOperand(0))) {
18474 if (CC == X86::COND_NE &&
18475 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
18476 CC = X86::GetOppositeBranchCondition(CC);
18477 std::swap(TrueOp, FalseOp);
18480 if (CC == X86::COND_E &&
18481 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
18482 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
18483 DAG.getConstant(CC, MVT::i8), Cond };
18484 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
18492 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG) {
18493 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
18495 default: return SDValue();
18496 // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
18497 case Intrinsic::x86_sse2_psrai_w:
18498 case Intrinsic::x86_sse2_psrai_d:
18499 case Intrinsic::x86_avx2_psrai_w:
18500 case Intrinsic::x86_avx2_psrai_d:
18501 case Intrinsic::x86_sse2_psra_w:
18502 case Intrinsic::x86_sse2_psra_d:
18503 case Intrinsic::x86_avx2_psra_w:
18504 case Intrinsic::x86_avx2_psra_d: {
18505 SDValue Op0 = N->getOperand(1);
18506 SDValue Op1 = N->getOperand(2);
18507 EVT VT = Op0.getValueType();
18508 assert(VT.isVector() && "Expected a vector type!");
18510 if (isa<BuildVectorSDNode>(Op1))
18511 Op1 = Op1.getOperand(0);
18513 if (!isa<ConstantSDNode>(Op1))
18516 EVT SVT = VT.getVectorElementType();
18517 unsigned SVTBits = SVT.getSizeInBits();
18519 ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
18520 const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
18521 uint64_t ShAmt = C.getZExtValue();
18523 // Don't try to convert this shift into a ISD::SRA if the shift
18524 // count is bigger than or equal to the element size.
18525 if (ShAmt >= SVTBits)
18528 // Trivial case: if the shift count is zero, then fold this
18529 // into the first operand.
18533 // Replace this packed shift intrinsic with a target independent
18535 SDValue Splat = DAG.getConstant(C, VT);
18536 return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
18541 /// PerformMulCombine - Optimize a single multiply with constant into two
18542 /// in order to implement it with two cheaper instructions, e.g.
18543 /// LEA + SHL, LEA + LEA.
18544 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
18545 TargetLowering::DAGCombinerInfo &DCI) {
18546 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
18549 EVT VT = N->getValueType(0);
18550 if (VT != MVT::i64)
18553 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
18556 uint64_t MulAmt = C->getZExtValue();
18557 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
18560 uint64_t MulAmt1 = 0;
18561 uint64_t MulAmt2 = 0;
18562 if ((MulAmt % 9) == 0) {
18564 MulAmt2 = MulAmt / 9;
18565 } else if ((MulAmt % 5) == 0) {
18567 MulAmt2 = MulAmt / 5;
18568 } else if ((MulAmt % 3) == 0) {
18570 MulAmt2 = MulAmt / 3;
18573 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
18576 if (isPowerOf2_64(MulAmt2) &&
18577 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
18578 // If second multiplifer is pow2, issue it first. We want the multiply by
18579 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
18581 std::swap(MulAmt1, MulAmt2);
18584 if (isPowerOf2_64(MulAmt1))
18585 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
18586 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
18588 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
18589 DAG.getConstant(MulAmt1, VT));
18591 if (isPowerOf2_64(MulAmt2))
18592 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
18593 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
18595 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
18596 DAG.getConstant(MulAmt2, VT));
18598 // Do not add new nodes to DAG combiner worklist.
18599 DCI.CombineTo(N, NewMul, false);
18604 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
18605 SDValue N0 = N->getOperand(0);
18606 SDValue N1 = N->getOperand(1);
18607 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
18608 EVT VT = N0.getValueType();
18610 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
18611 // since the result of setcc_c is all zero's or all ones.
18612 if (VT.isInteger() && !VT.isVector() &&
18613 N1C && N0.getOpcode() == ISD::AND &&
18614 N0.getOperand(1).getOpcode() == ISD::Constant) {
18615 SDValue N00 = N0.getOperand(0);
18616 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
18617 ((N00.getOpcode() == ISD::ANY_EXTEND ||
18618 N00.getOpcode() == ISD::ZERO_EXTEND) &&
18619 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
18620 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
18621 APInt ShAmt = N1C->getAPIntValue();
18622 Mask = Mask.shl(ShAmt);
18624 return DAG.getNode(ISD::AND, SDLoc(N), VT,
18625 N00, DAG.getConstant(Mask, VT));
18629 // Hardware support for vector shifts is sparse which makes us scalarize the
18630 // vector operations in many cases. Also, on sandybridge ADD is faster than
18632 // (shl V, 1) -> add V,V
18633 if (isSplatVector(N1.getNode())) {
18634 assert(N0.getValueType().isVector() && "Invalid vector shift type");
18635 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
18636 // We shift all of the values by one. In many cases we do not have
18637 // hardware support for this operation. This is better expressed as an ADD
18639 if (N1C && (1 == N1C->getZExtValue())) {
18640 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
18647 /// \brief Returns a vector of 0s if the node in input is a vector logical
18648 /// shift by a constant amount which is known to be bigger than or equal
18649 /// to the vector element size in bits.
18650 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
18651 const X86Subtarget *Subtarget) {
18652 EVT VT = N->getValueType(0);
18654 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
18655 (!Subtarget->hasInt256() ||
18656 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
18659 SDValue Amt = N->getOperand(1);
18661 if (isSplatVector(Amt.getNode())) {
18662 SDValue SclrAmt = Amt->getOperand(0);
18663 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
18664 APInt ShiftAmt = C->getAPIntValue();
18665 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
18667 // SSE2/AVX2 logical shifts always return a vector of 0s
18668 // if the shift amount is bigger than or equal to
18669 // the element size. The constant shift amount will be
18670 // encoded as a 8-bit immediate.
18671 if (ShiftAmt.trunc(8).uge(MaxAmount))
18672 return getZeroVector(VT, Subtarget, DAG, DL);
18679 /// PerformShiftCombine - Combine shifts.
18680 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
18681 TargetLowering::DAGCombinerInfo &DCI,
18682 const X86Subtarget *Subtarget) {
18683 if (N->getOpcode() == ISD::SHL) {
18684 SDValue V = PerformSHLCombine(N, DAG);
18685 if (V.getNode()) return V;
18688 if (N->getOpcode() != ISD::SRA) {
18689 // Try to fold this logical shift into a zero vector.
18690 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
18691 if (V.getNode()) return V;
18697 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
18698 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
18699 // and friends. Likewise for OR -> CMPNEQSS.
18700 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
18701 TargetLowering::DAGCombinerInfo &DCI,
18702 const X86Subtarget *Subtarget) {
18705 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
18706 // we're requiring SSE2 for both.
18707 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
18708 SDValue N0 = N->getOperand(0);
18709 SDValue N1 = N->getOperand(1);
18710 SDValue CMP0 = N0->getOperand(1);
18711 SDValue CMP1 = N1->getOperand(1);
18714 // The SETCCs should both refer to the same CMP.
18715 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
18718 SDValue CMP00 = CMP0->getOperand(0);
18719 SDValue CMP01 = CMP0->getOperand(1);
18720 EVT VT = CMP00.getValueType();
18722 if (VT == MVT::f32 || VT == MVT::f64) {
18723 bool ExpectingFlags = false;
18724 // Check for any users that want flags:
18725 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
18726 !ExpectingFlags && UI != UE; ++UI)
18727 switch (UI->getOpcode()) {
18732 ExpectingFlags = true;
18734 case ISD::CopyToReg:
18735 case ISD::SIGN_EXTEND:
18736 case ISD::ZERO_EXTEND:
18737 case ISD::ANY_EXTEND:
18741 if (!ExpectingFlags) {
18742 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
18743 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
18745 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
18746 X86::CondCode tmp = cc0;
18751 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
18752 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
18753 // FIXME: need symbolic constants for these magic numbers.
18754 // See X86ATTInstPrinter.cpp:printSSECC().
18755 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
18756 if (Subtarget->hasAVX512()) {
18757 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
18758 CMP01, DAG.getConstant(x86cc, MVT::i8));
18759 if (N->getValueType(0) != MVT::i1)
18760 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
18764 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
18765 CMP00.getValueType(), CMP00, CMP01,
18766 DAG.getConstant(x86cc, MVT::i8));
18768 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
18769 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
18771 if (is64BitFP && !Subtarget->is64Bit()) {
18772 // On a 32-bit target, we cannot bitcast the 64-bit float to a
18773 // 64-bit integer, since that's not a legal type. Since
18774 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
18775 // bits, but can do this little dance to extract the lowest 32 bits
18776 // and work with those going forward.
18777 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
18779 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
18781 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
18782 Vector32, DAG.getIntPtrConstant(0));
18786 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
18787 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
18788 DAG.getConstant(1, IntVT));
18789 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
18790 return OneBitOfTruth;
18798 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
18799 /// so it can be folded inside ANDNP.
18800 static bool CanFoldXORWithAllOnes(const SDNode *N) {
18801 EVT VT = N->getValueType(0);
18803 // Match direct AllOnes for 128 and 256-bit vectors
18804 if (ISD::isBuildVectorAllOnes(N))
18807 // Look through a bit convert.
18808 if (N->getOpcode() == ISD::BITCAST)
18809 N = N->getOperand(0).getNode();
18811 // Sometimes the operand may come from a insert_subvector building a 256-bit
18813 if (VT.is256BitVector() &&
18814 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
18815 SDValue V1 = N->getOperand(0);
18816 SDValue V2 = N->getOperand(1);
18818 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
18819 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
18820 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
18821 ISD::isBuildVectorAllOnes(V2.getNode()))
18828 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
18829 // register. In most cases we actually compare or select YMM-sized registers
18830 // and mixing the two types creates horrible code. This method optimizes
18831 // some of the transition sequences.
18832 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
18833 TargetLowering::DAGCombinerInfo &DCI,
18834 const X86Subtarget *Subtarget) {
18835 EVT VT = N->getValueType(0);
18836 if (!VT.is256BitVector())
18839 assert((N->getOpcode() == ISD::ANY_EXTEND ||
18840 N->getOpcode() == ISD::ZERO_EXTEND ||
18841 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
18843 SDValue Narrow = N->getOperand(0);
18844 EVT NarrowVT = Narrow->getValueType(0);
18845 if (!NarrowVT.is128BitVector())
18848 if (Narrow->getOpcode() != ISD::XOR &&
18849 Narrow->getOpcode() != ISD::AND &&
18850 Narrow->getOpcode() != ISD::OR)
18853 SDValue N0 = Narrow->getOperand(0);
18854 SDValue N1 = Narrow->getOperand(1);
18857 // The Left side has to be a trunc.
18858 if (N0.getOpcode() != ISD::TRUNCATE)
18861 // The type of the truncated inputs.
18862 EVT WideVT = N0->getOperand(0)->getValueType(0);
18866 // The right side has to be a 'trunc' or a constant vector.
18867 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
18868 bool RHSConst = (isSplatVector(N1.getNode()) &&
18869 isa<ConstantSDNode>(N1->getOperand(0)));
18870 if (!RHSTrunc && !RHSConst)
18873 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18875 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
18878 // Set N0 and N1 to hold the inputs to the new wide operation.
18879 N0 = N0->getOperand(0);
18881 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
18882 N1->getOperand(0));
18883 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
18884 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
18885 } else if (RHSTrunc) {
18886 N1 = N1->getOperand(0);
18889 // Generate the wide operation.
18890 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
18891 unsigned Opcode = N->getOpcode();
18893 case ISD::ANY_EXTEND:
18895 case ISD::ZERO_EXTEND: {
18896 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
18897 APInt Mask = APInt::getAllOnesValue(InBits);
18898 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
18899 return DAG.getNode(ISD::AND, DL, VT,
18900 Op, DAG.getConstant(Mask, VT));
18902 case ISD::SIGN_EXTEND:
18903 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
18904 Op, DAG.getValueType(NarrowVT));
18906 llvm_unreachable("Unexpected opcode");
18910 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
18911 TargetLowering::DAGCombinerInfo &DCI,
18912 const X86Subtarget *Subtarget) {
18913 EVT VT = N->getValueType(0);
18914 if (DCI.isBeforeLegalizeOps())
18917 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18921 // Create BEXTR instructions
18922 // BEXTR is ((X >> imm) & (2**size-1))
18923 if (VT == MVT::i32 || VT == MVT::i64) {
18924 SDValue N0 = N->getOperand(0);
18925 SDValue N1 = N->getOperand(1);
18928 // Check for BEXTR.
18929 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
18930 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
18931 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
18932 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
18933 if (MaskNode && ShiftNode) {
18934 uint64_t Mask = MaskNode->getZExtValue();
18935 uint64_t Shift = ShiftNode->getZExtValue();
18936 if (isMask_64(Mask)) {
18937 uint64_t MaskSize = CountPopulation_64(Mask);
18938 if (Shift + MaskSize <= VT.getSizeInBits())
18939 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
18940 DAG.getConstant(Shift | (MaskSize << 8), VT));
18948 // Want to form ANDNP nodes:
18949 // 1) In the hopes of then easily combining them with OR and AND nodes
18950 // to form PBLEND/PSIGN.
18951 // 2) To match ANDN packed intrinsics
18952 if (VT != MVT::v2i64 && VT != MVT::v4i64)
18955 SDValue N0 = N->getOperand(0);
18956 SDValue N1 = N->getOperand(1);
18959 // Check LHS for vnot
18960 if (N0.getOpcode() == ISD::XOR &&
18961 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
18962 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
18963 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
18965 // Check RHS for vnot
18966 if (N1.getOpcode() == ISD::XOR &&
18967 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
18968 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
18969 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
18974 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
18975 TargetLowering::DAGCombinerInfo &DCI,
18976 const X86Subtarget *Subtarget) {
18977 if (DCI.isBeforeLegalizeOps())
18980 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18984 SDValue N0 = N->getOperand(0);
18985 SDValue N1 = N->getOperand(1);
18986 EVT VT = N->getValueType(0);
18988 // look for psign/blend
18989 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
18990 if (!Subtarget->hasSSSE3() ||
18991 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
18994 // Canonicalize pandn to RHS
18995 if (N0.getOpcode() == X86ISD::ANDNP)
18997 // or (and (m, y), (pandn m, x))
18998 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
18999 SDValue Mask = N1.getOperand(0);
19000 SDValue X = N1.getOperand(1);
19002 if (N0.getOperand(0) == Mask)
19003 Y = N0.getOperand(1);
19004 if (N0.getOperand(1) == Mask)
19005 Y = N0.getOperand(0);
19007 // Check to see if the mask appeared in both the AND and ANDNP and
19011 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
19012 // Look through mask bitcast.
19013 if (Mask.getOpcode() == ISD::BITCAST)
19014 Mask = Mask.getOperand(0);
19015 if (X.getOpcode() == ISD::BITCAST)
19016 X = X.getOperand(0);
19017 if (Y.getOpcode() == ISD::BITCAST)
19018 Y = Y.getOperand(0);
19020 EVT MaskVT = Mask.getValueType();
19022 // Validate that the Mask operand is a vector sra node.
19023 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
19024 // there is no psrai.b
19025 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
19026 unsigned SraAmt = ~0;
19027 if (Mask.getOpcode() == ISD::SRA) {
19028 SDValue Amt = Mask.getOperand(1);
19029 if (isSplatVector(Amt.getNode())) {
19030 SDValue SclrAmt = Amt->getOperand(0);
19031 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
19032 SraAmt = C->getZExtValue();
19034 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
19035 SDValue SraC = Mask.getOperand(1);
19036 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
19038 if ((SraAmt + 1) != EltBits)
19043 // Now we know we at least have a plendvb with the mask val. See if
19044 // we can form a psignb/w/d.
19045 // psign = x.type == y.type == mask.type && y = sub(0, x);
19046 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
19047 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
19048 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
19049 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
19050 "Unsupported VT for PSIGN");
19051 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
19052 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
19054 // PBLENDVB only available on SSE 4.1
19055 if (!Subtarget->hasSSE41())
19058 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
19060 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
19061 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
19062 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
19063 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
19064 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
19068 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
19071 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
19072 MachineFunction &MF = DAG.getMachineFunction();
19073 bool OptForSize = MF.getFunction()->getAttributes().
19074 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
19076 // SHLD/SHRD instructions have lower register pressure, but on some
19077 // platforms they have higher latency than the equivalent
19078 // series of shifts/or that would otherwise be generated.
19079 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
19080 // have higher latencies and we are not optimizing for size.
19081 if (!OptForSize && Subtarget->isSHLDSlow())
19084 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
19086 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
19088 if (!N0.hasOneUse() || !N1.hasOneUse())
19091 SDValue ShAmt0 = N0.getOperand(1);
19092 if (ShAmt0.getValueType() != MVT::i8)
19094 SDValue ShAmt1 = N1.getOperand(1);
19095 if (ShAmt1.getValueType() != MVT::i8)
19097 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
19098 ShAmt0 = ShAmt0.getOperand(0);
19099 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
19100 ShAmt1 = ShAmt1.getOperand(0);
19103 unsigned Opc = X86ISD::SHLD;
19104 SDValue Op0 = N0.getOperand(0);
19105 SDValue Op1 = N1.getOperand(0);
19106 if (ShAmt0.getOpcode() == ISD::SUB) {
19107 Opc = X86ISD::SHRD;
19108 std::swap(Op0, Op1);
19109 std::swap(ShAmt0, ShAmt1);
19112 unsigned Bits = VT.getSizeInBits();
19113 if (ShAmt1.getOpcode() == ISD::SUB) {
19114 SDValue Sum = ShAmt1.getOperand(0);
19115 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
19116 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
19117 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
19118 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
19119 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
19120 return DAG.getNode(Opc, DL, VT,
19122 DAG.getNode(ISD::TRUNCATE, DL,
19125 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
19126 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
19128 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
19129 return DAG.getNode(Opc, DL, VT,
19130 N0.getOperand(0), N1.getOperand(0),
19131 DAG.getNode(ISD::TRUNCATE, DL,
19138 // Generate NEG and CMOV for integer abs.
19139 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
19140 EVT VT = N->getValueType(0);
19142 // Since X86 does not have CMOV for 8-bit integer, we don't convert
19143 // 8-bit integer abs to NEG and CMOV.
19144 if (VT.isInteger() && VT.getSizeInBits() == 8)
19147 SDValue N0 = N->getOperand(0);
19148 SDValue N1 = N->getOperand(1);
19151 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
19152 // and change it to SUB and CMOV.
19153 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
19154 N0.getOpcode() == ISD::ADD &&
19155 N0.getOperand(1) == N1 &&
19156 N1.getOpcode() == ISD::SRA &&
19157 N1.getOperand(0) == N0.getOperand(0))
19158 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
19159 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
19160 // Generate SUB & CMOV.
19161 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
19162 DAG.getConstant(0, VT), N0.getOperand(0));
19164 SDValue Ops[] = { N0.getOperand(0), Neg,
19165 DAG.getConstant(X86::COND_GE, MVT::i8),
19166 SDValue(Neg.getNode(), 1) };
19167 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
19172 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
19173 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
19174 TargetLowering::DAGCombinerInfo &DCI,
19175 const X86Subtarget *Subtarget) {
19176 if (DCI.isBeforeLegalizeOps())
19179 if (Subtarget->hasCMov()) {
19180 SDValue RV = performIntegerAbsCombine(N, DAG);
19188 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
19189 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
19190 TargetLowering::DAGCombinerInfo &DCI,
19191 const X86Subtarget *Subtarget) {
19192 LoadSDNode *Ld = cast<LoadSDNode>(N);
19193 EVT RegVT = Ld->getValueType(0);
19194 EVT MemVT = Ld->getMemoryVT();
19196 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19197 unsigned RegSz = RegVT.getSizeInBits();
19199 // On Sandybridge unaligned 256bit loads are inefficient.
19200 ISD::LoadExtType Ext = Ld->getExtensionType();
19201 unsigned Alignment = Ld->getAlignment();
19202 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
19203 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
19204 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
19205 unsigned NumElems = RegVT.getVectorNumElements();
19209 SDValue Ptr = Ld->getBasePtr();
19210 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
19212 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19214 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
19215 Ld->getPointerInfo(), Ld->isVolatile(),
19216 Ld->isNonTemporal(), Ld->isInvariant(),
19218 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19219 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
19220 Ld->getPointerInfo(), Ld->isVolatile(),
19221 Ld->isNonTemporal(), Ld->isInvariant(),
19222 std::min(16U, Alignment));
19223 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19225 Load2.getValue(1));
19227 SDValue NewVec = DAG.getUNDEF(RegVT);
19228 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
19229 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
19230 return DCI.CombineTo(N, NewVec, TF, true);
19233 // If this is a vector EXT Load then attempt to optimize it using a
19234 // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
19235 // expansion is still better than scalar code.
19236 // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
19237 // emit a shuffle and a arithmetic shift.
19238 // TODO: It is possible to support ZExt by zeroing the undef values
19239 // during the shuffle phase or after the shuffle.
19240 if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
19241 (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
19242 assert(MemVT != RegVT && "Cannot extend to the same type");
19243 assert(MemVT.isVector() && "Must load a vector from memory");
19245 unsigned NumElems = RegVT.getVectorNumElements();
19246 unsigned MemSz = MemVT.getSizeInBits();
19247 assert(RegSz > MemSz && "Register size must be greater than the mem size");
19249 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
19252 // All sizes must be a power of two.
19253 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
19256 // Attempt to load the original value using scalar loads.
19257 // Find the largest scalar type that divides the total loaded size.
19258 MVT SclrLoadTy = MVT::i8;
19259 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19260 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19261 MVT Tp = (MVT::SimpleValueType)tp;
19262 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
19267 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19268 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
19270 SclrLoadTy = MVT::f64;
19272 // Calculate the number of scalar loads that we need to perform
19273 // in order to load our vector from memory.
19274 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
19275 if (Ext == ISD::SEXTLOAD && NumLoads > 1)
19278 unsigned loadRegZize = RegSz;
19279 if (Ext == ISD::SEXTLOAD && RegSz == 256)
19282 // Represent our vector as a sequence of elements which are the
19283 // largest scalar that we can load.
19284 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
19285 loadRegZize/SclrLoadTy.getSizeInBits());
19287 // Represent the data using the same element type that is stored in
19288 // memory. In practice, we ''widen'' MemVT.
19290 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19291 loadRegZize/MemVT.getScalarType().getSizeInBits());
19293 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
19294 "Invalid vector type");
19296 // We can't shuffle using an illegal type.
19297 if (!TLI.isTypeLegal(WideVecVT))
19300 SmallVector<SDValue, 8> Chains;
19301 SDValue Ptr = Ld->getBasePtr();
19302 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
19303 TLI.getPointerTy());
19304 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
19306 for (unsigned i = 0; i < NumLoads; ++i) {
19307 // Perform a single load.
19308 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
19309 Ptr, Ld->getPointerInfo(),
19310 Ld->isVolatile(), Ld->isNonTemporal(),
19311 Ld->isInvariant(), Ld->getAlignment());
19312 Chains.push_back(ScalarLoad.getValue(1));
19313 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
19314 // another round of DAGCombining.
19316 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
19318 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
19319 ScalarLoad, DAG.getIntPtrConstant(i));
19321 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19324 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19326 // Bitcast the loaded value to a vector of the original element type, in
19327 // the size of the target vector type.
19328 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
19329 unsigned SizeRatio = RegSz/MemSz;
19331 if (Ext == ISD::SEXTLOAD) {
19332 // If we have SSE4.1 we can directly emit a VSEXT node.
19333 if (Subtarget->hasSSE41()) {
19334 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
19335 return DCI.CombineTo(N, Sext, TF, true);
19338 // Otherwise we'll shuffle the small elements in the high bits of the
19339 // larger type and perform an arithmetic shift. If the shift is not legal
19340 // it's better to scalarize.
19341 if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
19344 // Redistribute the loaded elements into the different locations.
19345 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19346 for (unsigned i = 0; i != NumElems; ++i)
19347 ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
19349 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19350 DAG.getUNDEF(WideVecVT),
19353 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19355 // Build the arithmetic shift.
19356 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
19357 MemVT.getVectorElementType().getSizeInBits();
19358 Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
19359 DAG.getConstant(Amt, RegVT));
19361 return DCI.CombineTo(N, Shuff, TF, true);
19364 // Redistribute the loaded elements into the different locations.
19365 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19366 for (unsigned i = 0; i != NumElems; ++i)
19367 ShuffleVec[i*SizeRatio] = i;
19369 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19370 DAG.getUNDEF(WideVecVT),
19373 // Bitcast to the requested type.
19374 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19375 // Replace the original load with the new sequence
19376 // and return the new chain.
19377 return DCI.CombineTo(N, Shuff, TF, true);
19383 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
19384 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
19385 const X86Subtarget *Subtarget) {
19386 StoreSDNode *St = cast<StoreSDNode>(N);
19387 EVT VT = St->getValue().getValueType();
19388 EVT StVT = St->getMemoryVT();
19390 SDValue StoredVal = St->getOperand(1);
19391 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19393 // If we are saving a concatenation of two XMM registers, perform two stores.
19394 // On Sandy Bridge, 256-bit memory operations are executed by two
19395 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
19396 // memory operation.
19397 unsigned Alignment = St->getAlignment();
19398 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
19399 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
19400 StVT == VT && !IsAligned) {
19401 unsigned NumElems = VT.getVectorNumElements();
19405 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
19406 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
19408 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
19409 SDValue Ptr0 = St->getBasePtr();
19410 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
19412 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
19413 St->getPointerInfo(), St->isVolatile(),
19414 St->isNonTemporal(), Alignment);
19415 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
19416 St->getPointerInfo(), St->isVolatile(),
19417 St->isNonTemporal(),
19418 std::min(16U, Alignment));
19419 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
19422 // Optimize trunc store (of multiple scalars) to shuffle and store.
19423 // First, pack all of the elements in one place. Next, store to memory
19424 // in fewer chunks.
19425 if (St->isTruncatingStore() && VT.isVector()) {
19426 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19427 unsigned NumElems = VT.getVectorNumElements();
19428 assert(StVT != VT && "Cannot truncate to the same type");
19429 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
19430 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
19432 // From, To sizes and ElemCount must be pow of two
19433 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
19434 // We are going to use the original vector elt for storing.
19435 // Accumulated smaller vector elements must be a multiple of the store size.
19436 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
19438 unsigned SizeRatio = FromSz / ToSz;
19440 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
19442 // Create a type on which we perform the shuffle
19443 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
19444 StVT.getScalarType(), NumElems*SizeRatio);
19446 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
19448 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
19449 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19450 for (unsigned i = 0; i != NumElems; ++i)
19451 ShuffleVec[i] = i * SizeRatio;
19453 // Can't shuffle using an illegal type.
19454 if (!TLI.isTypeLegal(WideVecVT))
19457 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
19458 DAG.getUNDEF(WideVecVT),
19460 // At this point all of the data is stored at the bottom of the
19461 // register. We now need to save it to mem.
19463 // Find the largest store unit
19464 MVT StoreType = MVT::i8;
19465 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19466 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19467 MVT Tp = (MVT::SimpleValueType)tp;
19468 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
19472 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19473 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
19474 (64 <= NumElems * ToSz))
19475 StoreType = MVT::f64;
19477 // Bitcast the original vector into a vector of store-size units
19478 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
19479 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
19480 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
19481 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
19482 SmallVector<SDValue, 8> Chains;
19483 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
19484 TLI.getPointerTy());
19485 SDValue Ptr = St->getBasePtr();
19487 // Perform one or more big stores into memory.
19488 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
19489 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
19490 StoreType, ShuffWide,
19491 DAG.getIntPtrConstant(i));
19492 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
19493 St->getPointerInfo(), St->isVolatile(),
19494 St->isNonTemporal(), St->getAlignment());
19495 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19496 Chains.push_back(Ch);
19499 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19502 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
19503 // the FP state in cases where an emms may be missing.
19504 // A preferable solution to the general problem is to figure out the right
19505 // places to insert EMMS. This qualifies as a quick hack.
19507 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
19508 if (VT.getSizeInBits() != 64)
19511 const Function *F = DAG.getMachineFunction().getFunction();
19512 bool NoImplicitFloatOps = F->getAttributes().
19513 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
19514 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
19515 && Subtarget->hasSSE2();
19516 if ((VT.isVector() ||
19517 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
19518 isa<LoadSDNode>(St->getValue()) &&
19519 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
19520 St->getChain().hasOneUse() && !St->isVolatile()) {
19521 SDNode* LdVal = St->getValue().getNode();
19522 LoadSDNode *Ld = nullptr;
19523 int TokenFactorIndex = -1;
19524 SmallVector<SDValue, 8> Ops;
19525 SDNode* ChainVal = St->getChain().getNode();
19526 // Must be a store of a load. We currently handle two cases: the load
19527 // is a direct child, and it's under an intervening TokenFactor. It is
19528 // possible to dig deeper under nested TokenFactors.
19529 if (ChainVal == LdVal)
19530 Ld = cast<LoadSDNode>(St->getChain());
19531 else if (St->getValue().hasOneUse() &&
19532 ChainVal->getOpcode() == ISD::TokenFactor) {
19533 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
19534 if (ChainVal->getOperand(i).getNode() == LdVal) {
19535 TokenFactorIndex = i;
19536 Ld = cast<LoadSDNode>(St->getValue());
19538 Ops.push_back(ChainVal->getOperand(i));
19542 if (!Ld || !ISD::isNormalLoad(Ld))
19545 // If this is not the MMX case, i.e. we are just turning i64 load/store
19546 // into f64 load/store, avoid the transformation if there are multiple
19547 // uses of the loaded value.
19548 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
19553 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
19554 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
19556 if (Subtarget->is64Bit() || F64IsLegal) {
19557 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
19558 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
19559 Ld->getPointerInfo(), Ld->isVolatile(),
19560 Ld->isNonTemporal(), Ld->isInvariant(),
19561 Ld->getAlignment());
19562 SDValue NewChain = NewLd.getValue(1);
19563 if (TokenFactorIndex != -1) {
19564 Ops.push_back(NewChain);
19565 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
19567 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
19568 St->getPointerInfo(),
19569 St->isVolatile(), St->isNonTemporal(),
19570 St->getAlignment());
19573 // Otherwise, lower to two pairs of 32-bit loads / stores.
19574 SDValue LoAddr = Ld->getBasePtr();
19575 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
19576 DAG.getConstant(4, MVT::i32));
19578 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
19579 Ld->getPointerInfo(),
19580 Ld->isVolatile(), Ld->isNonTemporal(),
19581 Ld->isInvariant(), Ld->getAlignment());
19582 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
19583 Ld->getPointerInfo().getWithOffset(4),
19584 Ld->isVolatile(), Ld->isNonTemporal(),
19586 MinAlign(Ld->getAlignment(), 4));
19588 SDValue NewChain = LoLd.getValue(1);
19589 if (TokenFactorIndex != -1) {
19590 Ops.push_back(LoLd);
19591 Ops.push_back(HiLd);
19592 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
19595 LoAddr = St->getBasePtr();
19596 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
19597 DAG.getConstant(4, MVT::i32));
19599 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
19600 St->getPointerInfo(),
19601 St->isVolatile(), St->isNonTemporal(),
19602 St->getAlignment());
19603 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
19604 St->getPointerInfo().getWithOffset(4),
19606 St->isNonTemporal(),
19607 MinAlign(St->getAlignment(), 4));
19608 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
19613 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
19614 /// and return the operands for the horizontal operation in LHS and RHS. A
19615 /// horizontal operation performs the binary operation on successive elements
19616 /// of its first operand, then on successive elements of its second operand,
19617 /// returning the resulting values in a vector. For example, if
19618 /// A = < float a0, float a1, float a2, float a3 >
19620 /// B = < float b0, float b1, float b2, float b3 >
19621 /// then the result of doing a horizontal operation on A and B is
19622 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
19623 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
19624 /// A horizontal-op B, for some already available A and B, and if so then LHS is
19625 /// set to A, RHS to B, and the routine returns 'true'.
19626 /// Note that the binary operation should have the property that if one of the
19627 /// operands is UNDEF then the result is UNDEF.
19628 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
19629 // Look for the following pattern: if
19630 // A = < float a0, float a1, float a2, float a3 >
19631 // B = < float b0, float b1, float b2, float b3 >
19633 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
19634 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
19635 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
19636 // which is A horizontal-op B.
19638 // At least one of the operands should be a vector shuffle.
19639 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
19640 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
19643 MVT VT = LHS.getSimpleValueType();
19645 assert((VT.is128BitVector() || VT.is256BitVector()) &&
19646 "Unsupported vector type for horizontal add/sub");
19648 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
19649 // operate independently on 128-bit lanes.
19650 unsigned NumElts = VT.getVectorNumElements();
19651 unsigned NumLanes = VT.getSizeInBits()/128;
19652 unsigned NumLaneElts = NumElts / NumLanes;
19653 assert((NumLaneElts % 2 == 0) &&
19654 "Vector type should have an even number of elements in each lane");
19655 unsigned HalfLaneElts = NumLaneElts/2;
19657 // View LHS in the form
19658 // LHS = VECTOR_SHUFFLE A, B, LMask
19659 // If LHS is not a shuffle then pretend it is the shuffle
19660 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
19661 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
19664 SmallVector<int, 16> LMask(NumElts);
19665 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19666 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
19667 A = LHS.getOperand(0);
19668 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
19669 B = LHS.getOperand(1);
19670 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
19671 std::copy(Mask.begin(), Mask.end(), LMask.begin());
19673 if (LHS.getOpcode() != ISD::UNDEF)
19675 for (unsigned i = 0; i != NumElts; ++i)
19679 // Likewise, view RHS in the form
19680 // RHS = VECTOR_SHUFFLE C, D, RMask
19682 SmallVector<int, 16> RMask(NumElts);
19683 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19684 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
19685 C = RHS.getOperand(0);
19686 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
19687 D = RHS.getOperand(1);
19688 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
19689 std::copy(Mask.begin(), Mask.end(), RMask.begin());
19691 if (RHS.getOpcode() != ISD::UNDEF)
19693 for (unsigned i = 0; i != NumElts; ++i)
19697 // Check that the shuffles are both shuffling the same vectors.
19698 if (!(A == C && B == D) && !(A == D && B == C))
19701 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
19702 if (!A.getNode() && !B.getNode())
19705 // If A and B occur in reverse order in RHS, then "swap" them (which means
19706 // rewriting the mask).
19708 CommuteVectorShuffleMask(RMask, NumElts);
19710 // At this point LHS and RHS are equivalent to
19711 // LHS = VECTOR_SHUFFLE A, B, LMask
19712 // RHS = VECTOR_SHUFFLE A, B, RMask
19713 // Check that the masks correspond to performing a horizontal operation.
19714 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
19715 for (unsigned i = 0; i != NumLaneElts; ++i) {
19716 int LIdx = LMask[i+l], RIdx = RMask[i+l];
19718 // Ignore any UNDEF components.
19719 if (LIdx < 0 || RIdx < 0 ||
19720 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
19721 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
19724 // Check that successive elements are being operated on. If not, this is
19725 // not a horizontal operation.
19726 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
19727 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
19728 if (!(LIdx == Index && RIdx == Index + 1) &&
19729 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
19734 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
19735 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
19739 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
19740 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
19741 const X86Subtarget *Subtarget) {
19742 EVT VT = N->getValueType(0);
19743 SDValue LHS = N->getOperand(0);
19744 SDValue RHS = N->getOperand(1);
19746 // Try to synthesize horizontal adds from adds of shuffles.
19747 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19748 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19749 isHorizontalBinOp(LHS, RHS, true))
19750 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
19754 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
19755 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
19756 const X86Subtarget *Subtarget) {
19757 EVT VT = N->getValueType(0);
19758 SDValue LHS = N->getOperand(0);
19759 SDValue RHS = N->getOperand(1);
19761 // Try to synthesize horizontal subs from subs of shuffles.
19762 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19763 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19764 isHorizontalBinOp(LHS, RHS, false))
19765 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
19769 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
19770 /// X86ISD::FXOR nodes.
19771 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
19772 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
19773 // F[X]OR(0.0, x) -> x
19774 // F[X]OR(x, 0.0) -> x
19775 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19776 if (C->getValueAPF().isPosZero())
19777 return N->getOperand(1);
19778 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19779 if (C->getValueAPF().isPosZero())
19780 return N->getOperand(0);
19784 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
19785 /// X86ISD::FMAX nodes.
19786 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
19787 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
19789 // Only perform optimizations if UnsafeMath is used.
19790 if (!DAG.getTarget().Options.UnsafeFPMath)
19793 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
19794 // into FMINC and FMAXC, which are Commutative operations.
19795 unsigned NewOp = 0;
19796 switch (N->getOpcode()) {
19797 default: llvm_unreachable("unknown opcode");
19798 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
19799 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
19802 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
19803 N->getOperand(0), N->getOperand(1));
19806 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
19807 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
19808 // FAND(0.0, x) -> 0.0
19809 // FAND(x, 0.0) -> 0.0
19810 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19811 if (C->getValueAPF().isPosZero())
19812 return N->getOperand(0);
19813 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19814 if (C->getValueAPF().isPosZero())
19815 return N->getOperand(1);
19819 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
19820 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
19821 // FANDN(x, 0.0) -> 0.0
19822 // FANDN(0.0, x) -> x
19823 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19824 if (C->getValueAPF().isPosZero())
19825 return N->getOperand(1);
19826 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19827 if (C->getValueAPF().isPosZero())
19828 return N->getOperand(1);
19832 static SDValue PerformBTCombine(SDNode *N,
19834 TargetLowering::DAGCombinerInfo &DCI) {
19835 // BT ignores high bits in the bit index operand.
19836 SDValue Op1 = N->getOperand(1);
19837 if (Op1.hasOneUse()) {
19838 unsigned BitWidth = Op1.getValueSizeInBits();
19839 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
19840 APInt KnownZero, KnownOne;
19841 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
19842 !DCI.isBeforeLegalizeOps());
19843 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19844 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
19845 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
19846 DCI.CommitTargetLoweringOpt(TLO);
19851 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
19852 SDValue Op = N->getOperand(0);
19853 if (Op.getOpcode() == ISD::BITCAST)
19854 Op = Op.getOperand(0);
19855 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
19856 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
19857 VT.getVectorElementType().getSizeInBits() ==
19858 OpVT.getVectorElementType().getSizeInBits()) {
19859 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
19864 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
19865 const X86Subtarget *Subtarget) {
19866 EVT VT = N->getValueType(0);
19867 if (!VT.isVector())
19870 SDValue N0 = N->getOperand(0);
19871 SDValue N1 = N->getOperand(1);
19872 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
19875 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
19876 // both SSE and AVX2 since there is no sign-extended shift right
19877 // operation on a vector with 64-bit elements.
19878 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
19879 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
19880 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
19881 N0.getOpcode() == ISD::SIGN_EXTEND)) {
19882 SDValue N00 = N0.getOperand(0);
19884 // EXTLOAD has a better solution on AVX2,
19885 // it may be replaced with X86ISD::VSEXT node.
19886 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
19887 if (!ISD::isNormalLoad(N00.getNode()))
19890 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
19891 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
19893 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
19899 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
19900 TargetLowering::DAGCombinerInfo &DCI,
19901 const X86Subtarget *Subtarget) {
19902 if (!DCI.isBeforeLegalizeOps())
19905 if (!Subtarget->hasFp256())
19908 EVT VT = N->getValueType(0);
19909 if (VT.isVector() && VT.getSizeInBits() == 256) {
19910 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19918 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
19919 const X86Subtarget* Subtarget) {
19921 EVT VT = N->getValueType(0);
19923 // Let legalize expand this if it isn't a legal type yet.
19924 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19927 EVT ScalarVT = VT.getScalarType();
19928 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
19929 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
19932 SDValue A = N->getOperand(0);
19933 SDValue B = N->getOperand(1);
19934 SDValue C = N->getOperand(2);
19936 bool NegA = (A.getOpcode() == ISD::FNEG);
19937 bool NegB = (B.getOpcode() == ISD::FNEG);
19938 bool NegC = (C.getOpcode() == ISD::FNEG);
19940 // Negative multiplication when NegA xor NegB
19941 bool NegMul = (NegA != NegB);
19943 A = A.getOperand(0);
19945 B = B.getOperand(0);
19947 C = C.getOperand(0);
19951 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
19953 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
19955 return DAG.getNode(Opcode, dl, VT, A, B, C);
19958 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
19959 TargetLowering::DAGCombinerInfo &DCI,
19960 const X86Subtarget *Subtarget) {
19961 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
19962 // (and (i32 x86isd::setcc_carry), 1)
19963 // This eliminates the zext. This transformation is necessary because
19964 // ISD::SETCC is always legalized to i8.
19966 SDValue N0 = N->getOperand(0);
19967 EVT VT = N->getValueType(0);
19969 if (N0.getOpcode() == ISD::AND &&
19971 N0.getOperand(0).hasOneUse()) {
19972 SDValue N00 = N0.getOperand(0);
19973 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19974 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19975 if (!C || C->getZExtValue() != 1)
19977 return DAG.getNode(ISD::AND, dl, VT,
19978 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19979 N00.getOperand(0), N00.getOperand(1)),
19980 DAG.getConstant(1, VT));
19984 if (N0.getOpcode() == ISD::TRUNCATE &&
19986 N0.getOperand(0).hasOneUse()) {
19987 SDValue N00 = N0.getOperand(0);
19988 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19989 return DAG.getNode(ISD::AND, dl, VT,
19990 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19991 N00.getOperand(0), N00.getOperand(1)),
19992 DAG.getConstant(1, VT));
19995 if (VT.is256BitVector()) {
19996 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
20004 // Optimize x == -y --> x+y == 0
20005 // x != -y --> x+y != 0
20006 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
20007 const X86Subtarget* Subtarget) {
20008 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
20009 SDValue LHS = N->getOperand(0);
20010 SDValue RHS = N->getOperand(1);
20011 EVT VT = N->getValueType(0);
20014 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
20015 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
20016 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
20017 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
20018 LHS.getValueType(), RHS, LHS.getOperand(1));
20019 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
20020 addV, DAG.getConstant(0, addV.getValueType()), CC);
20022 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
20023 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
20024 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
20025 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
20026 RHS.getValueType(), LHS, RHS.getOperand(1));
20027 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
20028 addV, DAG.getConstant(0, addV.getValueType()), CC);
20031 if (VT.getScalarType() == MVT::i1) {
20032 bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
20033 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
20034 bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
20035 if (!IsSEXT0 && !IsVZero0)
20037 bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
20038 (RHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
20039 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
20041 if (!IsSEXT1 && !IsVZero1)
20044 if (IsSEXT0 && IsVZero1) {
20045 assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
20046 if (CC == ISD::SETEQ)
20047 return DAG.getNOT(DL, LHS.getOperand(0), VT);
20048 return LHS.getOperand(0);
20050 if (IsSEXT1 && IsVZero0) {
20051 assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
20052 if (CC == ISD::SETEQ)
20053 return DAG.getNOT(DL, RHS.getOperand(0), VT);
20054 return RHS.getOperand(0);
20061 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
20062 // as "sbb reg,reg", since it can be extended without zext and produces
20063 // an all-ones bit which is more useful than 0/1 in some cases.
20064 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
20067 return DAG.getNode(ISD::AND, DL, VT,
20068 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
20069 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
20070 DAG.getConstant(1, VT));
20071 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
20072 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
20073 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
20074 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
20077 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
20078 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
20079 TargetLowering::DAGCombinerInfo &DCI,
20080 const X86Subtarget *Subtarget) {
20082 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
20083 SDValue EFLAGS = N->getOperand(1);
20085 if (CC == X86::COND_A) {
20086 // Try to convert COND_A into COND_B in an attempt to facilitate
20087 // materializing "setb reg".
20089 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
20090 // cannot take an immediate as its first operand.
20092 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
20093 EFLAGS.getValueType().isInteger() &&
20094 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
20095 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
20096 EFLAGS.getNode()->getVTList(),
20097 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
20098 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
20099 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
20103 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
20104 // a zext and produces an all-ones bit which is more useful than 0/1 in some
20106 if (CC == X86::COND_B)
20107 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
20111 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
20112 if (Flags.getNode()) {
20113 SDValue Cond = DAG.getConstant(CC, MVT::i8);
20114 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
20120 // Optimize branch condition evaluation.
20122 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
20123 TargetLowering::DAGCombinerInfo &DCI,
20124 const X86Subtarget *Subtarget) {
20126 SDValue Chain = N->getOperand(0);
20127 SDValue Dest = N->getOperand(1);
20128 SDValue EFLAGS = N->getOperand(3);
20129 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
20133 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
20134 if (Flags.getNode()) {
20135 SDValue Cond = DAG.getConstant(CC, MVT::i8);
20136 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
20143 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
20144 const X86TargetLowering *XTLI) {
20145 SDValue Op0 = N->getOperand(0);
20146 EVT InVT = Op0->getValueType(0);
20148 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
20149 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
20151 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
20152 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
20153 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
20156 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
20157 // a 32-bit target where SSE doesn't support i64->FP operations.
20158 if (Op0.getOpcode() == ISD::LOAD) {
20159 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
20160 EVT VT = Ld->getValueType(0);
20161 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
20162 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
20163 !XTLI->getSubtarget()->is64Bit() &&
20165 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
20166 Ld->getChain(), Op0, DAG);
20167 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
20174 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
20175 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
20176 X86TargetLowering::DAGCombinerInfo &DCI) {
20177 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
20178 // the result is either zero or one (depending on the input carry bit).
20179 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
20180 if (X86::isZeroNode(N->getOperand(0)) &&
20181 X86::isZeroNode(N->getOperand(1)) &&
20182 // We don't have a good way to replace an EFLAGS use, so only do this when
20184 SDValue(N, 1).use_empty()) {
20186 EVT VT = N->getValueType(0);
20187 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
20188 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
20189 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
20190 DAG.getConstant(X86::COND_B,MVT::i8),
20192 DAG.getConstant(1, VT));
20193 return DCI.CombineTo(N, Res1, CarryOut);
20199 // fold (add Y, (sete X, 0)) -> adc 0, Y
20200 // (add Y, (setne X, 0)) -> sbb -1, Y
20201 // (sub (sete X, 0), Y) -> sbb 0, Y
20202 // (sub (setne X, 0), Y) -> adc -1, Y
20203 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
20206 // Look through ZExts.
20207 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
20208 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
20211 SDValue SetCC = Ext.getOperand(0);
20212 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
20215 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
20216 if (CC != X86::COND_E && CC != X86::COND_NE)
20219 SDValue Cmp = SetCC.getOperand(1);
20220 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
20221 !X86::isZeroNode(Cmp.getOperand(1)) ||
20222 !Cmp.getOperand(0).getValueType().isInteger())
20225 SDValue CmpOp0 = Cmp.getOperand(0);
20226 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
20227 DAG.getConstant(1, CmpOp0.getValueType()));
20229 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
20230 if (CC == X86::COND_NE)
20231 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
20232 DL, OtherVal.getValueType(), OtherVal,
20233 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
20234 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
20235 DL, OtherVal.getValueType(), OtherVal,
20236 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
20239 /// PerformADDCombine - Do target-specific dag combines on integer adds.
20240 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
20241 const X86Subtarget *Subtarget) {
20242 EVT VT = N->getValueType(0);
20243 SDValue Op0 = N->getOperand(0);
20244 SDValue Op1 = N->getOperand(1);
20246 // Try to synthesize horizontal adds from adds of shuffles.
20247 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20248 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20249 isHorizontalBinOp(Op0, Op1, true))
20250 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
20252 return OptimizeConditionalInDecrement(N, DAG);
20255 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
20256 const X86Subtarget *Subtarget) {
20257 SDValue Op0 = N->getOperand(0);
20258 SDValue Op1 = N->getOperand(1);
20260 // X86 can't encode an immediate LHS of a sub. See if we can push the
20261 // negation into a preceding instruction.
20262 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
20263 // If the RHS of the sub is a XOR with one use and a constant, invert the
20264 // immediate. Then add one to the LHS of the sub so we can turn
20265 // X-Y -> X+~Y+1, saving one register.
20266 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
20267 isa<ConstantSDNode>(Op1.getOperand(1))) {
20268 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
20269 EVT VT = Op0.getValueType();
20270 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
20272 DAG.getConstant(~XorC, VT));
20273 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
20274 DAG.getConstant(C->getAPIntValue()+1, VT));
20278 // Try to synthesize horizontal adds from adds of shuffles.
20279 EVT VT = N->getValueType(0);
20280 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20281 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20282 isHorizontalBinOp(Op0, Op1, true))
20283 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
20285 return OptimizeConditionalInDecrement(N, DAG);
20288 /// performVZEXTCombine - Performs build vector combines
20289 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
20290 TargetLowering::DAGCombinerInfo &DCI,
20291 const X86Subtarget *Subtarget) {
20292 // (vzext (bitcast (vzext (x)) -> (vzext x)
20293 SDValue In = N->getOperand(0);
20294 while (In.getOpcode() == ISD::BITCAST)
20295 In = In.getOperand(0);
20297 if (In.getOpcode() != X86ISD::VZEXT)
20300 return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
20304 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
20305 DAGCombinerInfo &DCI) const {
20306 SelectionDAG &DAG = DCI.DAG;
20307 switch (N->getOpcode()) {
20309 case ISD::EXTRACT_VECTOR_ELT:
20310 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
20312 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
20313 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
20314 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
20315 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
20316 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
20317 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
20320 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
20321 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
20322 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
20323 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
20324 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
20325 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
20326 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
20327 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
20328 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
20330 case X86ISD::FOR: return PerformFORCombine(N, DAG);
20332 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
20333 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
20334 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
20335 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
20336 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
20337 case ISD::ANY_EXTEND:
20338 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
20339 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
20340 case ISD::SIGN_EXTEND_INREG:
20341 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
20342 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
20343 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
20344 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
20345 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
20346 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
20347 case X86ISD::SHUFP: // Handle all target specific shuffles
20348 case X86ISD::PALIGNR:
20349 case X86ISD::UNPCKH:
20350 case X86ISD::UNPCKL:
20351 case X86ISD::MOVHLPS:
20352 case X86ISD::MOVLHPS:
20353 case X86ISD::PSHUFD:
20354 case X86ISD::PSHUFHW:
20355 case X86ISD::PSHUFLW:
20356 case X86ISD::MOVSS:
20357 case X86ISD::MOVSD:
20358 case X86ISD::VPERMILP:
20359 case X86ISD::VPERM2X128:
20360 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
20361 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
20362 case ISD::INTRINSIC_WO_CHAIN: return PerformINTRINSIC_WO_CHAINCombine(N, DAG);
20368 /// isTypeDesirableForOp - Return true if the target has native support for
20369 /// the specified value type and it is 'desirable' to use the type for the
20370 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
20371 /// instruction encodings are longer and some i16 instructions are slow.
20372 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
20373 if (!isTypeLegal(VT))
20375 if (VT != MVT::i16)
20382 case ISD::SIGN_EXTEND:
20383 case ISD::ZERO_EXTEND:
20384 case ISD::ANY_EXTEND:
20397 /// IsDesirableToPromoteOp - This method query the target whether it is
20398 /// beneficial for dag combiner to promote the specified node. If true, it
20399 /// should return the desired promotion type by reference.
20400 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
20401 EVT VT = Op.getValueType();
20402 if (VT != MVT::i16)
20405 bool Promote = false;
20406 bool Commute = false;
20407 switch (Op.getOpcode()) {
20410 LoadSDNode *LD = cast<LoadSDNode>(Op);
20411 // If the non-extending load has a single use and it's not live out, then it
20412 // might be folded.
20413 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
20414 Op.hasOneUse()*/) {
20415 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
20416 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
20417 // The only case where we'd want to promote LOAD (rather then it being
20418 // promoted as an operand is when it's only use is liveout.
20419 if (UI->getOpcode() != ISD::CopyToReg)
20426 case ISD::SIGN_EXTEND:
20427 case ISD::ZERO_EXTEND:
20428 case ISD::ANY_EXTEND:
20433 SDValue N0 = Op.getOperand(0);
20434 // Look out for (store (shl (load), x)).
20435 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
20448 SDValue N0 = Op.getOperand(0);
20449 SDValue N1 = Op.getOperand(1);
20450 if (!Commute && MayFoldLoad(N1))
20452 // Avoid disabling potential load folding opportunities.
20453 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
20455 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
20465 //===----------------------------------------------------------------------===//
20466 // X86 Inline Assembly Support
20467 //===----------------------------------------------------------------------===//
20470 // Helper to match a string separated by whitespace.
20471 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
20472 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
20474 for (unsigned i = 0, e = args.size(); i != e; ++i) {
20475 StringRef piece(*args[i]);
20476 if (!s.startswith(piece)) // Check if the piece matches.
20479 s = s.substr(piece.size());
20480 StringRef::size_type pos = s.find_first_not_of(" \t");
20481 if (pos == 0) // We matched a prefix.
20489 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
20492 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
20494 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
20495 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
20496 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
20497 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
20499 if (AsmPieces.size() == 3)
20501 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
20508 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
20509 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
20511 std::string AsmStr = IA->getAsmString();
20513 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
20514 if (!Ty || Ty->getBitWidth() % 16 != 0)
20517 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
20518 SmallVector<StringRef, 4> AsmPieces;
20519 SplitString(AsmStr, AsmPieces, ";\n");
20521 switch (AsmPieces.size()) {
20522 default: return false;
20524 // FIXME: this should verify that we are targeting a 486 or better. If not,
20525 // we will turn this bswap into something that will be lowered to logical
20526 // ops instead of emitting the bswap asm. For now, we don't support 486 or
20527 // lower so don't worry about this.
20529 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
20530 matchAsm(AsmPieces[0], "bswapl", "$0") ||
20531 matchAsm(AsmPieces[0], "bswapq", "$0") ||
20532 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
20533 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
20534 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
20535 // No need to check constraints, nothing other than the equivalent of
20536 // "=r,0" would be valid here.
20537 return IntrinsicLowering::LowerToByteSwap(CI);
20540 // rorw $$8, ${0:w} --> llvm.bswap.i16
20541 if (CI->getType()->isIntegerTy(16) &&
20542 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20543 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
20544 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
20546 const std::string &ConstraintsStr = IA->getConstraintString();
20547 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20548 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20549 if (clobbersFlagRegisters(AsmPieces))
20550 return IntrinsicLowering::LowerToByteSwap(CI);
20554 if (CI->getType()->isIntegerTy(32) &&
20555 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20556 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
20557 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
20558 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
20560 const std::string &ConstraintsStr = IA->getConstraintString();
20561 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20562 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20563 if (clobbersFlagRegisters(AsmPieces))
20564 return IntrinsicLowering::LowerToByteSwap(CI);
20567 if (CI->getType()->isIntegerTy(64)) {
20568 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
20569 if (Constraints.size() >= 2 &&
20570 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
20571 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
20572 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
20573 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
20574 matchAsm(AsmPieces[1], "bswap", "%edx") &&
20575 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
20576 return IntrinsicLowering::LowerToByteSwap(CI);
20584 /// getConstraintType - Given a constraint letter, return the type of
20585 /// constraint it is for this target.
20586 X86TargetLowering::ConstraintType
20587 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
20588 if (Constraint.size() == 1) {
20589 switch (Constraint[0]) {
20600 return C_RegisterClass;
20624 return TargetLowering::getConstraintType(Constraint);
20627 /// Examine constraint type and operand type and determine a weight value.
20628 /// This object must already have been set up with the operand type
20629 /// and the current alternative constraint selected.
20630 TargetLowering::ConstraintWeight
20631 X86TargetLowering::getSingleConstraintMatchWeight(
20632 AsmOperandInfo &info, const char *constraint) const {
20633 ConstraintWeight weight = CW_Invalid;
20634 Value *CallOperandVal = info.CallOperandVal;
20635 // If we don't have a value, we can't do a match,
20636 // but allow it at the lowest weight.
20637 if (!CallOperandVal)
20639 Type *type = CallOperandVal->getType();
20640 // Look at the constraint type.
20641 switch (*constraint) {
20643 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
20654 if (CallOperandVal->getType()->isIntegerTy())
20655 weight = CW_SpecificReg;
20660 if (type->isFloatingPointTy())
20661 weight = CW_SpecificReg;
20664 if (type->isX86_MMXTy() && Subtarget->hasMMX())
20665 weight = CW_SpecificReg;
20669 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
20670 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
20671 weight = CW_Register;
20674 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
20675 if (C->getZExtValue() <= 31)
20676 weight = CW_Constant;
20680 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20681 if (C->getZExtValue() <= 63)
20682 weight = CW_Constant;
20686 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20687 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
20688 weight = CW_Constant;
20692 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20693 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
20694 weight = CW_Constant;
20698 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20699 if (C->getZExtValue() <= 3)
20700 weight = CW_Constant;
20704 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20705 if (C->getZExtValue() <= 0xff)
20706 weight = CW_Constant;
20711 if (dyn_cast<ConstantFP>(CallOperandVal)) {
20712 weight = CW_Constant;
20716 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20717 if ((C->getSExtValue() >= -0x80000000LL) &&
20718 (C->getSExtValue() <= 0x7fffffffLL))
20719 weight = CW_Constant;
20723 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20724 if (C->getZExtValue() <= 0xffffffff)
20725 weight = CW_Constant;
20732 /// LowerXConstraint - try to replace an X constraint, which matches anything,
20733 /// with another that has more specific requirements based on the type of the
20734 /// corresponding operand.
20735 const char *X86TargetLowering::
20736 LowerXConstraint(EVT ConstraintVT) const {
20737 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
20738 // 'f' like normal targets.
20739 if (ConstraintVT.isFloatingPoint()) {
20740 if (Subtarget->hasSSE2())
20742 if (Subtarget->hasSSE1())
20746 return TargetLowering::LowerXConstraint(ConstraintVT);
20749 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
20750 /// vector. If it is invalid, don't add anything to Ops.
20751 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
20752 std::string &Constraint,
20753 std::vector<SDValue>&Ops,
20754 SelectionDAG &DAG) const {
20757 // Only support length 1 constraints for now.
20758 if (Constraint.length() > 1) return;
20760 char ConstraintLetter = Constraint[0];
20761 switch (ConstraintLetter) {
20764 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20765 if (C->getZExtValue() <= 31) {
20766 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20772 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20773 if (C->getZExtValue() <= 63) {
20774 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20780 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20781 if (isInt<8>(C->getSExtValue())) {
20782 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20788 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20789 if (C->getZExtValue() <= 255) {
20790 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20796 // 32-bit signed value
20797 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20798 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20799 C->getSExtValue())) {
20800 // Widen to 64 bits here to get it sign extended.
20801 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
20804 // FIXME gcc accepts some relocatable values here too, but only in certain
20805 // memory models; it's complicated.
20810 // 32-bit unsigned value
20811 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20812 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20813 C->getZExtValue())) {
20814 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20818 // FIXME gcc accepts some relocatable values here too, but only in certain
20819 // memory models; it's complicated.
20823 // Literal immediates are always ok.
20824 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
20825 // Widen to 64 bits here to get it sign extended.
20826 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
20830 // In any sort of PIC mode addresses need to be computed at runtime by
20831 // adding in a register or some sort of table lookup. These can't
20832 // be used as immediates.
20833 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
20836 // If we are in non-pic codegen mode, we allow the address of a global (with
20837 // an optional displacement) to be used with 'i'.
20838 GlobalAddressSDNode *GA = nullptr;
20839 int64_t Offset = 0;
20841 // Match either (GA), (GA+C), (GA+C1+C2), etc.
20843 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
20844 Offset += GA->getOffset();
20846 } else if (Op.getOpcode() == ISD::ADD) {
20847 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20848 Offset += C->getZExtValue();
20849 Op = Op.getOperand(0);
20852 } else if (Op.getOpcode() == ISD::SUB) {
20853 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20854 Offset += -C->getZExtValue();
20855 Op = Op.getOperand(0);
20860 // Otherwise, this isn't something we can handle, reject it.
20864 const GlobalValue *GV = GA->getGlobal();
20865 // If we require an extra load to get this address, as in PIC mode, we
20866 // can't accept it.
20867 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
20868 getTargetMachine())))
20871 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
20872 GA->getValueType(0), Offset);
20877 if (Result.getNode()) {
20878 Ops.push_back(Result);
20881 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
20884 std::pair<unsigned, const TargetRegisterClass*>
20885 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
20887 // First, see if this is a constraint that directly corresponds to an LLVM
20889 if (Constraint.size() == 1) {
20890 // GCC Constraint Letters
20891 switch (Constraint[0]) {
20893 // TODO: Slight differences here in allocation order and leaving
20894 // RIP in the class. Do they matter any more here than they do
20895 // in the normal allocation?
20896 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
20897 if (Subtarget->is64Bit()) {
20898 if (VT == MVT::i32 || VT == MVT::f32)
20899 return std::make_pair(0U, &X86::GR32RegClass);
20900 if (VT == MVT::i16)
20901 return std::make_pair(0U, &X86::GR16RegClass);
20902 if (VT == MVT::i8 || VT == MVT::i1)
20903 return std::make_pair(0U, &X86::GR8RegClass);
20904 if (VT == MVT::i64 || VT == MVT::f64)
20905 return std::make_pair(0U, &X86::GR64RegClass);
20908 // 32-bit fallthrough
20909 case 'Q': // Q_REGS
20910 if (VT == MVT::i32 || VT == MVT::f32)
20911 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
20912 if (VT == MVT::i16)
20913 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
20914 if (VT == MVT::i8 || VT == MVT::i1)
20915 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
20916 if (VT == MVT::i64)
20917 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
20919 case 'r': // GENERAL_REGS
20920 case 'l': // INDEX_REGS
20921 if (VT == MVT::i8 || VT == MVT::i1)
20922 return std::make_pair(0U, &X86::GR8RegClass);
20923 if (VT == MVT::i16)
20924 return std::make_pair(0U, &X86::GR16RegClass);
20925 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
20926 return std::make_pair(0U, &X86::GR32RegClass);
20927 return std::make_pair(0U, &X86::GR64RegClass);
20928 case 'R': // LEGACY_REGS
20929 if (VT == MVT::i8 || VT == MVT::i1)
20930 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
20931 if (VT == MVT::i16)
20932 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
20933 if (VT == MVT::i32 || !Subtarget->is64Bit())
20934 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
20935 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
20936 case 'f': // FP Stack registers.
20937 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
20938 // value to the correct fpstack register class.
20939 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
20940 return std::make_pair(0U, &X86::RFP32RegClass);
20941 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
20942 return std::make_pair(0U, &X86::RFP64RegClass);
20943 return std::make_pair(0U, &X86::RFP80RegClass);
20944 case 'y': // MMX_REGS if MMX allowed.
20945 if (!Subtarget->hasMMX()) break;
20946 return std::make_pair(0U, &X86::VR64RegClass);
20947 case 'Y': // SSE_REGS if SSE2 allowed
20948 if (!Subtarget->hasSSE2()) break;
20950 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
20951 if (!Subtarget->hasSSE1()) break;
20953 switch (VT.SimpleTy) {
20955 // Scalar SSE types.
20958 return std::make_pair(0U, &X86::FR32RegClass);
20961 return std::make_pair(0U, &X86::FR64RegClass);
20969 return std::make_pair(0U, &X86::VR128RegClass);
20977 return std::make_pair(0U, &X86::VR256RegClass);
20982 return std::make_pair(0U, &X86::VR512RegClass);
20988 // Use the default implementation in TargetLowering to convert the register
20989 // constraint into a member of a register class.
20990 std::pair<unsigned, const TargetRegisterClass*> Res;
20991 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
20993 // Not found as a standard register?
20995 // Map st(0) -> st(7) -> ST0
20996 if (Constraint.size() == 7 && Constraint[0] == '{' &&
20997 tolower(Constraint[1]) == 's' &&
20998 tolower(Constraint[2]) == 't' &&
20999 Constraint[3] == '(' &&
21000 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
21001 Constraint[5] == ')' &&
21002 Constraint[6] == '}') {
21004 Res.first = X86::ST0+Constraint[4]-'0';
21005 Res.second = &X86::RFP80RegClass;
21009 // GCC allows "st(0)" to be called just plain "st".
21010 if (StringRef("{st}").equals_lower(Constraint)) {
21011 Res.first = X86::ST0;
21012 Res.second = &X86::RFP80RegClass;
21017 if (StringRef("{flags}").equals_lower(Constraint)) {
21018 Res.first = X86::EFLAGS;
21019 Res.second = &X86::CCRRegClass;
21023 // 'A' means EAX + EDX.
21024 if (Constraint == "A") {
21025 Res.first = X86::EAX;
21026 Res.second = &X86::GR32_ADRegClass;
21032 // Otherwise, check to see if this is a register class of the wrong value
21033 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
21034 // turn into {ax},{dx}.
21035 if (Res.second->hasType(VT))
21036 return Res; // Correct type already, nothing to do.
21038 // All of the single-register GCC register classes map their values onto
21039 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
21040 // really want an 8-bit or 32-bit register, map to the appropriate register
21041 // class and return the appropriate register.
21042 if (Res.second == &X86::GR16RegClass) {
21043 if (VT == MVT::i8 || VT == MVT::i1) {
21044 unsigned DestReg = 0;
21045 switch (Res.first) {
21047 case X86::AX: DestReg = X86::AL; break;
21048 case X86::DX: DestReg = X86::DL; break;
21049 case X86::CX: DestReg = X86::CL; break;
21050 case X86::BX: DestReg = X86::BL; break;
21053 Res.first = DestReg;
21054 Res.second = &X86::GR8RegClass;
21056 } else if (VT == MVT::i32 || VT == MVT::f32) {
21057 unsigned DestReg = 0;
21058 switch (Res.first) {
21060 case X86::AX: DestReg = X86::EAX; break;
21061 case X86::DX: DestReg = X86::EDX; break;
21062 case X86::CX: DestReg = X86::ECX; break;
21063 case X86::BX: DestReg = X86::EBX; break;
21064 case X86::SI: DestReg = X86::ESI; break;
21065 case X86::DI: DestReg = X86::EDI; break;
21066 case X86::BP: DestReg = X86::EBP; break;
21067 case X86::SP: DestReg = X86::ESP; break;
21070 Res.first = DestReg;
21071 Res.second = &X86::GR32RegClass;
21073 } else if (VT == MVT::i64 || VT == MVT::f64) {
21074 unsigned DestReg = 0;
21075 switch (Res.first) {
21077 case X86::AX: DestReg = X86::RAX; break;
21078 case X86::DX: DestReg = X86::RDX; break;
21079 case X86::CX: DestReg = X86::RCX; break;
21080 case X86::BX: DestReg = X86::RBX; break;
21081 case X86::SI: DestReg = X86::RSI; break;
21082 case X86::DI: DestReg = X86::RDI; break;
21083 case X86::BP: DestReg = X86::RBP; break;
21084 case X86::SP: DestReg = X86::RSP; break;
21087 Res.first = DestReg;
21088 Res.second = &X86::GR64RegClass;
21091 } else if (Res.second == &X86::FR32RegClass ||
21092 Res.second == &X86::FR64RegClass ||
21093 Res.second == &X86::VR128RegClass ||
21094 Res.second == &X86::VR256RegClass ||
21095 Res.second == &X86::FR32XRegClass ||
21096 Res.second == &X86::FR64XRegClass ||
21097 Res.second == &X86::VR128XRegClass ||
21098 Res.second == &X86::VR256XRegClass ||
21099 Res.second == &X86::VR512RegClass) {
21100 // Handle references to XMM physical registers that got mapped into the
21101 // wrong class. This can happen with constraints like {xmm0} where the
21102 // target independent register mapper will just pick the first match it can
21103 // find, ignoring the required type.
21105 if (VT == MVT::f32 || VT == MVT::i32)
21106 Res.second = &X86::FR32RegClass;
21107 else if (VT == MVT::f64 || VT == MVT::i64)
21108 Res.second = &X86::FR64RegClass;
21109 else if (X86::VR128RegClass.hasType(VT))
21110 Res.second = &X86::VR128RegClass;
21111 else if (X86::VR256RegClass.hasType(VT))
21112 Res.second = &X86::VR256RegClass;
21113 else if (X86::VR512RegClass.hasType(VT))
21114 Res.second = &X86::VR512RegClass;
21120 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
21122 // Scaling factors are not free at all.
21123 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
21124 // will take 2 allocations in the out of order engine instead of 1
21125 // for plain addressing mode, i.e. inst (reg1).
21127 // vaddps (%rsi,%drx), %ymm0, %ymm1
21128 // Requires two allocations (one for the load, one for the computation)
21130 // vaddps (%rsi), %ymm0, %ymm1
21131 // Requires just 1 allocation, i.e., freeing allocations for other operations
21132 // and having less micro operations to execute.
21134 // For some X86 architectures, this is even worse because for instance for
21135 // stores, the complex addressing mode forces the instruction to use the
21136 // "load" ports instead of the dedicated "store" port.
21137 // E.g., on Haswell:
21138 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
21139 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
21140 if (isLegalAddressingMode(AM, Ty))
21141 // Scale represents reg2 * scale, thus account for 1
21142 // as soon as we use a second register.
21143 return AM.Scale != 0;