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 #define DEBUG_TYPE "x86-isel"
16 #include "X86ISelLowering.h"
17 #include "Utils/X86ShuffleDecode.h"
19 #include "X86InstrBuilder.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/VariadicFunction.h"
26 #include "llvm/CodeGen/IntrinsicLowering.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineJumpTableInfo.h"
31 #include "llvm/CodeGen/MachineModuleInfo.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/IR/CallingConv.h"
34 #include "llvm/IR/Constants.h"
35 #include "llvm/IR/DerivedTypes.h"
36 #include "llvm/IR/Function.h"
37 #include "llvm/IR/GlobalAlias.h"
38 #include "llvm/IR/GlobalVariable.h"
39 #include "llvm/IR/Instructions.h"
40 #include "llvm/IR/Intrinsics.h"
41 #include "llvm/IR/LLVMContext.h"
42 #include "llvm/MC/MCAsmInfo.h"
43 #include "llvm/MC/MCContext.h"
44 #include "llvm/MC/MCExpr.h"
45 #include "llvm/MC/MCSymbol.h"
46 #include "llvm/Support/CallSite.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 STATISTIC(NumTailCalls, "Number of tail calls");
57 // Forward declarations.
58 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
61 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
62 SelectionDAG &DAG, SDLoc dl,
63 unsigned vectorWidth) {
64 assert((vectorWidth == 128 || vectorWidth == 256) &&
65 "Unsupported vector width");
66 EVT VT = Vec.getValueType();
67 EVT ElVT = VT.getVectorElementType();
68 unsigned Factor = VT.getSizeInBits()/vectorWidth;
69 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
70 VT.getVectorNumElements()/Factor);
72 // Extract from UNDEF is UNDEF.
73 if (Vec.getOpcode() == ISD::UNDEF)
74 return DAG.getUNDEF(ResultVT);
76 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
77 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
79 // This is the index of the first element of the vectorWidth-bit chunk
81 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
84 // If the input is a buildvector just emit a smaller one.
85 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
86 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
87 Vec->op_begin()+NormalizedIdxVal, ElemsPerChunk);
89 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
90 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
96 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
97 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
98 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
99 /// instructions or a simple subregister reference. Idx is an index in the
100 /// 128 bits we want. It need not be aligned to a 128-bit bounday. That makes
101 /// lowering EXTRACT_VECTOR_ELT operations easier.
102 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
103 SelectionDAG &DAG, SDLoc dl) {
104 assert((Vec.getValueType().is256BitVector() ||
105 Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
106 return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
109 /// Generate a DAG to grab 256-bits from a 512-bit vector.
110 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
111 SelectionDAG &DAG, SDLoc dl) {
112 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
113 return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
116 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
117 unsigned IdxVal, SelectionDAG &DAG,
118 SDLoc dl, unsigned vectorWidth) {
119 assert((vectorWidth == 128 || vectorWidth == 256) &&
120 "Unsupported vector width");
121 // Inserting UNDEF is Result
122 if (Vec.getOpcode() == ISD::UNDEF)
124 EVT VT = Vec.getValueType();
125 EVT ElVT = VT.getVectorElementType();
126 EVT ResultVT = Result.getValueType();
128 // Insert the relevant vectorWidth bits.
129 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
131 // This is the index of the first element of the vectorWidth-bit chunk
133 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
136 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
137 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
140 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
141 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
142 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
143 /// simple superregister reference. Idx is an index in the 128 bits
144 /// we want. It need not be aligned to a 128-bit bounday. That makes
145 /// lowering INSERT_VECTOR_ELT operations easier.
146 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
147 unsigned IdxVal, SelectionDAG &DAG,
149 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
150 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
153 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
154 unsigned IdxVal, SelectionDAG &DAG,
156 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
157 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
160 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
161 /// instructions. This is used because creating CONCAT_VECTOR nodes of
162 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
163 /// large BUILD_VECTORS.
164 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
165 unsigned NumElems, SelectionDAG &DAG,
167 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
168 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
171 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
172 unsigned NumElems, SelectionDAG &DAG,
174 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
175 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
178 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
179 const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
180 bool is64Bit = Subtarget->is64Bit();
182 if (Subtarget->isTargetEnvMacho()) {
184 return new X86_64MachoTargetObjectFile();
185 return new TargetLoweringObjectFileMachO();
188 if (Subtarget->isTargetLinux())
189 return new X86LinuxTargetObjectFile();
190 if (Subtarget->isTargetELF())
191 return new TargetLoweringObjectFileELF();
192 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
193 return new TargetLoweringObjectFileCOFF();
194 llvm_unreachable("unknown subtarget type");
197 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
198 : TargetLowering(TM, createTLOF(TM)) {
199 Subtarget = &TM.getSubtarget<X86Subtarget>();
200 X86ScalarSSEf64 = Subtarget->hasSSE2();
201 X86ScalarSSEf32 = Subtarget->hasSSE1();
202 TD = getDataLayout();
204 resetOperationActions();
207 void X86TargetLowering::resetOperationActions() {
208 const TargetMachine &TM = getTargetMachine();
209 static bool FirstTimeThrough = true;
211 // If none of the target options have changed, then we don't need to reset the
212 // operation actions.
213 if (!FirstTimeThrough && TO == TM.Options) return;
215 if (!FirstTimeThrough) {
216 // Reinitialize the actions.
218 FirstTimeThrough = false;
223 // Set up the TargetLowering object.
224 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
226 // X86 is weird, it always uses i8 for shift amounts and setcc results.
227 setBooleanContents(ZeroOrOneBooleanContent);
228 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
229 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
231 // For 64-bit since we have so many registers use the ILP scheduler, for
232 // 32-bit code use the register pressure specific scheduling.
233 // For Atom, always use ILP scheduling.
234 if (Subtarget->isAtom())
235 setSchedulingPreference(Sched::ILP);
236 else if (Subtarget->is64Bit())
237 setSchedulingPreference(Sched::ILP);
239 setSchedulingPreference(Sched::RegPressure);
240 const X86RegisterInfo *RegInfo =
241 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
242 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
244 // Bypass expensive divides on Atom when compiling with O2
245 if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
246 addBypassSlowDiv(32, 8);
247 if (Subtarget->is64Bit())
248 addBypassSlowDiv(64, 16);
251 if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
252 // Setup Windows compiler runtime calls.
253 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
254 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
255 setLibcallName(RTLIB::SREM_I64, "_allrem");
256 setLibcallName(RTLIB::UREM_I64, "_aullrem");
257 setLibcallName(RTLIB::MUL_I64, "_allmul");
258 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
259 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
260 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
261 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
262 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
264 // The _ftol2 runtime function has an unusual calling conv, which
265 // is modeled by a special pseudo-instruction.
266 setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
267 setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
268 setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
269 setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
272 if (Subtarget->isTargetDarwin()) {
273 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
274 setUseUnderscoreSetJmp(false);
275 setUseUnderscoreLongJmp(false);
276 } else if (Subtarget->isTargetMingw()) {
277 // MS runtime is weird: it exports _setjmp, but longjmp!
278 setUseUnderscoreSetJmp(true);
279 setUseUnderscoreLongJmp(false);
281 setUseUnderscoreSetJmp(true);
282 setUseUnderscoreLongJmp(true);
285 // Set up the register classes.
286 addRegisterClass(MVT::i8, &X86::GR8RegClass);
287 addRegisterClass(MVT::i16, &X86::GR16RegClass);
288 addRegisterClass(MVT::i32, &X86::GR32RegClass);
289 if (Subtarget->is64Bit())
290 addRegisterClass(MVT::i64, &X86::GR64RegClass);
292 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
294 // We don't accept any truncstore of integer registers.
295 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
296 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
297 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
298 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
299 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
300 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
302 // SETOEQ and SETUNE require checking two conditions.
303 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
304 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
305 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
306 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
307 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
308 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
310 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
312 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
313 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
314 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
316 if (Subtarget->is64Bit()) {
317 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
318 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
319 } else if (!TM.Options.UseSoftFloat) {
320 // We have an algorithm for SSE2->double, and we turn this into a
321 // 64-bit FILD followed by conditional FADD for other targets.
322 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
323 // We have an algorithm for SSE2, and we turn this into a 64-bit
324 // FILD for other targets.
325 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
328 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
330 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
331 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
333 if (!TM.Options.UseSoftFloat) {
334 // SSE has no i16 to fp conversion, only i32
335 if (X86ScalarSSEf32) {
336 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
337 // f32 and f64 cases are Legal, f80 case is not
338 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
340 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
341 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
344 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
345 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
348 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
349 // are Legal, f80 is custom lowered.
350 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
351 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
353 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
355 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
356 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
358 if (X86ScalarSSEf32) {
359 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
360 // f32 and f64 cases are Legal, f80 case is not
361 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
363 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
364 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
367 // Handle FP_TO_UINT by promoting the destination to a larger signed
369 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
370 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
371 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
373 if (Subtarget->is64Bit()) {
374 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
375 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
376 } else if (!TM.Options.UseSoftFloat) {
377 // Since AVX is a superset of SSE3, only check for SSE here.
378 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
379 // Expand FP_TO_UINT into a select.
380 // FIXME: We would like to use a Custom expander here eventually to do
381 // the optimal thing for SSE vs. the default expansion in the legalizer.
382 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
384 // With SSE3 we can use fisttpll to convert to a signed i64; without
385 // SSE, we're stuck with a fistpll.
386 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
389 if (isTargetFTOL()) {
390 // Use the _ftol2 runtime function, which has a pseudo-instruction
391 // to handle its weird calling convention.
392 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
395 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
396 if (!X86ScalarSSEf64) {
397 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
398 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
399 if (Subtarget->is64Bit()) {
400 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
401 // Without SSE, i64->f64 goes through memory.
402 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
406 // Scalar integer divide and remainder are lowered to use operations that
407 // produce two results, to match the available instructions. This exposes
408 // the two-result form to trivial CSE, which is able to combine x/y and x%y
409 // into a single instruction.
411 // Scalar integer multiply-high is also lowered to use two-result
412 // operations, to match the available instructions. However, plain multiply
413 // (low) operations are left as Legal, as there are single-result
414 // instructions for this in x86. Using the two-result multiply instructions
415 // when both high and low results are needed must be arranged by dagcombine.
416 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
418 setOperationAction(ISD::MULHS, VT, Expand);
419 setOperationAction(ISD::MULHU, VT, Expand);
420 setOperationAction(ISD::SDIV, VT, Expand);
421 setOperationAction(ISD::UDIV, VT, Expand);
422 setOperationAction(ISD::SREM, VT, Expand);
423 setOperationAction(ISD::UREM, VT, Expand);
425 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
426 setOperationAction(ISD::ADDC, VT, Custom);
427 setOperationAction(ISD::ADDE, VT, Custom);
428 setOperationAction(ISD::SUBC, VT, Custom);
429 setOperationAction(ISD::SUBE, VT, Custom);
432 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
433 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
434 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
435 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
436 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
437 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
438 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
439 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
440 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
441 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
442 if (Subtarget->is64Bit())
443 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
444 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
445 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
446 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
447 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
448 setOperationAction(ISD::FREM , MVT::f32 , Expand);
449 setOperationAction(ISD::FREM , MVT::f64 , Expand);
450 setOperationAction(ISD::FREM , MVT::f80 , Expand);
451 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
453 // Promote the i8 variants and force them on up to i32 which has a shorter
455 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
456 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
457 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
458 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
459 if (Subtarget->hasBMI()) {
460 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
461 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
462 if (Subtarget->is64Bit())
463 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
465 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
466 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
467 if (Subtarget->is64Bit())
468 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
471 if (Subtarget->hasLZCNT()) {
472 // When promoting the i8 variants, force them to i32 for a shorter
474 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
475 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
476 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
477 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
478 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
479 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
480 if (Subtarget->is64Bit())
481 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
483 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
484 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
485 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
486 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
487 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
488 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
489 if (Subtarget->is64Bit()) {
490 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
491 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
495 if (Subtarget->hasPOPCNT()) {
496 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
498 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
499 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
500 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
501 if (Subtarget->is64Bit())
502 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
505 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
506 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
508 // These should be promoted to a larger select which is supported.
509 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
510 // X86 wants to expand cmov itself.
511 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
512 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
513 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
514 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
515 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
516 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
517 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
518 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
519 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
520 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
521 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
522 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
523 if (Subtarget->is64Bit()) {
524 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
525 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
527 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
528 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
529 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
530 // support continuation, user-level threading, and etc.. As a result, no
531 // other SjLj exception interfaces are implemented and please don't build
532 // your own exception handling based on them.
533 // LLVM/Clang supports zero-cost DWARF exception handling.
534 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
535 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
538 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
539 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
540 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
541 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
542 if (Subtarget->is64Bit())
543 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
544 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
545 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
546 if (Subtarget->is64Bit()) {
547 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
548 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
549 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
550 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
551 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
553 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
554 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
555 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
556 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
557 if (Subtarget->is64Bit()) {
558 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
559 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
560 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
563 if (Subtarget->hasSSE1())
564 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
566 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
568 // Expand certain atomics
569 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
571 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
572 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
573 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
576 if (!Subtarget->is64Bit()) {
577 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
578 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
579 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
580 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
581 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
582 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
583 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
584 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
585 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
586 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
587 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
588 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
591 if (Subtarget->hasCmpxchg16b()) {
592 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
595 // FIXME - use subtarget debug flags
596 if (!Subtarget->isTargetDarwin() &&
597 !Subtarget->isTargetELF() &&
598 !Subtarget->isTargetCygMing()) {
599 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
602 if (Subtarget->is64Bit()) {
603 setExceptionPointerRegister(X86::RAX);
604 setExceptionSelectorRegister(X86::RDX);
606 setExceptionPointerRegister(X86::EAX);
607 setExceptionSelectorRegister(X86::EDX);
609 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
610 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
612 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
613 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
615 setOperationAction(ISD::TRAP, MVT::Other, Legal);
616 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
618 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
619 setOperationAction(ISD::VASTART , MVT::Other, Custom);
620 setOperationAction(ISD::VAEND , MVT::Other, Expand);
621 if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
622 // TargetInfo::X86_64ABIBuiltinVaList
623 setOperationAction(ISD::VAARG , MVT::Other, Custom);
624 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
626 // TargetInfo::CharPtrBuiltinVaList
627 setOperationAction(ISD::VAARG , MVT::Other, Expand);
628 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
631 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
632 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
634 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
635 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
636 MVT::i64 : MVT::i32, Custom);
637 else if (TM.Options.EnableSegmentedStacks)
638 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
639 MVT::i64 : MVT::i32, Custom);
641 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
642 MVT::i64 : MVT::i32, Expand);
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::UMUL_LOHI, VT, Expand);
832 setOperationAction(ISD::SDIVREM, VT, Expand);
833 setOperationAction(ISD::UDIVREM, VT, Expand);
834 setOperationAction(ISD::FPOW, VT, Expand);
835 setOperationAction(ISD::CTPOP, VT, Expand);
836 setOperationAction(ISD::CTTZ, VT, Expand);
837 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
838 setOperationAction(ISD::CTLZ, VT, Expand);
839 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
840 setOperationAction(ISD::SHL, VT, Expand);
841 setOperationAction(ISD::SRA, VT, Expand);
842 setOperationAction(ISD::SRL, VT, Expand);
843 setOperationAction(ISD::ROTL, VT, Expand);
844 setOperationAction(ISD::ROTR, VT, Expand);
845 setOperationAction(ISD::BSWAP, VT, Expand);
846 setOperationAction(ISD::SETCC, VT, Expand);
847 setOperationAction(ISD::FLOG, VT, Expand);
848 setOperationAction(ISD::FLOG2, VT, Expand);
849 setOperationAction(ISD::FLOG10, VT, Expand);
850 setOperationAction(ISD::FEXP, VT, Expand);
851 setOperationAction(ISD::FEXP2, VT, Expand);
852 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
853 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
854 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
855 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
856 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
857 setOperationAction(ISD::TRUNCATE, VT, Expand);
858 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
859 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
860 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
861 setOperationAction(ISD::VSELECT, VT, Expand);
862 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
863 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
864 setTruncStoreAction(VT,
865 (MVT::SimpleValueType)InnerVT, Expand);
866 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
867 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
868 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
871 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
872 // with -msoft-float, disable use of MMX as well.
873 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
874 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
875 // No operations on x86mmx supported, everything uses intrinsics.
878 // MMX-sized vectors (other than x86mmx) are expected to be expanded
879 // into smaller operations.
880 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
881 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
882 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
883 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
884 setOperationAction(ISD::AND, MVT::v8i8, Expand);
885 setOperationAction(ISD::AND, MVT::v4i16, Expand);
886 setOperationAction(ISD::AND, MVT::v2i32, Expand);
887 setOperationAction(ISD::AND, MVT::v1i64, Expand);
888 setOperationAction(ISD::OR, MVT::v8i8, Expand);
889 setOperationAction(ISD::OR, MVT::v4i16, Expand);
890 setOperationAction(ISD::OR, MVT::v2i32, Expand);
891 setOperationAction(ISD::OR, MVT::v1i64, Expand);
892 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
893 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
894 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
895 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
896 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
897 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
898 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
899 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
900 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
901 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
902 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
903 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
904 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
905 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
906 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
907 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
908 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
910 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
911 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
913 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
914 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
915 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
916 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
917 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
918 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
919 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
920 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
921 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
922 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
923 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
924 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
927 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
928 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
930 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
931 // registers cannot be used even for integer operations.
932 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
933 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
934 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
935 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
937 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
938 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
939 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
940 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
941 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
942 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
943 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
944 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
945 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
946 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
947 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
948 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
949 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
950 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
951 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
952 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
953 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
954 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
956 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
957 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
958 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
959 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
961 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
962 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
963 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
964 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
965 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
967 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
968 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
969 MVT VT = (MVT::SimpleValueType)i;
970 // Do not attempt to custom lower non-power-of-2 vectors
971 if (!isPowerOf2_32(VT.getVectorNumElements()))
973 // Do not attempt to custom lower non-128-bit vectors
974 if (!VT.is128BitVector())
976 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
977 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
978 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
981 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
982 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
983 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
984 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
985 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
986 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
988 if (Subtarget->is64Bit()) {
989 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
990 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
993 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
994 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
995 MVT VT = (MVT::SimpleValueType)i;
997 // Do not attempt to promote non-128-bit vectors
998 if (!VT.is128BitVector())
1001 setOperationAction(ISD::AND, VT, Promote);
1002 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
1003 setOperationAction(ISD::OR, VT, Promote);
1004 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
1005 setOperationAction(ISD::XOR, VT, Promote);
1006 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
1007 setOperationAction(ISD::LOAD, VT, Promote);
1008 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
1009 setOperationAction(ISD::SELECT, VT, Promote);
1010 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1013 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1015 // Custom lower v2i64 and v2f64 selects.
1016 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
1017 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
1018 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
1019 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
1021 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1022 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1024 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1025 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1026 // As there is no 64-bit GPR available, we need build a special custom
1027 // sequence to convert from v2i32 to v2f32.
1028 if (!Subtarget->is64Bit())
1029 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
1031 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1032 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
1034 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
1037 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1038 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1039 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1040 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1041 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1042 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1043 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1044 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1045 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1046 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1047 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1049 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1050 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
1051 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1052 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
1053 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
1054 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
1055 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
1056 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
1057 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
1058 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
1060 // FIXME: Do we need to handle scalar-to-vector here?
1061 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1063 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
1064 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal);
1065 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
1066 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
1067 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
1069 // i8 and i16 vectors are custom , because the source register and source
1070 // source memory operand types are not the same width. f32 vectors are
1071 // custom since the immediate controlling the insert encodes additional
1073 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1074 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1075 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1076 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1078 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1079 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1080 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1081 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1083 // FIXME: these should be Legal but thats only for the case where
1084 // the index is constant. For now custom expand to deal with that.
1085 if (Subtarget->is64Bit()) {
1086 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1087 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1091 if (Subtarget->hasSSE2()) {
1092 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1093 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1095 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1096 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1098 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1099 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1101 // In the customized shift lowering, the legal cases in AVX2 will be
1103 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1104 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1106 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1107 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1109 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1111 setOperationAction(ISD::SDIV, MVT::v8i16, Custom);
1112 setOperationAction(ISD::SDIV, MVT::v4i32, Custom);
1115 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1116 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1117 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1118 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1119 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1120 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1121 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1123 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1124 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1125 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1127 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1128 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1129 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1130 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1131 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1132 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1133 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1134 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1135 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1136 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1137 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1138 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1140 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1141 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1142 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1143 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1144 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1145 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1146 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1147 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1148 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1149 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1150 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1151 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1153 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1154 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1156 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom);
1158 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1159 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1160 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1161 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1163 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1164 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1165 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1167 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1169 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1170 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1172 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1173 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1175 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1176 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1178 setOperationAction(ISD::SDIV, MVT::v16i16, Custom);
1180 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1181 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1182 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1183 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1185 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1186 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1187 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1189 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1190 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal);
1191 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal);
1192 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal);
1194 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1195 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1196 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1197 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1198 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1199 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1201 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1202 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1203 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1204 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1205 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1206 setOperationAction(ISD::FMA, MVT::f32, Legal);
1207 setOperationAction(ISD::FMA, MVT::f64, Legal);
1210 if (Subtarget->hasInt256()) {
1211 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1212 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1213 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1214 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1216 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1217 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1218 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1219 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1221 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1222 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1223 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1224 // Don't lower v32i8 because there is no 128-bit byte mul
1226 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1228 setOperationAction(ISD::SDIV, MVT::v8i32, Custom);
1230 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1231 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1232 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1233 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1235 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1236 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1237 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1238 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1240 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1241 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1242 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1243 // Don't lower v32i8 because there is no 128-bit byte mul
1246 // In the customized shift lowering, the legal cases in AVX2 will be
1248 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1249 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1251 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1252 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1254 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1256 // Custom lower several nodes for 256-bit types.
1257 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1258 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1259 MVT VT = (MVT::SimpleValueType)i;
1261 // Extract subvector is special because the value type
1262 // (result) is 128-bit but the source is 256-bit wide.
1263 if (VT.is128BitVector())
1264 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1266 // Do not attempt to custom lower other non-256-bit vectors
1267 if (!VT.is256BitVector())
1270 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1271 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1272 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1273 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1274 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1275 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1276 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1279 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1280 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1281 MVT VT = (MVT::SimpleValueType)i;
1283 // Do not attempt to promote non-256-bit vectors
1284 if (!VT.is256BitVector())
1287 setOperationAction(ISD::AND, VT, Promote);
1288 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1289 setOperationAction(ISD::OR, VT, Promote);
1290 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1291 setOperationAction(ISD::XOR, VT, Promote);
1292 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1293 setOperationAction(ISD::LOAD, VT, Promote);
1294 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1295 setOperationAction(ISD::SELECT, VT, Promote);
1296 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1300 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1301 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1302 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1303 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1304 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1306 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1307 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1309 setLoadExtAction(ISD::EXTLOAD, MVT::v8f32, Legal);
1310 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1311 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1312 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1313 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1314 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1316 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1317 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1318 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1319 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1320 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1321 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1323 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1324 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1325 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1326 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1327 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1328 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1329 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1330 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1331 setOperationAction(ISD::SDIV, MVT::v16i32, Custom);
1334 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1335 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1336 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1337 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1338 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1339 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1340 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1341 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1343 setOperationAction(ISD::TRUNCATE, MVT::i1, Legal);
1344 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1345 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1346 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1347 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1348 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1349 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1350 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1351 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1352 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1353 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1354 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1356 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1357 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1358 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1359 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1360 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1362 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1363 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1365 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1367 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1368 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1369 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1370 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1371 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1373 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1374 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1376 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1377 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1379 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1381 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1382 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1384 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1385 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1387 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1388 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1390 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1391 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1392 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1394 // Custom lower several nodes.
1395 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1396 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1397 MVT VT = (MVT::SimpleValueType)i;
1399 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1400 // Extract subvector is special because the value type
1401 // (result) is 256/128-bit but the source is 512-bit wide.
1402 if (VT.is128BitVector() || VT.is256BitVector())
1403 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1405 if (VT.getVectorElementType() == MVT::i1)
1406 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1408 // Do not attempt to custom lower other non-512-bit vectors
1409 if (!VT.is512BitVector())
1412 if (VT != MVT::v8i64) {
1413 setOperationAction(ISD::XOR, VT, Promote);
1414 AddPromotedToType (ISD::XOR, VT, MVT::v8i64);
1415 setOperationAction(ISD::OR, VT, Promote);
1416 AddPromotedToType (ISD::OR, VT, MVT::v8i64);
1417 setOperationAction(ISD::AND, VT, Promote);
1418 AddPromotedToType (ISD::AND, VT, MVT::v8i64);
1420 if ( EltSize >= 32) {
1421 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1422 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1423 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1424 setOperationAction(ISD::VSELECT, VT, Legal);
1425 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1426 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1427 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1430 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1431 MVT VT = (MVT::SimpleValueType)i;
1433 // Do not attempt to promote non-256-bit vectors
1434 if (!VT.is512BitVector())
1437 setOperationAction(ISD::LOAD, VT, Promote);
1438 AddPromotedToType (ISD::LOAD, VT, MVT::v8i64);
1439 setOperationAction(ISD::SELECT, VT, Promote);
1440 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1444 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1445 // of this type with custom code.
1446 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1447 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1448 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1452 // We want to custom lower some of our intrinsics.
1453 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1454 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1456 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1457 // handle type legalization for these operations here.
1459 // FIXME: We really should do custom legalization for addition and
1460 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1461 // than generic legalization for 64-bit multiplication-with-overflow, though.
1462 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1463 // Add/Sub/Mul with overflow operations are custom lowered.
1465 setOperationAction(ISD::SADDO, VT, Custom);
1466 setOperationAction(ISD::UADDO, VT, Custom);
1467 setOperationAction(ISD::SSUBO, VT, Custom);
1468 setOperationAction(ISD::USUBO, VT, Custom);
1469 setOperationAction(ISD::SMULO, VT, Custom);
1470 setOperationAction(ISD::UMULO, VT, Custom);
1473 // There are no 8-bit 3-address imul/mul instructions
1474 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1475 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1477 if (!Subtarget->is64Bit()) {
1478 // These libcalls are not available in 32-bit.
1479 setLibcallName(RTLIB::SHL_I128, 0);
1480 setLibcallName(RTLIB::SRL_I128, 0);
1481 setLibcallName(RTLIB::SRA_I128, 0);
1484 // Combine sin / cos into one node or libcall if possible.
1485 if (Subtarget->hasSinCos()) {
1486 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1487 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1488 if (Subtarget->isTargetDarwin()) {
1489 // For MacOSX, we don't want to the normal expansion of a libcall to
1490 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1492 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1493 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1497 // We have target-specific dag combine patterns for the following nodes:
1498 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1499 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1500 setTargetDAGCombine(ISD::VSELECT);
1501 setTargetDAGCombine(ISD::SELECT);
1502 setTargetDAGCombine(ISD::SHL);
1503 setTargetDAGCombine(ISD::SRA);
1504 setTargetDAGCombine(ISD::SRL);
1505 setTargetDAGCombine(ISD::OR);
1506 setTargetDAGCombine(ISD::AND);
1507 setTargetDAGCombine(ISD::ADD);
1508 setTargetDAGCombine(ISD::FADD);
1509 setTargetDAGCombine(ISD::FSUB);
1510 setTargetDAGCombine(ISD::FMA);
1511 setTargetDAGCombine(ISD::SUB);
1512 setTargetDAGCombine(ISD::LOAD);
1513 setTargetDAGCombine(ISD::STORE);
1514 setTargetDAGCombine(ISD::ZERO_EXTEND);
1515 setTargetDAGCombine(ISD::ANY_EXTEND);
1516 setTargetDAGCombine(ISD::SIGN_EXTEND);
1517 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1518 setTargetDAGCombine(ISD::TRUNCATE);
1519 setTargetDAGCombine(ISD::SINT_TO_FP);
1520 setTargetDAGCombine(ISD::SETCC);
1521 if (Subtarget->is64Bit())
1522 setTargetDAGCombine(ISD::MUL);
1523 setTargetDAGCombine(ISD::XOR);
1525 computeRegisterProperties();
1527 // On Darwin, -Os means optimize for size without hurting performance,
1528 // do not reduce the limit.
1529 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1530 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1531 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1532 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1533 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1534 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1535 setPrefLoopAlignment(4); // 2^4 bytes.
1537 // Predictable cmov don't hurt on atom because it's in-order.
1538 PredictableSelectIsExpensive = !Subtarget->isAtom();
1540 setPrefFunctionAlignment(4); // 2^4 bytes.
1543 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1544 if (!VT.isVector()) return MVT::i8;
1545 return VT.changeVectorElementTypeToInteger();
1548 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1549 /// the desired ByVal argument alignment.
1550 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1553 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1554 if (VTy->getBitWidth() == 128)
1556 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1557 unsigned EltAlign = 0;
1558 getMaxByValAlign(ATy->getElementType(), EltAlign);
1559 if (EltAlign > MaxAlign)
1560 MaxAlign = EltAlign;
1561 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1562 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1563 unsigned EltAlign = 0;
1564 getMaxByValAlign(STy->getElementType(i), EltAlign);
1565 if (EltAlign > MaxAlign)
1566 MaxAlign = EltAlign;
1573 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1574 /// function arguments in the caller parameter area. For X86, aggregates
1575 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1576 /// are at 4-byte boundaries.
1577 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1578 if (Subtarget->is64Bit()) {
1579 // Max of 8 and alignment of type.
1580 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1587 if (Subtarget->hasSSE1())
1588 getMaxByValAlign(Ty, Align);
1592 /// getOptimalMemOpType - Returns the target specific optimal type for load
1593 /// and store operations as a result of memset, memcpy, and memmove
1594 /// lowering. If DstAlign is zero that means it's safe to destination
1595 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1596 /// means there isn't a need to check it against alignment requirement,
1597 /// probably because the source does not need to be loaded. If 'IsMemset' is
1598 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1599 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1600 /// source is constant so it does not need to be loaded.
1601 /// It returns EVT::Other if the type should be determined using generic
1602 /// target-independent logic.
1604 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1605 unsigned DstAlign, unsigned SrcAlign,
1606 bool IsMemset, bool ZeroMemset,
1608 MachineFunction &MF) const {
1609 const Function *F = MF.getFunction();
1610 if ((!IsMemset || ZeroMemset) &&
1611 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1612 Attribute::NoImplicitFloat)) {
1614 (Subtarget->isUnalignedMemAccessFast() ||
1615 ((DstAlign == 0 || DstAlign >= 16) &&
1616 (SrcAlign == 0 || SrcAlign >= 16)))) {
1618 if (Subtarget->hasInt256())
1620 if (Subtarget->hasFp256())
1623 if (Subtarget->hasSSE2())
1625 if (Subtarget->hasSSE1())
1627 } else if (!MemcpyStrSrc && Size >= 8 &&
1628 !Subtarget->is64Bit() &&
1629 Subtarget->hasSSE2()) {
1630 // Do not use f64 to lower memcpy if source is string constant. It's
1631 // better to use i32 to avoid the loads.
1635 if (Subtarget->is64Bit() && Size >= 8)
1640 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1642 return X86ScalarSSEf32;
1643 else if (VT == MVT::f64)
1644 return X86ScalarSSEf64;
1649 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
1651 *Fast = Subtarget->isUnalignedMemAccessFast();
1655 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1656 /// current function. The returned value is a member of the
1657 /// MachineJumpTableInfo::JTEntryKind enum.
1658 unsigned X86TargetLowering::getJumpTableEncoding() const {
1659 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1661 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1662 Subtarget->isPICStyleGOT())
1663 return MachineJumpTableInfo::EK_Custom32;
1665 // Otherwise, use the normal jump table encoding heuristics.
1666 return TargetLowering::getJumpTableEncoding();
1670 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1671 const MachineBasicBlock *MBB,
1672 unsigned uid,MCContext &Ctx) const{
1673 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1674 Subtarget->isPICStyleGOT());
1675 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1677 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1678 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1681 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1683 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1684 SelectionDAG &DAG) const {
1685 if (!Subtarget->is64Bit())
1686 // This doesn't have SDLoc associated with it, but is not really the
1687 // same as a Register.
1688 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1692 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1693 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1695 const MCExpr *X86TargetLowering::
1696 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1697 MCContext &Ctx) const {
1698 // X86-64 uses RIP relative addressing based on the jump table label.
1699 if (Subtarget->isPICStyleRIPRel())
1700 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1702 // Otherwise, the reference is relative to the PIC base.
1703 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1706 // FIXME: Why this routine is here? Move to RegInfo!
1707 std::pair<const TargetRegisterClass*, uint8_t>
1708 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1709 const TargetRegisterClass *RRC = 0;
1711 switch (VT.SimpleTy) {
1713 return TargetLowering::findRepresentativeClass(VT);
1714 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1715 RRC = Subtarget->is64Bit() ?
1716 (const TargetRegisterClass*)&X86::GR64RegClass :
1717 (const TargetRegisterClass*)&X86::GR32RegClass;
1720 RRC = &X86::VR64RegClass;
1722 case MVT::f32: case MVT::f64:
1723 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1724 case MVT::v4f32: case MVT::v2f64:
1725 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1727 RRC = &X86::VR128RegClass;
1730 return std::make_pair(RRC, Cost);
1733 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1734 unsigned &Offset) const {
1735 if (!Subtarget->isTargetLinux())
1738 if (Subtarget->is64Bit()) {
1739 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1741 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1753 //===----------------------------------------------------------------------===//
1754 // Return Value Calling Convention Implementation
1755 //===----------------------------------------------------------------------===//
1757 #include "X86GenCallingConv.inc"
1760 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1761 MachineFunction &MF, bool isVarArg,
1762 const SmallVectorImpl<ISD::OutputArg> &Outs,
1763 LLVMContext &Context) const {
1764 SmallVector<CCValAssign, 16> RVLocs;
1765 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1767 return CCInfo.CheckReturn(Outs, RetCC_X86);
1771 X86TargetLowering::LowerReturn(SDValue Chain,
1772 CallingConv::ID CallConv, bool isVarArg,
1773 const SmallVectorImpl<ISD::OutputArg> &Outs,
1774 const SmallVectorImpl<SDValue> &OutVals,
1775 SDLoc dl, SelectionDAG &DAG) const {
1776 MachineFunction &MF = DAG.getMachineFunction();
1777 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1779 SmallVector<CCValAssign, 16> RVLocs;
1780 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1781 RVLocs, *DAG.getContext());
1782 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1785 SmallVector<SDValue, 6> RetOps;
1786 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1787 // Operand #1 = Bytes To Pop
1788 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1791 // Copy the result values into the output registers.
1792 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1793 CCValAssign &VA = RVLocs[i];
1794 assert(VA.isRegLoc() && "Can only return in registers!");
1795 SDValue ValToCopy = OutVals[i];
1796 EVT ValVT = ValToCopy.getValueType();
1798 // Promote values to the appropriate types
1799 if (VA.getLocInfo() == CCValAssign::SExt)
1800 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1801 else if (VA.getLocInfo() == CCValAssign::ZExt)
1802 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1803 else if (VA.getLocInfo() == CCValAssign::AExt)
1804 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1805 else if (VA.getLocInfo() == CCValAssign::BCvt)
1806 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1808 // If this is x86-64, and we disabled SSE, we can't return FP values,
1809 // or SSE or MMX vectors.
1810 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1811 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1812 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1813 report_fatal_error("SSE register return with SSE disabled");
1815 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1816 // llvm-gcc has never done it right and no one has noticed, so this
1817 // should be OK for now.
1818 if (ValVT == MVT::f64 &&
1819 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1820 report_fatal_error("SSE2 register return with SSE2 disabled");
1822 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1823 // the RET instruction and handled by the FP Stackifier.
1824 if (VA.getLocReg() == X86::ST0 ||
1825 VA.getLocReg() == X86::ST1) {
1826 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1827 // change the value to the FP stack register class.
1828 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1829 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1830 RetOps.push_back(ValToCopy);
1831 // Don't emit a copytoreg.
1835 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1836 // which is returned in RAX / RDX.
1837 if (Subtarget->is64Bit()) {
1838 if (ValVT == MVT::x86mmx) {
1839 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1840 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1841 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1843 // If we don't have SSE2 available, convert to v4f32 so the generated
1844 // register is legal.
1845 if (!Subtarget->hasSSE2())
1846 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1851 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1852 Flag = Chain.getValue(1);
1853 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1856 // The x86-64 ABIs require that for returning structs by value we copy
1857 // the sret argument into %rax/%eax (depending on ABI) for the return.
1858 // Win32 requires us to put the sret argument to %eax as well.
1859 // We saved the argument into a virtual register in the entry block,
1860 // so now we copy the value out and into %rax/%eax.
1861 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1862 (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
1863 MachineFunction &MF = DAG.getMachineFunction();
1864 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1865 unsigned Reg = FuncInfo->getSRetReturnReg();
1867 "SRetReturnReg should have been set in LowerFormalArguments().");
1868 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1871 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1872 X86::RAX : X86::EAX;
1873 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1874 Flag = Chain.getValue(1);
1876 // RAX/EAX now acts like a return value.
1877 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1880 RetOps[0] = Chain; // Update chain.
1882 // Add the flag if we have it.
1884 RetOps.push_back(Flag);
1886 return DAG.getNode(X86ISD::RET_FLAG, dl,
1887 MVT::Other, &RetOps[0], RetOps.size());
1890 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1891 if (N->getNumValues() != 1)
1893 if (!N->hasNUsesOfValue(1, 0))
1896 SDValue TCChain = Chain;
1897 SDNode *Copy = *N->use_begin();
1898 if (Copy->getOpcode() == ISD::CopyToReg) {
1899 // If the copy has a glue operand, we conservatively assume it isn't safe to
1900 // perform a tail call.
1901 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1903 TCChain = Copy->getOperand(0);
1904 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1907 bool HasRet = false;
1908 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1910 if (UI->getOpcode() != X86ISD::RET_FLAG)
1923 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1924 ISD::NodeType ExtendKind) const {
1926 // TODO: Is this also valid on 32-bit?
1927 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1928 ReturnMVT = MVT::i8;
1930 ReturnMVT = MVT::i32;
1932 MVT MinVT = getRegisterType(ReturnMVT);
1933 return VT.bitsLT(MinVT) ? MinVT : VT;
1936 /// LowerCallResult - Lower the result values of a call into the
1937 /// appropriate copies out of appropriate physical registers.
1940 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1941 CallingConv::ID CallConv, bool isVarArg,
1942 const SmallVectorImpl<ISD::InputArg> &Ins,
1943 SDLoc dl, SelectionDAG &DAG,
1944 SmallVectorImpl<SDValue> &InVals) const {
1946 // Assign locations to each value returned by this call.
1947 SmallVector<CCValAssign, 16> RVLocs;
1948 bool Is64Bit = Subtarget->is64Bit();
1949 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1950 getTargetMachine(), RVLocs, *DAG.getContext());
1951 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1953 // Copy all of the result registers out of their specified physreg.
1954 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1955 CCValAssign &VA = RVLocs[i];
1956 EVT CopyVT = VA.getValVT();
1958 // If this is x86-64, and we disabled SSE, we can't return FP values
1959 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1960 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1961 report_fatal_error("SSE register return with SSE disabled");
1966 // If this is a call to a function that returns an fp value on the floating
1967 // point stack, we must guarantee the value is popped from the stack, so
1968 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1969 // if the return value is not used. We use the FpPOP_RETVAL instruction
1971 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1972 // If we prefer to use the value in xmm registers, copy it out as f80 and
1973 // use a truncate to move it from fp stack reg to xmm reg.
1974 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1975 SDValue Ops[] = { Chain, InFlag };
1976 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1977 MVT::Other, MVT::Glue, Ops), 1);
1978 Val = Chain.getValue(0);
1980 // Round the f80 to the right size, which also moves it to the appropriate
1982 if (CopyVT != VA.getValVT())
1983 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1984 // This truncation won't change the value.
1985 DAG.getIntPtrConstant(1));
1987 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1988 CopyVT, InFlag).getValue(1);
1989 Val = Chain.getValue(0);
1991 InFlag = Chain.getValue(2);
1992 InVals.push_back(Val);
1998 //===----------------------------------------------------------------------===//
1999 // C & StdCall & Fast Calling Convention implementation
2000 //===----------------------------------------------------------------------===//
2001 // StdCall calling convention seems to be standard for many Windows' API
2002 // routines and around. It differs from C calling convention just a little:
2003 // callee should clean up the stack, not caller. Symbols should be also
2004 // decorated in some fancy way :) It doesn't support any vector arguments.
2005 // For info on fast calling convention see Fast Calling Convention (tail call)
2006 // implementation LowerX86_32FastCCCallTo.
2008 /// CallIsStructReturn - Determines whether a call uses struct return
2010 enum StructReturnType {
2015 static StructReturnType
2016 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2018 return NotStructReturn;
2020 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2021 if (!Flags.isSRet())
2022 return NotStructReturn;
2023 if (Flags.isInReg())
2024 return RegStructReturn;
2025 return StackStructReturn;
2028 /// ArgsAreStructReturn - Determines whether a function uses struct
2029 /// return semantics.
2030 static StructReturnType
2031 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2033 return NotStructReturn;
2035 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2036 if (!Flags.isSRet())
2037 return NotStructReturn;
2038 if (Flags.isInReg())
2039 return RegStructReturn;
2040 return StackStructReturn;
2043 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2044 /// by "Src" to address "Dst" with size and alignment information specified by
2045 /// the specific parameter attribute. The copy will be passed as a byval
2046 /// function parameter.
2048 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2049 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2051 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2053 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2054 /*isVolatile*/false, /*AlwaysInline=*/true,
2055 MachinePointerInfo(), MachinePointerInfo());
2058 /// IsTailCallConvention - Return true if the calling convention is one that
2059 /// supports tail call optimization.
2060 static bool IsTailCallConvention(CallingConv::ID CC) {
2061 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2062 CC == CallingConv::HiPE);
2065 /// \brief Return true if the calling convention is a C calling convention.
2066 static bool IsCCallConvention(CallingConv::ID CC) {
2067 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2068 CC == CallingConv::X86_64_SysV);
2071 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2072 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2076 CallingConv::ID CalleeCC = CS.getCallingConv();
2077 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2083 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2084 /// a tailcall target by changing its ABI.
2085 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2086 bool GuaranteedTailCallOpt) {
2087 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2091 X86TargetLowering::LowerMemArgument(SDValue Chain,
2092 CallingConv::ID CallConv,
2093 const SmallVectorImpl<ISD::InputArg> &Ins,
2094 SDLoc dl, SelectionDAG &DAG,
2095 const CCValAssign &VA,
2096 MachineFrameInfo *MFI,
2098 // Create the nodes corresponding to a load from this parameter slot.
2099 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2100 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2101 getTargetMachine().Options.GuaranteedTailCallOpt);
2102 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2105 // If value is passed by pointer we have address passed instead of the value
2107 if (VA.getLocInfo() == CCValAssign::Indirect)
2108 ValVT = VA.getLocVT();
2110 ValVT = VA.getValVT();
2112 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2113 // changed with more analysis.
2114 // In case of tail call optimization mark all arguments mutable. Since they
2115 // could be overwritten by lowering of arguments in case of a tail call.
2116 if (Flags.isByVal()) {
2117 unsigned Bytes = Flags.getByValSize();
2118 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2119 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2120 return DAG.getFrameIndex(FI, getPointerTy());
2122 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2123 VA.getLocMemOffset(), isImmutable);
2124 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2125 return DAG.getLoad(ValVT, dl, Chain, FIN,
2126 MachinePointerInfo::getFixedStack(FI),
2127 false, false, false, 0);
2132 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2133 CallingConv::ID CallConv,
2135 const SmallVectorImpl<ISD::InputArg> &Ins,
2138 SmallVectorImpl<SDValue> &InVals)
2140 MachineFunction &MF = DAG.getMachineFunction();
2141 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2143 const Function* Fn = MF.getFunction();
2144 if (Fn->hasExternalLinkage() &&
2145 Subtarget->isTargetCygMing() &&
2146 Fn->getName() == "main")
2147 FuncInfo->setForceFramePointer(true);
2149 MachineFrameInfo *MFI = MF.getFrameInfo();
2150 bool Is64Bit = Subtarget->is64Bit();
2151 bool IsWindows = Subtarget->isTargetWindows();
2152 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2154 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2155 "Var args not supported with calling convention fastcc, ghc or hipe");
2157 // Assign locations to all of the incoming arguments.
2158 SmallVector<CCValAssign, 16> ArgLocs;
2159 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2160 ArgLocs, *DAG.getContext());
2162 // Allocate shadow area for Win64
2164 CCInfo.AllocateStack(32, 8);
2166 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2168 unsigned LastVal = ~0U;
2170 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2171 CCValAssign &VA = ArgLocs[i];
2172 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2174 assert(VA.getValNo() != LastVal &&
2175 "Don't support value assigned to multiple locs yet");
2177 LastVal = VA.getValNo();
2179 if (VA.isRegLoc()) {
2180 EVT RegVT = VA.getLocVT();
2181 const TargetRegisterClass *RC;
2182 if (RegVT == MVT::i32)
2183 RC = &X86::GR32RegClass;
2184 else if (Is64Bit && RegVT == MVT::i64)
2185 RC = &X86::GR64RegClass;
2186 else if (RegVT == MVT::f32)
2187 RC = &X86::FR32RegClass;
2188 else if (RegVT == MVT::f64)
2189 RC = &X86::FR64RegClass;
2190 else if (RegVT.is512BitVector())
2191 RC = &X86::VR512RegClass;
2192 else if (RegVT.is256BitVector())
2193 RC = &X86::VR256RegClass;
2194 else if (RegVT.is128BitVector())
2195 RC = &X86::VR128RegClass;
2196 else if (RegVT == MVT::x86mmx)
2197 RC = &X86::VR64RegClass;
2198 else if (RegVT == MVT::v8i1)
2199 RC = &X86::VK8RegClass;
2200 else if (RegVT == MVT::v16i1)
2201 RC = &X86::VK16RegClass;
2203 llvm_unreachable("Unknown argument type!");
2205 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2206 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2208 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2209 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2211 if (VA.getLocInfo() == CCValAssign::SExt)
2212 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2213 DAG.getValueType(VA.getValVT()));
2214 else if (VA.getLocInfo() == CCValAssign::ZExt)
2215 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2216 DAG.getValueType(VA.getValVT()));
2217 else if (VA.getLocInfo() == CCValAssign::BCvt)
2218 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2220 if (VA.isExtInLoc()) {
2221 // Handle MMX values passed in XMM regs.
2222 if (RegVT.isVector())
2223 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2225 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2228 assert(VA.isMemLoc());
2229 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2232 // If value is passed via pointer - do a load.
2233 if (VA.getLocInfo() == CCValAssign::Indirect)
2234 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2235 MachinePointerInfo(), false, false, false, 0);
2237 InVals.push_back(ArgValue);
2240 // The x86-64 ABIs require that for returning structs by value we copy
2241 // the sret argument into %rax/%eax (depending on ABI) for the return.
2242 // Win32 requires us to put the sret argument to %eax as well.
2243 // Save the argument into a virtual register so that we can access it
2244 // from the return points.
2245 if (MF.getFunction()->hasStructRetAttr() &&
2246 (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
2247 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2248 unsigned Reg = FuncInfo->getSRetReturnReg();
2250 MVT PtrTy = getPointerTy();
2251 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2252 FuncInfo->setSRetReturnReg(Reg);
2254 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2255 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2258 unsigned StackSize = CCInfo.getNextStackOffset();
2259 // Align stack specially for tail calls.
2260 if (FuncIsMadeTailCallSafe(CallConv,
2261 MF.getTarget().Options.GuaranteedTailCallOpt))
2262 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2264 // If the function takes variable number of arguments, make a frame index for
2265 // the start of the first vararg value... for expansion of llvm.va_start.
2267 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2268 CallConv != CallingConv::X86_ThisCall)) {
2269 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2272 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2274 // FIXME: We should really autogenerate these arrays
2275 static const uint16_t GPR64ArgRegsWin64[] = {
2276 X86::RCX, X86::RDX, X86::R8, X86::R9
2278 static const uint16_t GPR64ArgRegs64Bit[] = {
2279 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2281 static const uint16_t XMMArgRegs64Bit[] = {
2282 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2283 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2285 const uint16_t *GPR64ArgRegs;
2286 unsigned NumXMMRegs = 0;
2289 // The XMM registers which might contain var arg parameters are shadowed
2290 // in their paired GPR. So we only need to save the GPR to their home
2292 TotalNumIntRegs = 4;
2293 GPR64ArgRegs = GPR64ArgRegsWin64;
2295 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2296 GPR64ArgRegs = GPR64ArgRegs64Bit;
2298 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2301 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2304 bool NoImplicitFloatOps = Fn->getAttributes().
2305 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2306 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2307 "SSE register cannot be used when SSE is disabled!");
2308 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2309 NoImplicitFloatOps) &&
2310 "SSE register cannot be used when SSE is disabled!");
2311 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2312 !Subtarget->hasSSE1())
2313 // Kernel mode asks for SSE to be disabled, so don't push them
2315 TotalNumXMMRegs = 0;
2318 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2319 // Get to the caller-allocated home save location. Add 8 to account
2320 // for the return address.
2321 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2322 FuncInfo->setRegSaveFrameIndex(
2323 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2324 // Fixup to set vararg frame on shadow area (4 x i64).
2326 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2328 // For X86-64, if there are vararg parameters that are passed via
2329 // registers, then we must store them to their spots on the stack so
2330 // they may be loaded by deferencing the result of va_next.
2331 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2332 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2333 FuncInfo->setRegSaveFrameIndex(
2334 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2338 // Store the integer parameter registers.
2339 SmallVector<SDValue, 8> MemOps;
2340 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2342 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2343 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2344 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2345 DAG.getIntPtrConstant(Offset));
2346 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2347 &X86::GR64RegClass);
2348 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2350 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2351 MachinePointerInfo::getFixedStack(
2352 FuncInfo->getRegSaveFrameIndex(), Offset),
2354 MemOps.push_back(Store);
2358 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2359 // Now store the XMM (fp + vector) parameter registers.
2360 SmallVector<SDValue, 11> SaveXMMOps;
2361 SaveXMMOps.push_back(Chain);
2363 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2364 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2365 SaveXMMOps.push_back(ALVal);
2367 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2368 FuncInfo->getRegSaveFrameIndex()));
2369 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2370 FuncInfo->getVarArgsFPOffset()));
2372 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2373 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2374 &X86::VR128RegClass);
2375 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2376 SaveXMMOps.push_back(Val);
2378 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2380 &SaveXMMOps[0], SaveXMMOps.size()));
2383 if (!MemOps.empty())
2384 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2385 &MemOps[0], MemOps.size());
2389 // Some CCs need callee pop.
2390 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2391 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2392 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2394 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2395 // If this is an sret function, the return should pop the hidden pointer.
2396 if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2397 argsAreStructReturn(Ins) == StackStructReturn)
2398 FuncInfo->setBytesToPopOnReturn(4);
2402 // RegSaveFrameIndex is X86-64 only.
2403 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2404 if (CallConv == CallingConv::X86_FastCall ||
2405 CallConv == CallingConv::X86_ThisCall)
2406 // fastcc functions can't have varargs.
2407 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2410 FuncInfo->setArgumentStackSize(StackSize);
2416 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2417 SDValue StackPtr, SDValue Arg,
2418 SDLoc dl, SelectionDAG &DAG,
2419 const CCValAssign &VA,
2420 ISD::ArgFlagsTy Flags) const {
2421 unsigned LocMemOffset = VA.getLocMemOffset();
2422 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2423 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2424 if (Flags.isByVal())
2425 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2427 return DAG.getStore(Chain, dl, Arg, PtrOff,
2428 MachinePointerInfo::getStack(LocMemOffset),
2432 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2433 /// optimization is performed and it is required.
2435 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2436 SDValue &OutRetAddr, SDValue Chain,
2437 bool IsTailCall, bool Is64Bit,
2438 int FPDiff, SDLoc dl) const {
2439 // Adjust the Return address stack slot.
2440 EVT VT = getPointerTy();
2441 OutRetAddr = getReturnAddressFrameIndex(DAG);
2443 // Load the "old" Return address.
2444 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2445 false, false, false, 0);
2446 return SDValue(OutRetAddr.getNode(), 1);
2449 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2450 /// optimization is performed and it is required (FPDiff!=0).
2452 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2453 SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2454 unsigned SlotSize, int FPDiff, SDLoc dl) {
2455 // Store the return address to the appropriate stack slot.
2456 if (!FPDiff) return Chain;
2457 // Calculate the new stack slot for the return address.
2458 int NewReturnAddrFI =
2459 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2461 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2462 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2463 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2469 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2470 SmallVectorImpl<SDValue> &InVals) const {
2471 SelectionDAG &DAG = CLI.DAG;
2473 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2474 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2475 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2476 SDValue Chain = CLI.Chain;
2477 SDValue Callee = CLI.Callee;
2478 CallingConv::ID CallConv = CLI.CallConv;
2479 bool &isTailCall = CLI.IsTailCall;
2480 bool isVarArg = CLI.IsVarArg;
2482 MachineFunction &MF = DAG.getMachineFunction();
2483 bool Is64Bit = Subtarget->is64Bit();
2484 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2485 bool IsWindows = Subtarget->isTargetWindows();
2486 StructReturnType SR = callIsStructReturn(Outs);
2487 bool IsSibcall = false;
2489 if (MF.getTarget().Options.DisableTailCalls)
2493 // Check if it's really possible to do a tail call.
2494 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2495 isVarArg, SR != NotStructReturn,
2496 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2497 Outs, OutVals, Ins, DAG);
2499 // Sibcalls are automatically detected tailcalls which do not require
2501 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2508 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2509 "Var args not supported with calling convention fastcc, ghc or hipe");
2511 // Analyze operands of the call, assigning locations to each operand.
2512 SmallVector<CCValAssign, 16> ArgLocs;
2513 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2514 ArgLocs, *DAG.getContext());
2516 // Allocate shadow area for Win64
2518 CCInfo.AllocateStack(32, 8);
2520 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2522 // Get a count of how many bytes are to be pushed on the stack.
2523 unsigned NumBytes = CCInfo.getNextStackOffset();
2525 // This is a sibcall. The memory operands are available in caller's
2526 // own caller's stack.
2528 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2529 IsTailCallConvention(CallConv))
2530 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2533 if (isTailCall && !IsSibcall) {
2534 // Lower arguments at fp - stackoffset + fpdiff.
2535 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2536 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2538 FPDiff = NumBytesCallerPushed - NumBytes;
2540 // Set the delta of movement of the returnaddr stackslot.
2541 // But only set if delta is greater than previous delta.
2542 if (FPDiff < X86Info->getTCReturnAddrDelta())
2543 X86Info->setTCReturnAddrDelta(FPDiff);
2547 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
2550 SDValue RetAddrFrIdx;
2551 // Load return address for tail calls.
2552 if (isTailCall && FPDiff)
2553 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2554 Is64Bit, FPDiff, dl);
2556 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2557 SmallVector<SDValue, 8> MemOpChains;
2560 // Walk the register/memloc assignments, inserting copies/loads. In the case
2561 // of tail call optimization arguments are handle later.
2562 const X86RegisterInfo *RegInfo =
2563 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2564 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2565 CCValAssign &VA = ArgLocs[i];
2566 EVT RegVT = VA.getLocVT();
2567 SDValue Arg = OutVals[i];
2568 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2569 bool isByVal = Flags.isByVal();
2571 // Promote the value if needed.
2572 switch (VA.getLocInfo()) {
2573 default: llvm_unreachable("Unknown loc info!");
2574 case CCValAssign::Full: break;
2575 case CCValAssign::SExt:
2576 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2578 case CCValAssign::ZExt:
2579 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2581 case CCValAssign::AExt:
2582 if (RegVT.is128BitVector()) {
2583 // Special case: passing MMX values in XMM registers.
2584 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2585 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2586 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2588 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2590 case CCValAssign::BCvt:
2591 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2593 case CCValAssign::Indirect: {
2594 // Store the argument.
2595 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2596 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2597 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2598 MachinePointerInfo::getFixedStack(FI),
2605 if (VA.isRegLoc()) {
2606 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2607 if (isVarArg && IsWin64) {
2608 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2609 // shadow reg if callee is a varargs function.
2610 unsigned ShadowReg = 0;
2611 switch (VA.getLocReg()) {
2612 case X86::XMM0: ShadowReg = X86::RCX; break;
2613 case X86::XMM1: ShadowReg = X86::RDX; break;
2614 case X86::XMM2: ShadowReg = X86::R8; break;
2615 case X86::XMM3: ShadowReg = X86::R9; break;
2618 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2620 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2621 assert(VA.isMemLoc());
2622 if (StackPtr.getNode() == 0)
2623 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2625 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2626 dl, DAG, VA, Flags));
2630 if (!MemOpChains.empty())
2631 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2632 &MemOpChains[0], MemOpChains.size());
2634 if (Subtarget->isPICStyleGOT()) {
2635 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2638 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2639 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2641 // If we are tail calling and generating PIC/GOT style code load the
2642 // address of the callee into ECX. The value in ecx is used as target of
2643 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2644 // for tail calls on PIC/GOT architectures. Normally we would just put the
2645 // address of GOT into ebx and then call target@PLT. But for tail calls
2646 // ebx would be restored (since ebx is callee saved) before jumping to the
2649 // Note: The actual moving to ECX is done further down.
2650 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2651 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2652 !G->getGlobal()->hasProtectedVisibility())
2653 Callee = LowerGlobalAddress(Callee, DAG);
2654 else if (isa<ExternalSymbolSDNode>(Callee))
2655 Callee = LowerExternalSymbol(Callee, DAG);
2659 if (Is64Bit && isVarArg && !IsWin64) {
2660 // From AMD64 ABI document:
2661 // For calls that may call functions that use varargs or stdargs
2662 // (prototype-less calls or calls to functions containing ellipsis (...) in
2663 // the declaration) %al is used as hidden argument to specify the number
2664 // of SSE registers used. The contents of %al do not need to match exactly
2665 // the number of registers, but must be an ubound on the number of SSE
2666 // registers used and is in the range 0 - 8 inclusive.
2668 // Count the number of XMM registers allocated.
2669 static const uint16_t XMMArgRegs[] = {
2670 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2671 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2673 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2674 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2675 && "SSE registers cannot be used when SSE is disabled");
2677 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2678 DAG.getConstant(NumXMMRegs, MVT::i8)));
2681 // For tail calls lower the arguments to the 'real' stack slot.
2683 // Force all the incoming stack arguments to be loaded from the stack
2684 // before any new outgoing arguments are stored to the stack, because the
2685 // outgoing stack slots may alias the incoming argument stack slots, and
2686 // the alias isn't otherwise explicit. This is slightly more conservative
2687 // than necessary, because it means that each store effectively depends
2688 // on every argument instead of just those arguments it would clobber.
2689 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2691 SmallVector<SDValue, 8> MemOpChains2;
2694 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2695 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2696 CCValAssign &VA = ArgLocs[i];
2699 assert(VA.isMemLoc());
2700 SDValue Arg = OutVals[i];
2701 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2702 // Create frame index.
2703 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2704 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2705 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2706 FIN = DAG.getFrameIndex(FI, getPointerTy());
2708 if (Flags.isByVal()) {
2709 // Copy relative to framepointer.
2710 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2711 if (StackPtr.getNode() == 0)
2712 StackPtr = DAG.getCopyFromReg(Chain, dl,
2713 RegInfo->getStackRegister(),
2715 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2717 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2721 // Store relative to framepointer.
2722 MemOpChains2.push_back(
2723 DAG.getStore(ArgChain, dl, Arg, FIN,
2724 MachinePointerInfo::getFixedStack(FI),
2730 if (!MemOpChains2.empty())
2731 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2732 &MemOpChains2[0], MemOpChains2.size());
2734 // Store the return address to the appropriate stack slot.
2735 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2736 getPointerTy(), RegInfo->getSlotSize(),
2740 // Build a sequence of copy-to-reg nodes chained together with token chain
2741 // and flag operands which copy the outgoing args into registers.
2743 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2744 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2745 RegsToPass[i].second, InFlag);
2746 InFlag = Chain.getValue(1);
2749 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2750 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2751 // In the 64-bit large code model, we have to make all calls
2752 // through a register, since the call instruction's 32-bit
2753 // pc-relative offset may not be large enough to hold the whole
2755 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2756 // If the callee is a GlobalAddress node (quite common, every direct call
2757 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2760 // We should use extra load for direct calls to dllimported functions in
2762 const GlobalValue *GV = G->getGlobal();
2763 if (!GV->hasDLLImportLinkage()) {
2764 unsigned char OpFlags = 0;
2765 bool ExtraLoad = false;
2766 unsigned WrapperKind = ISD::DELETED_NODE;
2768 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2769 // external symbols most go through the PLT in PIC mode. If the symbol
2770 // has hidden or protected visibility, or if it is static or local, then
2771 // we don't need to use the PLT - we can directly call it.
2772 if (Subtarget->isTargetELF() &&
2773 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2774 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2775 OpFlags = X86II::MO_PLT;
2776 } else if (Subtarget->isPICStyleStubAny() &&
2777 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2778 (!Subtarget->getTargetTriple().isMacOSX() ||
2779 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2780 // PC-relative references to external symbols should go through $stub,
2781 // unless we're building with the leopard linker or later, which
2782 // automatically synthesizes these stubs.
2783 OpFlags = X86II::MO_DARWIN_STUB;
2784 } else if (Subtarget->isPICStyleRIPRel() &&
2785 isa<Function>(GV) &&
2786 cast<Function>(GV)->getAttributes().
2787 hasAttribute(AttributeSet::FunctionIndex,
2788 Attribute::NonLazyBind)) {
2789 // If the function is marked as non-lazy, generate an indirect call
2790 // which loads from the GOT directly. This avoids runtime overhead
2791 // at the cost of eager binding (and one extra byte of encoding).
2792 OpFlags = X86II::MO_GOTPCREL;
2793 WrapperKind = X86ISD::WrapperRIP;
2797 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2798 G->getOffset(), OpFlags);
2800 // Add a wrapper if needed.
2801 if (WrapperKind != ISD::DELETED_NODE)
2802 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2803 // Add extra indirection if needed.
2805 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2806 MachinePointerInfo::getGOT(),
2807 false, false, false, 0);
2809 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2810 unsigned char OpFlags = 0;
2812 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2813 // external symbols should go through the PLT.
2814 if (Subtarget->isTargetELF() &&
2815 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2816 OpFlags = X86II::MO_PLT;
2817 } else if (Subtarget->isPICStyleStubAny() &&
2818 (!Subtarget->getTargetTriple().isMacOSX() ||
2819 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2820 // PC-relative references to external symbols should go through $stub,
2821 // unless we're building with the leopard linker or later, which
2822 // automatically synthesizes these stubs.
2823 OpFlags = X86II::MO_DARWIN_STUB;
2826 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2830 // Returns a chain & a flag for retval copy to use.
2831 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2832 SmallVector<SDValue, 8> Ops;
2834 if (!IsSibcall && isTailCall) {
2835 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2836 DAG.getIntPtrConstant(0, true), InFlag, dl);
2837 InFlag = Chain.getValue(1);
2840 Ops.push_back(Chain);
2841 Ops.push_back(Callee);
2844 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2846 // Add argument registers to the end of the list so that they are known live
2848 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2849 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2850 RegsToPass[i].second.getValueType()));
2852 // Add a register mask operand representing the call-preserved registers.
2853 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2854 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2855 assert(Mask && "Missing call preserved mask for calling convention");
2856 Ops.push_back(DAG.getRegisterMask(Mask));
2858 if (InFlag.getNode())
2859 Ops.push_back(InFlag);
2863 //// If this is the first return lowered for this function, add the regs
2864 //// to the liveout set for the function.
2865 // This isn't right, although it's probably harmless on x86; liveouts
2866 // should be computed from returns not tail calls. Consider a void
2867 // function making a tail call to a function returning int.
2868 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
2871 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2872 InFlag = Chain.getValue(1);
2874 // Create the CALLSEQ_END node.
2875 unsigned NumBytesForCalleeToPush;
2876 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2877 getTargetMachine().Options.GuaranteedTailCallOpt))
2878 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2879 else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2880 SR == StackStructReturn)
2881 // If this is a call to a struct-return function, the callee
2882 // pops the hidden struct pointer, so we have to push it back.
2883 // This is common for Darwin/X86, Linux & Mingw32 targets.
2884 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2885 NumBytesForCalleeToPush = 4;
2887 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2889 // Returns a flag for retval copy to use.
2891 Chain = DAG.getCALLSEQ_END(Chain,
2892 DAG.getIntPtrConstant(NumBytes, true),
2893 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2896 InFlag = Chain.getValue(1);
2899 // Handle result values, copying them out of physregs into vregs that we
2901 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2902 Ins, dl, DAG, InVals);
2905 //===----------------------------------------------------------------------===//
2906 // Fast Calling Convention (tail call) implementation
2907 //===----------------------------------------------------------------------===//
2909 // Like std call, callee cleans arguments, convention except that ECX is
2910 // reserved for storing the tail called function address. Only 2 registers are
2911 // free for argument passing (inreg). Tail call optimization is performed
2913 // * tailcallopt is enabled
2914 // * caller/callee are fastcc
2915 // On X86_64 architecture with GOT-style position independent code only local
2916 // (within module) calls are supported at the moment.
2917 // To keep the stack aligned according to platform abi the function
2918 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2919 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2920 // If a tail called function callee has more arguments than the caller the
2921 // caller needs to make sure that there is room to move the RETADDR to. This is
2922 // achieved by reserving an area the size of the argument delta right after the
2923 // original REtADDR, but before the saved framepointer or the spilled registers
2924 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2936 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2937 /// for a 16 byte align requirement.
2939 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2940 SelectionDAG& DAG) const {
2941 MachineFunction &MF = DAG.getMachineFunction();
2942 const TargetMachine &TM = MF.getTarget();
2943 const X86RegisterInfo *RegInfo =
2944 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
2945 const TargetFrameLowering &TFI = *TM.getFrameLowering();
2946 unsigned StackAlignment = TFI.getStackAlignment();
2947 uint64_t AlignMask = StackAlignment - 1;
2948 int64_t Offset = StackSize;
2949 unsigned SlotSize = RegInfo->getSlotSize();
2950 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2951 // Number smaller than 12 so just add the difference.
2952 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2954 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2955 Offset = ((~AlignMask) & Offset) + StackAlignment +
2956 (StackAlignment-SlotSize);
2961 /// MatchingStackOffset - Return true if the given stack call argument is
2962 /// already available in the same position (relatively) of the caller's
2963 /// incoming argument stack.
2965 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2966 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2967 const X86InstrInfo *TII) {
2968 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2970 if (Arg.getOpcode() == ISD::CopyFromReg) {
2971 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2972 if (!TargetRegisterInfo::isVirtualRegister(VR))
2974 MachineInstr *Def = MRI->getVRegDef(VR);
2977 if (!Flags.isByVal()) {
2978 if (!TII->isLoadFromStackSlot(Def, FI))
2981 unsigned Opcode = Def->getOpcode();
2982 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2983 Def->getOperand(1).isFI()) {
2984 FI = Def->getOperand(1).getIndex();
2985 Bytes = Flags.getByValSize();
2989 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2990 if (Flags.isByVal())
2991 // ByVal argument is passed in as a pointer but it's now being
2992 // dereferenced. e.g.
2993 // define @foo(%struct.X* %A) {
2994 // tail call @bar(%struct.X* byval %A)
2997 SDValue Ptr = Ld->getBasePtr();
2998 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3001 FI = FINode->getIndex();
3002 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3003 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3004 FI = FINode->getIndex();
3005 Bytes = Flags.getByValSize();
3009 assert(FI != INT_MAX);
3010 if (!MFI->isFixedObjectIndex(FI))
3012 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3015 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3016 /// for tail call optimization. Targets which want to do tail call
3017 /// optimization should implement this function.
3019 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3020 CallingConv::ID CalleeCC,
3022 bool isCalleeStructRet,
3023 bool isCallerStructRet,
3025 const SmallVectorImpl<ISD::OutputArg> &Outs,
3026 const SmallVectorImpl<SDValue> &OutVals,
3027 const SmallVectorImpl<ISD::InputArg> &Ins,
3028 SelectionDAG &DAG) const {
3029 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3032 // If -tailcallopt is specified, make fastcc functions tail-callable.
3033 const MachineFunction &MF = DAG.getMachineFunction();
3034 const Function *CallerF = MF.getFunction();
3036 // If the function return type is x86_fp80 and the callee return type is not,
3037 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3038 // perform a tailcall optimization here.
3039 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3042 CallingConv::ID CallerCC = CallerF->getCallingConv();
3043 bool CCMatch = CallerCC == CalleeCC;
3044 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3045 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3047 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3048 if (IsTailCallConvention(CalleeCC) && CCMatch)
3053 // Look for obvious safe cases to perform tail call optimization that do not
3054 // require ABI changes. This is what gcc calls sibcall.
3056 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3057 // emit a special epilogue.
3058 const X86RegisterInfo *RegInfo =
3059 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3060 if (RegInfo->needsStackRealignment(MF))
3063 // Also avoid sibcall optimization if either caller or callee uses struct
3064 // return semantics.
3065 if (isCalleeStructRet || isCallerStructRet)
3068 // An stdcall caller is expected to clean up its arguments; the callee
3069 // isn't going to do that.
3070 if (!CCMatch && CallerCC == CallingConv::X86_StdCall)
3073 // Do not sibcall optimize vararg calls unless all arguments are passed via
3075 if (isVarArg && !Outs.empty()) {
3077 // Optimizing for varargs on Win64 is unlikely to be safe without
3078 // additional testing.
3079 if (IsCalleeWin64 || IsCallerWin64)
3082 SmallVector<CCValAssign, 16> ArgLocs;
3083 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3084 getTargetMachine(), ArgLocs, *DAG.getContext());
3086 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3087 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3088 if (!ArgLocs[i].isRegLoc())
3092 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3093 // stack. Therefore, if it's not used by the call it is not safe to optimize
3094 // this into a sibcall.
3095 bool Unused = false;
3096 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3103 SmallVector<CCValAssign, 16> RVLocs;
3104 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3105 getTargetMachine(), RVLocs, *DAG.getContext());
3106 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3107 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3108 CCValAssign &VA = RVLocs[i];
3109 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3114 // If the calling conventions do not match, then we'd better make sure the
3115 // results are returned in the same way as what the caller expects.
3117 SmallVector<CCValAssign, 16> RVLocs1;
3118 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3119 getTargetMachine(), RVLocs1, *DAG.getContext());
3120 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3122 SmallVector<CCValAssign, 16> RVLocs2;
3123 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3124 getTargetMachine(), RVLocs2, *DAG.getContext());
3125 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3127 if (RVLocs1.size() != RVLocs2.size())
3129 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3130 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3132 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3134 if (RVLocs1[i].isRegLoc()) {
3135 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3138 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3144 // If the callee takes no arguments then go on to check the results of the
3146 if (!Outs.empty()) {
3147 // Check if stack adjustment is needed. For now, do not do this if any
3148 // argument is passed on the stack.
3149 SmallVector<CCValAssign, 16> ArgLocs;
3150 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3151 getTargetMachine(), ArgLocs, *DAG.getContext());
3153 // Allocate shadow area for Win64
3155 CCInfo.AllocateStack(32, 8);
3157 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3158 if (CCInfo.getNextStackOffset()) {
3159 MachineFunction &MF = DAG.getMachineFunction();
3160 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3163 // Check if the arguments are already laid out in the right way as
3164 // the caller's fixed stack objects.
3165 MachineFrameInfo *MFI = MF.getFrameInfo();
3166 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3167 const X86InstrInfo *TII =
3168 ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3169 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3170 CCValAssign &VA = ArgLocs[i];
3171 SDValue Arg = OutVals[i];
3172 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3173 if (VA.getLocInfo() == CCValAssign::Indirect)
3175 if (!VA.isRegLoc()) {
3176 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3183 // If the tailcall address may be in a register, then make sure it's
3184 // possible to register allocate for it. In 32-bit, the call address can
3185 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3186 // callee-saved registers are restored. These happen to be the same
3187 // registers used to pass 'inreg' arguments so watch out for those.
3188 if (!Subtarget->is64Bit() &&
3189 ((!isa<GlobalAddressSDNode>(Callee) &&
3190 !isa<ExternalSymbolSDNode>(Callee)) ||
3191 getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3192 unsigned NumInRegs = 0;
3193 // In PIC we need an extra register to formulate the address computation
3195 unsigned MaxInRegs =
3196 (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3198 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3199 CCValAssign &VA = ArgLocs[i];
3202 unsigned Reg = VA.getLocReg();
3205 case X86::EAX: case X86::EDX: case X86::ECX:
3206 if (++NumInRegs == MaxInRegs)
3218 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3219 const TargetLibraryInfo *libInfo) const {
3220 return X86::createFastISel(funcInfo, libInfo);
3223 //===----------------------------------------------------------------------===//
3224 // Other Lowering Hooks
3225 //===----------------------------------------------------------------------===//
3227 static bool MayFoldLoad(SDValue Op) {
3228 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3231 static bool MayFoldIntoStore(SDValue Op) {
3232 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3235 static bool isTargetShuffle(unsigned Opcode) {
3237 default: return false;
3238 case X86ISD::PSHUFD:
3239 case X86ISD::PSHUFHW:
3240 case X86ISD::PSHUFLW:
3242 case X86ISD::PALIGNR:
3243 case X86ISD::MOVLHPS:
3244 case X86ISD::MOVLHPD:
3245 case X86ISD::MOVHLPS:
3246 case X86ISD::MOVLPS:
3247 case X86ISD::MOVLPD:
3248 case X86ISD::MOVSHDUP:
3249 case X86ISD::MOVSLDUP:
3250 case X86ISD::MOVDDUP:
3253 case X86ISD::UNPCKL:
3254 case X86ISD::UNPCKH:
3255 case X86ISD::VPERMILP:
3256 case X86ISD::VPERM2X128:
3257 case X86ISD::VPERMI:
3262 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3263 SDValue V1, SelectionDAG &DAG) {
3265 default: llvm_unreachable("Unknown x86 shuffle node");
3266 case X86ISD::MOVSHDUP:
3267 case X86ISD::MOVSLDUP:
3268 case X86ISD::MOVDDUP:
3269 return DAG.getNode(Opc, dl, VT, V1);
3273 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3274 SDValue V1, unsigned TargetMask,
3275 SelectionDAG &DAG) {
3277 default: llvm_unreachable("Unknown x86 shuffle node");
3278 case X86ISD::PSHUFD:
3279 case X86ISD::PSHUFHW:
3280 case X86ISD::PSHUFLW:
3281 case X86ISD::VPERMILP:
3282 case X86ISD::VPERMI:
3283 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3287 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3288 SDValue V1, SDValue V2, unsigned TargetMask,
3289 SelectionDAG &DAG) {
3291 default: llvm_unreachable("Unknown x86 shuffle node");
3292 case X86ISD::PALIGNR:
3294 case X86ISD::VPERM2X128:
3295 return DAG.getNode(Opc, dl, VT, V1, V2,
3296 DAG.getConstant(TargetMask, MVT::i8));
3300 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3301 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3303 default: llvm_unreachable("Unknown x86 shuffle node");
3304 case X86ISD::MOVLHPS:
3305 case X86ISD::MOVLHPD:
3306 case X86ISD::MOVHLPS:
3307 case X86ISD::MOVLPS:
3308 case X86ISD::MOVLPD:
3311 case X86ISD::UNPCKL:
3312 case X86ISD::UNPCKH:
3313 return DAG.getNode(Opc, dl, VT, V1, V2);
3317 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3318 MachineFunction &MF = DAG.getMachineFunction();
3319 const X86RegisterInfo *RegInfo =
3320 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3321 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3322 int ReturnAddrIndex = FuncInfo->getRAIndex();
3324 if (ReturnAddrIndex == 0) {
3325 // Set up a frame object for the return address.
3326 unsigned SlotSize = RegInfo->getSlotSize();
3327 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3330 FuncInfo->setRAIndex(ReturnAddrIndex);
3333 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3336 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3337 bool hasSymbolicDisplacement) {
3338 // Offset should fit into 32 bit immediate field.
3339 if (!isInt<32>(Offset))
3342 // If we don't have a symbolic displacement - we don't have any extra
3344 if (!hasSymbolicDisplacement)
3347 // FIXME: Some tweaks might be needed for medium code model.
3348 if (M != CodeModel::Small && M != CodeModel::Kernel)
3351 // For small code model we assume that latest object is 16MB before end of 31
3352 // bits boundary. We may also accept pretty large negative constants knowing
3353 // that all objects are in the positive half of address space.
3354 if (M == CodeModel::Small && Offset < 16*1024*1024)
3357 // For kernel code model we know that all object resist in the negative half
3358 // of 32bits address space. We may not accept negative offsets, since they may
3359 // be just off and we may accept pretty large positive ones.
3360 if (M == CodeModel::Kernel && Offset > 0)
3366 /// isCalleePop - Determines whether the callee is required to pop its
3367 /// own arguments. Callee pop is necessary to support tail calls.
3368 bool X86::isCalleePop(CallingConv::ID CallingConv,
3369 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3373 switch (CallingConv) {
3376 case CallingConv::X86_StdCall:
3378 case CallingConv::X86_FastCall:
3380 case CallingConv::X86_ThisCall:
3382 case CallingConv::Fast:
3384 case CallingConv::GHC:
3386 case CallingConv::HiPE:
3391 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3392 /// specific condition code, returning the condition code and the LHS/RHS of the
3393 /// comparison to make.
3394 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3395 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3397 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3398 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3399 // X > -1 -> X == 0, jump !sign.
3400 RHS = DAG.getConstant(0, RHS.getValueType());
3401 return X86::COND_NS;
3403 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3404 // X < 0 -> X == 0, jump on sign.
3407 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3409 RHS = DAG.getConstant(0, RHS.getValueType());
3410 return X86::COND_LE;
3414 switch (SetCCOpcode) {
3415 default: llvm_unreachable("Invalid integer condition!");
3416 case ISD::SETEQ: return X86::COND_E;
3417 case ISD::SETGT: return X86::COND_G;
3418 case ISD::SETGE: return X86::COND_GE;
3419 case ISD::SETLT: return X86::COND_L;
3420 case ISD::SETLE: return X86::COND_LE;
3421 case ISD::SETNE: return X86::COND_NE;
3422 case ISD::SETULT: return X86::COND_B;
3423 case ISD::SETUGT: return X86::COND_A;
3424 case ISD::SETULE: return X86::COND_BE;
3425 case ISD::SETUGE: return X86::COND_AE;
3429 // First determine if it is required or is profitable to flip the operands.
3431 // If LHS is a foldable load, but RHS is not, flip the condition.
3432 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3433 !ISD::isNON_EXTLoad(RHS.getNode())) {
3434 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3435 std::swap(LHS, RHS);
3438 switch (SetCCOpcode) {
3444 std::swap(LHS, RHS);
3448 // On a floating point condition, the flags are set as follows:
3450 // 0 | 0 | 0 | X > Y
3451 // 0 | 0 | 1 | X < Y
3452 // 1 | 0 | 0 | X == Y
3453 // 1 | 1 | 1 | unordered
3454 switch (SetCCOpcode) {
3455 default: llvm_unreachable("Condcode should be pre-legalized away");
3457 case ISD::SETEQ: return X86::COND_E;
3458 case ISD::SETOLT: // flipped
3460 case ISD::SETGT: return X86::COND_A;
3461 case ISD::SETOLE: // flipped
3463 case ISD::SETGE: return X86::COND_AE;
3464 case ISD::SETUGT: // flipped
3466 case ISD::SETLT: return X86::COND_B;
3467 case ISD::SETUGE: // flipped
3469 case ISD::SETLE: return X86::COND_BE;
3471 case ISD::SETNE: return X86::COND_NE;
3472 case ISD::SETUO: return X86::COND_P;
3473 case ISD::SETO: return X86::COND_NP;
3475 case ISD::SETUNE: return X86::COND_INVALID;
3479 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3480 /// code. Current x86 isa includes the following FP cmov instructions:
3481 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3482 static bool hasFPCMov(unsigned X86CC) {
3498 /// isFPImmLegal - Returns true if the target can instruction select the
3499 /// specified FP immediate natively. If false, the legalizer will
3500 /// materialize the FP immediate as a load from a constant pool.
3501 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3502 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3503 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3509 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3510 /// the specified range (L, H].
3511 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3512 return (Val < 0) || (Val >= Low && Val < Hi);
3515 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3516 /// specified value.
3517 static bool isUndefOrEqual(int Val, int CmpVal) {
3518 return (Val < 0 || Val == CmpVal);
3521 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3522 /// from position Pos and ending in Pos+Size, falls within the specified
3523 /// sequential range (L, L+Pos]. or is undef.
3524 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3525 unsigned Pos, unsigned Size, int Low) {
3526 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3527 if (!isUndefOrEqual(Mask[i], Low))
3532 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3533 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3534 /// the second operand.
3535 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3536 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3537 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3538 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3539 return (Mask[0] < 2 && Mask[1] < 2);
3543 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3544 /// is suitable for input to PSHUFHW.
3545 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3546 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3549 // Lower quadword copied in order or undef.
3550 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3553 // Upper quadword shuffled.
3554 for (unsigned i = 4; i != 8; ++i)
3555 if (!isUndefOrInRange(Mask[i], 4, 8))
3558 if (VT == MVT::v16i16) {
3559 // Lower quadword copied in order or undef.
3560 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3563 // Upper quadword shuffled.
3564 for (unsigned i = 12; i != 16; ++i)
3565 if (!isUndefOrInRange(Mask[i], 12, 16))
3572 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3573 /// is suitable for input to PSHUFLW.
3574 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3575 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3578 // Upper quadword copied in order.
3579 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3582 // Lower quadword shuffled.
3583 for (unsigned i = 0; i != 4; ++i)
3584 if (!isUndefOrInRange(Mask[i], 0, 4))
3587 if (VT == MVT::v16i16) {
3588 // Upper quadword copied in order.
3589 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3592 // Lower quadword shuffled.
3593 for (unsigned i = 8; i != 12; ++i)
3594 if (!isUndefOrInRange(Mask[i], 8, 12))
3601 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3602 /// is suitable for input to PALIGNR.
3603 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3604 const X86Subtarget *Subtarget) {
3605 if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3606 (VT.is256BitVector() && !Subtarget->hasInt256()))
3609 unsigned NumElts = VT.getVectorNumElements();
3610 unsigned NumLanes = VT.getSizeInBits()/128;
3611 unsigned NumLaneElts = NumElts/NumLanes;
3613 // Do not handle 64-bit element shuffles with palignr.
3614 if (NumLaneElts == 2)
3617 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3619 for (i = 0; i != NumLaneElts; ++i) {
3624 // Lane is all undef, go to next lane
3625 if (i == NumLaneElts)
3628 int Start = Mask[i+l];
3630 // Make sure its in this lane in one of the sources
3631 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3632 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3635 // If not lane 0, then we must match lane 0
3636 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3639 // Correct second source to be contiguous with first source
3640 if (Start >= (int)NumElts)
3641 Start -= NumElts - NumLaneElts;
3643 // Make sure we're shifting in the right direction.
3644 if (Start <= (int)(i+l))
3649 // Check the rest of the elements to see if they are consecutive.
3650 for (++i; i != NumLaneElts; ++i) {
3651 int Idx = Mask[i+l];
3653 // Make sure its in this lane
3654 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3655 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3658 // If not lane 0, then we must match lane 0
3659 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3662 if (Idx >= (int)NumElts)
3663 Idx -= NumElts - NumLaneElts;
3665 if (!isUndefOrEqual(Idx, Start+i))
3674 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3675 /// the two vector operands have swapped position.
3676 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3677 unsigned NumElems) {
3678 for (unsigned i = 0; i != NumElems; ++i) {
3682 else if (idx < (int)NumElems)
3683 Mask[i] = idx + NumElems;
3685 Mask[i] = idx - NumElems;
3689 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3690 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3691 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3692 /// reverse of what x86 shuffles want.
3693 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool HasFp256,
3694 bool Commuted = false) {
3695 if (!HasFp256 && VT.is256BitVector())
3698 unsigned NumElems = VT.getVectorNumElements();
3699 unsigned NumLanes = VT.getSizeInBits()/128;
3700 unsigned NumLaneElems = NumElems/NumLanes;
3702 if (NumLaneElems != 2 && NumLaneElems != 4)
3705 // VSHUFPSY divides the resulting vector into 4 chunks.
3706 // The sources are also splitted into 4 chunks, and each destination
3707 // chunk must come from a different source chunk.
3709 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3710 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3712 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3713 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3715 // VSHUFPDY divides the resulting vector into 4 chunks.
3716 // The sources are also splitted into 4 chunks, and each destination
3717 // chunk must come from a different source chunk.
3719 // SRC1 => X3 X2 X1 X0
3720 // SRC2 => Y3 Y2 Y1 Y0
3722 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3724 unsigned HalfLaneElems = NumLaneElems/2;
3725 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3726 for (unsigned i = 0; i != NumLaneElems; ++i) {
3727 int Idx = Mask[i+l];
3728 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3729 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3731 // For VSHUFPSY, the mask of the second half must be the same as the
3732 // first but with the appropriate offsets. This works in the same way as
3733 // VPERMILPS works with masks.
3734 if (NumElems != 8 || l == 0 || Mask[i] < 0)
3736 if (!isUndefOrEqual(Idx, Mask[i]+l))
3744 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3745 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3746 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3747 if (!VT.is128BitVector())
3750 unsigned NumElems = VT.getVectorNumElements();
3755 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3756 return isUndefOrEqual(Mask[0], 6) &&
3757 isUndefOrEqual(Mask[1], 7) &&
3758 isUndefOrEqual(Mask[2], 2) &&
3759 isUndefOrEqual(Mask[3], 3);
3762 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3763 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3765 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3766 if (!VT.is128BitVector())
3769 unsigned NumElems = VT.getVectorNumElements();
3774 return isUndefOrEqual(Mask[0], 2) &&
3775 isUndefOrEqual(Mask[1], 3) &&
3776 isUndefOrEqual(Mask[2], 2) &&
3777 isUndefOrEqual(Mask[3], 3);
3780 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3781 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3782 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3783 if (!VT.is128BitVector())
3786 unsigned NumElems = VT.getVectorNumElements();
3788 if (NumElems != 2 && NumElems != 4)
3791 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3792 if (!isUndefOrEqual(Mask[i], i + NumElems))
3795 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3796 if (!isUndefOrEqual(Mask[i], i))
3802 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3803 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3804 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3805 if (!VT.is128BitVector())
3808 unsigned NumElems = VT.getVectorNumElements();
3810 if (NumElems != 2 && NumElems != 4)
3813 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3814 if (!isUndefOrEqual(Mask[i], i))
3817 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3818 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3825 // Some special combinations that can be optimized.
3828 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3829 SelectionDAG &DAG) {
3830 MVT VT = SVOp->getValueType(0).getSimpleVT();
3833 if (VT != MVT::v8i32 && VT != MVT::v8f32)
3836 ArrayRef<int> Mask = SVOp->getMask();
3838 // These are the special masks that may be optimized.
3839 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3840 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
3841 bool MatchEvenMask = true;
3842 bool MatchOddMask = true;
3843 for (int i=0; i<8; ++i) {
3844 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3845 MatchEvenMask = false;
3846 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3847 MatchOddMask = false;
3850 if (!MatchEvenMask && !MatchOddMask)
3853 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3855 SDValue Op0 = SVOp->getOperand(0);
3856 SDValue Op1 = SVOp->getOperand(1);
3858 if (MatchEvenMask) {
3859 // Shift the second operand right to 32 bits.
3860 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3861 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3863 // Shift the first operand left to 32 bits.
3864 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3865 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3867 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3868 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3871 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3872 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3873 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
3874 bool HasInt256, bool V2IsSplat = false) {
3876 if (VT.is512BitVector())
3878 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3879 "Unsupported vector type for unpckh");
3881 unsigned NumElts = VT.getVectorNumElements();
3882 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3883 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3886 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3887 // independently on 128-bit lanes.
3888 unsigned NumLanes = VT.getSizeInBits()/128;
3889 unsigned NumLaneElts = NumElts/NumLanes;
3891 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
3892 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
3893 int BitI = Mask[l+i];
3894 int BitI1 = Mask[l+i+1];
3895 if (!isUndefOrEqual(BitI, j))
3898 if (!isUndefOrEqual(BitI1, NumElts))
3901 if (!isUndefOrEqual(BitI1, j + NumElts))
3910 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3911 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3912 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
3913 bool HasInt256, bool V2IsSplat = false) {
3914 unsigned NumElts = VT.getVectorNumElements();
3916 if (VT.is512BitVector())
3918 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3919 "Unsupported vector type for unpckh");
3921 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3922 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3925 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3926 // independently on 128-bit lanes.
3927 unsigned NumLanes = VT.getSizeInBits()/128;
3928 unsigned NumLaneElts = NumElts/NumLanes;
3930 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
3931 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
3932 int BitI = Mask[l+i];
3933 int BitI1 = Mask[l+i+1];
3934 if (!isUndefOrEqual(BitI, j))
3937 if (isUndefOrEqual(BitI1, NumElts))
3940 if (!isUndefOrEqual(BitI1, j+NumElts))
3948 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3949 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3951 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3952 unsigned NumElts = VT.getVectorNumElements();
3953 bool Is256BitVec = VT.is256BitVector();
3955 if (VT.is512BitVector())
3957 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3958 "Unsupported vector type for unpckh");
3960 if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
3961 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3964 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3965 // FIXME: Need a better way to get rid of this, there's no latency difference
3966 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3967 // the former later. We should also remove the "_undef" special mask.
3968 if (NumElts == 4 && Is256BitVec)
3971 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3972 // independently on 128-bit lanes.
3973 unsigned NumLanes = VT.getSizeInBits()/128;
3974 unsigned NumLaneElts = NumElts/NumLanes;
3976 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
3977 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
3978 int BitI = Mask[l+i];
3979 int BitI1 = Mask[l+i+1];
3981 if (!isUndefOrEqual(BitI, j))
3983 if (!isUndefOrEqual(BitI1, j))
3991 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3992 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3994 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3995 unsigned NumElts = VT.getVectorNumElements();
3997 if (VT.is512BitVector())
4000 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4001 "Unsupported vector type for unpckh");
4003 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4004 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4007 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4008 // independently on 128-bit lanes.
4009 unsigned NumLanes = VT.getSizeInBits()/128;
4010 unsigned NumLaneElts = NumElts/NumLanes;
4012 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4013 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4014 int BitI = Mask[l+i];
4015 int BitI1 = Mask[l+i+1];
4016 if (!isUndefOrEqual(BitI, j))
4018 if (!isUndefOrEqual(BitI1, j))
4025 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4026 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4027 /// MOVSD, and MOVD, i.e. setting the lowest element.
4028 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4029 if (VT.getVectorElementType().getSizeInBits() < 32)
4031 if (!VT.is128BitVector())
4034 unsigned NumElts = VT.getVectorNumElements();
4036 if (!isUndefOrEqual(Mask[0], NumElts))
4039 for (unsigned i = 1; i != NumElts; ++i)
4040 if (!isUndefOrEqual(Mask[i], i))
4046 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4047 /// as permutations between 128-bit chunks or halves. As an example: this
4049 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4050 /// The first half comes from the second half of V1 and the second half from the
4051 /// the second half of V2.
4052 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
4053 if (!HasFp256 || !VT.is256BitVector())
4056 // The shuffle result is divided into half A and half B. In total the two
4057 // sources have 4 halves, namely: C, D, E, F. The final values of A and
4058 // B must come from C, D, E or F.
4059 unsigned HalfSize = VT.getVectorNumElements()/2;
4060 bool MatchA = false, MatchB = false;
4062 // Check if A comes from one of C, D, E, F.
4063 for (unsigned Half = 0; Half != 4; ++Half) {
4064 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4070 // Check if B comes from one of C, D, E, F.
4071 for (unsigned Half = 0; Half != 4; ++Half) {
4072 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4078 return MatchA && MatchB;
4081 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4082 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4083 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4084 MVT VT = SVOp->getValueType(0).getSimpleVT();
4086 unsigned HalfSize = VT.getVectorNumElements()/2;
4088 unsigned FstHalf = 0, SndHalf = 0;
4089 for (unsigned i = 0; i < HalfSize; ++i) {
4090 if (SVOp->getMaskElt(i) > 0) {
4091 FstHalf = SVOp->getMaskElt(i)/HalfSize;
4095 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4096 if (SVOp->getMaskElt(i) > 0) {
4097 SndHalf = SVOp->getMaskElt(i)/HalfSize;
4102 return (FstHalf | (SndHalf << 4));
4105 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4106 static bool isPermImmMask(ArrayRef<int> Mask, EVT VT, unsigned& Imm8) {
4107 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4111 unsigned NumElts = VT.getVectorNumElements();
4113 if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4114 for (unsigned i = 0; i != NumElts; ++i) {
4117 Imm8 |= Mask[i] << (i*2);
4122 unsigned LaneSize = 4;
4123 SmallVector<int, 4> MaskVal(LaneSize, -1);
4125 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4126 for (unsigned i = 0; i != LaneSize; ++i) {
4127 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4131 if (MaskVal[i] < 0) {
4132 MaskVal[i] = Mask[i+l] - l;
4133 Imm8 |= MaskVal[i] << (i*2);
4136 if (Mask[i+l] != (signed)(MaskVal[i]+l))
4143 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4144 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4145 /// Note that VPERMIL mask matching is different depending whether theunderlying
4146 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4147 /// to the same elements of the low, but to the higher half of the source.
4148 /// In VPERMILPD the two lanes could be shuffled independently of each other
4149 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4150 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
4154 unsigned NumElts = VT.getVectorNumElements();
4155 // Only match 256-bit with 32/64-bit types
4156 if (!VT.is256BitVector() || (NumElts != 4 && NumElts != 8))
4159 unsigned NumLanes = VT.getSizeInBits()/128;
4160 unsigned LaneSize = NumElts/NumLanes;
4161 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4162 for (unsigned i = 0; i != LaneSize; ++i) {
4163 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4165 if (NumElts != 8 || l == 0)
4167 // VPERMILPS handling
4170 if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
4178 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4179 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
4180 /// element of vector 2 and the other elements to come from vector 1 in order.
4181 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4182 bool V2IsSplat = false, bool V2IsUndef = false) {
4183 if (!VT.is128BitVector())
4186 unsigned NumOps = VT.getVectorNumElements();
4187 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4190 if (!isUndefOrEqual(Mask[0], 0))
4193 for (unsigned i = 1; i != NumOps; ++i)
4194 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4195 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4196 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4202 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4203 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4204 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4205 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4206 const X86Subtarget *Subtarget) {
4207 if (!Subtarget->hasSSE3())
4210 unsigned NumElems = VT.getVectorNumElements();
4212 if ((VT.is128BitVector() && NumElems != 4) ||
4213 (VT.is256BitVector() && NumElems != 8) ||
4214 (VT.is512BitVector() && NumElems != 16))
4217 // "i+1" is the value the indexed mask element must have
4218 for (unsigned i = 0; i != NumElems; i += 2)
4219 if (!isUndefOrEqual(Mask[i], i+1) ||
4220 !isUndefOrEqual(Mask[i+1], i+1))
4226 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4227 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4228 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4229 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4230 const X86Subtarget *Subtarget) {
4231 if (!Subtarget->hasSSE3())
4234 unsigned NumElems = VT.getVectorNumElements();
4236 if ((VT.is128BitVector() && NumElems != 4) ||
4237 (VT.is256BitVector() && NumElems != 8) ||
4238 (VT.is512BitVector() && NumElems != 16))
4241 // "i" is the value the indexed mask element must have
4242 for (unsigned i = 0; i != NumElems; i += 2)
4243 if (!isUndefOrEqual(Mask[i], i) ||
4244 !isUndefOrEqual(Mask[i+1], i))
4250 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4251 /// specifies a shuffle of elements that is suitable for input to 256-bit
4252 /// version of MOVDDUP.
4253 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4254 if (!HasFp256 || !VT.is256BitVector())
4257 unsigned NumElts = VT.getVectorNumElements();
4261 for (unsigned i = 0; i != NumElts/2; ++i)
4262 if (!isUndefOrEqual(Mask[i], 0))
4264 for (unsigned i = NumElts/2; i != NumElts; ++i)
4265 if (!isUndefOrEqual(Mask[i], NumElts/2))
4270 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4271 /// specifies a shuffle of elements that is suitable for input to 128-bit
4272 /// version of MOVDDUP.
4273 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4274 if (!VT.is128BitVector())
4277 unsigned e = VT.getVectorNumElements() / 2;
4278 for (unsigned i = 0; i != e; ++i)
4279 if (!isUndefOrEqual(Mask[i], i))
4281 for (unsigned i = 0; i != e; ++i)
4282 if (!isUndefOrEqual(Mask[e+i], i))
4287 /// isVEXTRACTIndex - Return true if the specified
4288 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4289 /// suitable for instruction that extract 128 or 256 bit vectors
4290 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4291 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4292 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4295 // The index should be aligned on a vecWidth-bit boundary.
4297 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4299 MVT VT = N->getValueType(0).getSimpleVT();
4300 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4301 bool Result = (Index * ElSize) % vecWidth == 0;
4306 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4307 /// operand specifies a subvector insert that is suitable for input to
4308 /// insertion of 128 or 256-bit subvectors
4309 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4310 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4311 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4313 // The index should be aligned on a vecWidth-bit boundary.
4315 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4317 MVT VT = N->getValueType(0).getSimpleVT();
4318 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4319 bool Result = (Index * ElSize) % vecWidth == 0;
4324 bool X86::isVINSERT128Index(SDNode *N) {
4325 return isVINSERTIndex(N, 128);
4328 bool X86::isVINSERT256Index(SDNode *N) {
4329 return isVINSERTIndex(N, 256);
4332 bool X86::isVEXTRACT128Index(SDNode *N) {
4333 return isVEXTRACTIndex(N, 128);
4336 bool X86::isVEXTRACT256Index(SDNode *N) {
4337 return isVEXTRACTIndex(N, 256);
4340 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4341 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4342 /// Handles 128-bit and 256-bit.
4343 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4344 MVT VT = N->getValueType(0).getSimpleVT();
4346 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4347 "Unsupported vector type for PSHUF/SHUFP");
4349 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4350 // independently on 128-bit lanes.
4351 unsigned NumElts = VT.getVectorNumElements();
4352 unsigned NumLanes = VT.getSizeInBits()/128;
4353 unsigned NumLaneElts = NumElts/NumLanes;
4355 assert((NumLaneElts == 2 || NumLaneElts == 4) &&
4356 "Only supports 2 or 4 elements per lane");
4358 unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
4360 for (unsigned i = 0; i != NumElts; ++i) {
4361 int Elt = N->getMaskElt(i);
4362 if (Elt < 0) continue;
4363 Elt &= NumLaneElts - 1;
4364 unsigned ShAmt = (i << Shift) % 8;
4365 Mask |= Elt << ShAmt;
4371 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4372 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4373 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4374 MVT VT = N->getValueType(0).getSimpleVT();
4376 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4377 "Unsupported vector type for PSHUFHW");
4379 unsigned NumElts = VT.getVectorNumElements();
4382 for (unsigned l = 0; l != NumElts; l += 8) {
4383 // 8 nodes per lane, but we only care about the last 4.
4384 for (unsigned i = 0; i < 4; ++i) {
4385 int Elt = N->getMaskElt(l+i+4);
4386 if (Elt < 0) continue;
4387 Elt &= 0x3; // only 2-bits.
4388 Mask |= Elt << (i * 2);
4395 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4396 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4397 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4398 MVT VT = N->getValueType(0).getSimpleVT();
4400 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4401 "Unsupported vector type for PSHUFHW");
4403 unsigned NumElts = VT.getVectorNumElements();
4406 for (unsigned l = 0; l != NumElts; l += 8) {
4407 // 8 nodes per lane, but we only care about the first 4.
4408 for (unsigned i = 0; i < 4; ++i) {
4409 int Elt = N->getMaskElt(l+i);
4410 if (Elt < 0) continue;
4411 Elt &= 0x3; // only 2-bits
4412 Mask |= Elt << (i * 2);
4419 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4420 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4421 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4422 MVT VT = SVOp->getValueType(0).getSimpleVT();
4423 unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4425 unsigned NumElts = VT.getVectorNumElements();
4426 unsigned NumLanes = VT.getSizeInBits()/128;
4427 unsigned NumLaneElts = NumElts/NumLanes;
4431 for (i = 0; i != NumElts; ++i) {
4432 Val = SVOp->getMaskElt(i);
4436 if (Val >= (int)NumElts)
4437 Val -= NumElts - NumLaneElts;
4439 assert(Val - i > 0 && "PALIGNR imm should be positive");
4440 return (Val - i) * EltSize;
4443 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4444 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4445 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4446 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4449 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4451 MVT VecVT = N->getOperand(0).getValueType().getSimpleVT();
4452 MVT ElVT = VecVT.getVectorElementType();
4454 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4455 return Index / NumElemsPerChunk;
4458 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4459 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4460 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4461 llvm_unreachable("Illegal insert subvector for VINSERT");
4464 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4466 MVT VecVT = N->getValueType(0).getSimpleVT();
4467 MVT ElVT = VecVT.getVectorElementType();
4469 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4470 return Index / NumElemsPerChunk;
4473 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4474 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4475 /// and VINSERTI128 instructions.
4476 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4477 return getExtractVEXTRACTImmediate(N, 128);
4480 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4481 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4482 /// and VINSERTI64x4 instructions.
4483 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4484 return getExtractVEXTRACTImmediate(N, 256);
4487 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4488 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4489 /// and VINSERTI128 instructions.
4490 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4491 return getInsertVINSERTImmediate(N, 128);
4494 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4495 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4496 /// and VINSERTI64x4 instructions.
4497 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4498 return getInsertVINSERTImmediate(N, 256);
4501 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4503 bool X86::isZeroNode(SDValue Elt) {
4504 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4505 return CN->isNullValue();
4506 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4507 return CFP->getValueAPF().isPosZero();
4511 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4512 /// their permute mask.
4513 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4514 SelectionDAG &DAG) {
4515 MVT VT = SVOp->getValueType(0).getSimpleVT();
4516 unsigned NumElems = VT.getVectorNumElements();
4517 SmallVector<int, 8> MaskVec;
4519 for (unsigned i = 0; i != NumElems; ++i) {
4520 int Idx = SVOp->getMaskElt(i);
4522 if (Idx < (int)NumElems)
4527 MaskVec.push_back(Idx);
4529 return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4530 SVOp->getOperand(0), &MaskVec[0]);
4533 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4534 /// match movhlps. The lower half elements should come from upper half of
4535 /// V1 (and in order), and the upper half elements should come from the upper
4536 /// half of V2 (and in order).
4537 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4538 if (!VT.is128BitVector())
4540 if (VT.getVectorNumElements() != 4)
4542 for (unsigned i = 0, e = 2; i != e; ++i)
4543 if (!isUndefOrEqual(Mask[i], i+2))
4545 for (unsigned i = 2; i != 4; ++i)
4546 if (!isUndefOrEqual(Mask[i], i+4))
4551 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4552 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4554 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4555 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4557 N = N->getOperand(0).getNode();
4558 if (!ISD::isNON_EXTLoad(N))
4561 *LD = cast<LoadSDNode>(N);
4565 // Test whether the given value is a vector value which will be legalized
4567 static bool WillBeConstantPoolLoad(SDNode *N) {
4568 if (N->getOpcode() != ISD::BUILD_VECTOR)
4571 // Check for any non-constant elements.
4572 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4573 switch (N->getOperand(i).getNode()->getOpcode()) {
4575 case ISD::ConstantFP:
4582 // Vectors of all-zeros and all-ones are materialized with special
4583 // instructions rather than being loaded.
4584 return !ISD::isBuildVectorAllZeros(N) &&
4585 !ISD::isBuildVectorAllOnes(N);
4588 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4589 /// match movlp{s|d}. The lower half elements should come from lower half of
4590 /// V1 (and in order), and the upper half elements should come from the upper
4591 /// half of V2 (and in order). And since V1 will become the source of the
4592 /// MOVLP, it must be either a vector load or a scalar load to vector.
4593 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4594 ArrayRef<int> Mask, MVT VT) {
4595 if (!VT.is128BitVector())
4598 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4600 // Is V2 is a vector load, don't do this transformation. We will try to use
4601 // load folding shufps op.
4602 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4605 unsigned NumElems = VT.getVectorNumElements();
4607 if (NumElems != 2 && NumElems != 4)
4609 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4610 if (!isUndefOrEqual(Mask[i], i))
4612 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4613 if (!isUndefOrEqual(Mask[i], i+NumElems))
4618 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4620 static bool isSplatVector(SDNode *N) {
4621 if (N->getOpcode() != ISD::BUILD_VECTOR)
4624 SDValue SplatValue = N->getOperand(0);
4625 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4626 if (N->getOperand(i) != SplatValue)
4631 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4632 /// to an zero vector.
4633 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4634 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4635 SDValue V1 = N->getOperand(0);
4636 SDValue V2 = N->getOperand(1);
4637 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4638 for (unsigned i = 0; i != NumElems; ++i) {
4639 int Idx = N->getMaskElt(i);
4640 if (Idx >= (int)NumElems) {
4641 unsigned Opc = V2.getOpcode();
4642 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4644 if (Opc != ISD::BUILD_VECTOR ||
4645 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4647 } else if (Idx >= 0) {
4648 unsigned Opc = V1.getOpcode();
4649 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4651 if (Opc != ISD::BUILD_VECTOR ||
4652 !X86::isZeroNode(V1.getOperand(Idx)))
4659 /// getZeroVector - Returns a vector of specified type with all zero elements.
4661 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4662 SelectionDAG &DAG, SDLoc dl) {
4663 assert(VT.isVector() && "Expected a vector type");
4665 // Always build SSE zero vectors as <4 x i32> bitcasted
4666 // to their dest type. This ensures they get CSE'd.
4668 if (VT.is128BitVector()) { // SSE
4669 if (Subtarget->hasSSE2()) { // SSE2
4670 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4671 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4673 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4674 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4676 } else if (VT.is256BitVector()) { // AVX
4677 if (Subtarget->hasInt256()) { // AVX2
4678 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4679 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4680 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4681 array_lengthof(Ops));
4683 // 256-bit logic and arithmetic instructions in AVX are all
4684 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4685 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4686 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4687 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops,
4688 array_lengthof(Ops));
4691 llvm_unreachable("Unexpected vector type");
4693 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4696 /// getOnesVector - Returns a vector of specified type with all bits set.
4697 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4698 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4699 /// Then bitcast to their original type, ensuring they get CSE'd.
4700 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4702 assert(VT.isVector() && "Expected a vector type");
4704 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4706 if (VT.is256BitVector()) {
4707 if (HasInt256) { // AVX2
4708 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4709 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4710 array_lengthof(Ops));
4712 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4713 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4715 } else if (VT.is128BitVector()) {
4716 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4718 llvm_unreachable("Unexpected vector type");
4720 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4723 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4724 /// that point to V2 points to its first element.
4725 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4726 for (unsigned i = 0; i != NumElems; ++i) {
4727 if (Mask[i] > (int)NumElems) {
4733 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4734 /// operation of specified width.
4735 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4737 unsigned NumElems = VT.getVectorNumElements();
4738 SmallVector<int, 8> Mask;
4739 Mask.push_back(NumElems);
4740 for (unsigned i = 1; i != NumElems; ++i)
4742 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4745 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4746 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4748 unsigned NumElems = VT.getVectorNumElements();
4749 SmallVector<int, 8> Mask;
4750 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4752 Mask.push_back(i + NumElems);
4754 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4757 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4758 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4760 unsigned NumElems = VT.getVectorNumElements();
4761 SmallVector<int, 8> Mask;
4762 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4763 Mask.push_back(i + Half);
4764 Mask.push_back(i + NumElems + Half);
4766 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4769 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4770 // a generic shuffle instruction because the target has no such instructions.
4771 // Generate shuffles which repeat i16 and i8 several times until they can be
4772 // represented by v4f32 and then be manipulated by target suported shuffles.
4773 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4774 EVT VT = V.getValueType();
4775 int NumElems = VT.getVectorNumElements();
4778 while (NumElems > 4) {
4779 if (EltNo < NumElems/2) {
4780 V = getUnpackl(DAG, dl, VT, V, V);
4782 V = getUnpackh(DAG, dl, VT, V, V);
4783 EltNo -= NumElems/2;
4790 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4791 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4792 EVT VT = V.getValueType();
4795 if (VT.is128BitVector()) {
4796 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4797 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4798 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4800 } else if (VT.is256BitVector()) {
4801 // To use VPERMILPS to splat scalars, the second half of indicies must
4802 // refer to the higher part, which is a duplication of the lower one,
4803 // because VPERMILPS can only handle in-lane permutations.
4804 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4805 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4807 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4808 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4811 llvm_unreachable("Vector size not supported");
4813 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4816 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4817 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4818 EVT SrcVT = SV->getValueType(0);
4819 SDValue V1 = SV->getOperand(0);
4822 int EltNo = SV->getSplatIndex();
4823 int NumElems = SrcVT.getVectorNumElements();
4824 bool Is256BitVec = SrcVT.is256BitVector();
4826 assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4827 "Unknown how to promote splat for type");
4829 // Extract the 128-bit part containing the splat element and update
4830 // the splat element index when it refers to the higher register.
4832 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4833 if (EltNo >= NumElems/2)
4834 EltNo -= NumElems/2;
4837 // All i16 and i8 vector types can't be used directly by a generic shuffle
4838 // instruction because the target has no such instruction. Generate shuffles
4839 // which repeat i16 and i8 several times until they fit in i32, and then can
4840 // be manipulated by target suported shuffles.
4841 EVT EltVT = SrcVT.getVectorElementType();
4842 if (EltVT == MVT::i8 || EltVT == MVT::i16)
4843 V1 = PromoteSplati8i16(V1, DAG, EltNo);
4845 // Recreate the 256-bit vector and place the same 128-bit vector
4846 // into the low and high part. This is necessary because we want
4847 // to use VPERM* to shuffle the vectors
4849 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4852 return getLegalSplat(DAG, V1, EltNo);
4855 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4856 /// vector of zero or undef vector. This produces a shuffle where the low
4857 /// element of V2 is swizzled into the zero/undef vector, landing at element
4858 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4859 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4861 const X86Subtarget *Subtarget,
4862 SelectionDAG &DAG) {
4863 EVT VT = V2.getValueType();
4865 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4866 unsigned NumElems = VT.getVectorNumElements();
4867 SmallVector<int, 16> MaskVec;
4868 for (unsigned i = 0; i != NumElems; ++i)
4869 // If this is the insertion idx, put the low elt of V2 here.
4870 MaskVec.push_back(i == Idx ? NumElems : i);
4871 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4874 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4875 /// target specific opcode. Returns true if the Mask could be calculated.
4876 /// Sets IsUnary to true if only uses one source.
4877 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4878 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4879 unsigned NumElems = VT.getVectorNumElements();
4883 switch(N->getOpcode()) {
4885 ImmN = N->getOperand(N->getNumOperands()-1);
4886 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4888 case X86ISD::UNPCKH:
4889 DecodeUNPCKHMask(VT, Mask);
4891 case X86ISD::UNPCKL:
4892 DecodeUNPCKLMask(VT, Mask);
4894 case X86ISD::MOVHLPS:
4895 DecodeMOVHLPSMask(NumElems, Mask);
4897 case X86ISD::MOVLHPS:
4898 DecodeMOVLHPSMask(NumElems, Mask);
4900 case X86ISD::PALIGNR:
4901 ImmN = N->getOperand(N->getNumOperands()-1);
4902 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4904 case X86ISD::PSHUFD:
4905 case X86ISD::VPERMILP:
4906 ImmN = N->getOperand(N->getNumOperands()-1);
4907 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4910 case X86ISD::PSHUFHW:
4911 ImmN = N->getOperand(N->getNumOperands()-1);
4912 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4915 case X86ISD::PSHUFLW:
4916 ImmN = N->getOperand(N->getNumOperands()-1);
4917 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4920 case X86ISD::VPERMI:
4921 ImmN = N->getOperand(N->getNumOperands()-1);
4922 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4926 case X86ISD::MOVSD: {
4927 // The index 0 always comes from the first element of the second source,
4928 // this is why MOVSS and MOVSD are used in the first place. The other
4929 // elements come from the other positions of the first source vector
4930 Mask.push_back(NumElems);
4931 for (unsigned i = 1; i != NumElems; ++i) {
4936 case X86ISD::VPERM2X128:
4937 ImmN = N->getOperand(N->getNumOperands()-1);
4938 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4939 if (Mask.empty()) return false;
4941 case X86ISD::MOVDDUP:
4942 case X86ISD::MOVLHPD:
4943 case X86ISD::MOVLPD:
4944 case X86ISD::MOVLPS:
4945 case X86ISD::MOVSHDUP:
4946 case X86ISD::MOVSLDUP:
4947 // Not yet implemented
4949 default: llvm_unreachable("unknown target shuffle node");
4955 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4956 /// element of the result of the vector shuffle.
4957 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4960 return SDValue(); // Limit search depth.
4962 SDValue V = SDValue(N, 0);
4963 EVT VT = V.getValueType();
4964 unsigned Opcode = V.getOpcode();
4966 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4967 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4968 int Elt = SV->getMaskElt(Index);
4971 return DAG.getUNDEF(VT.getVectorElementType());
4973 unsigned NumElems = VT.getVectorNumElements();
4974 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4975 : SV->getOperand(1);
4976 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4979 // Recurse into target specific vector shuffles to find scalars.
4980 if (isTargetShuffle(Opcode)) {
4981 MVT ShufVT = V.getValueType().getSimpleVT();
4982 unsigned NumElems = ShufVT.getVectorNumElements();
4983 SmallVector<int, 16> ShuffleMask;
4986 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4989 int Elt = ShuffleMask[Index];
4991 return DAG.getUNDEF(ShufVT.getVectorElementType());
4993 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4995 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4999 // Actual nodes that may contain scalar elements
5000 if (Opcode == ISD::BITCAST) {
5001 V = V.getOperand(0);
5002 EVT SrcVT = V.getValueType();
5003 unsigned NumElems = VT.getVectorNumElements();
5005 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5009 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5010 return (Index == 0) ? V.getOperand(0)
5011 : DAG.getUNDEF(VT.getVectorElementType());
5013 if (V.getOpcode() == ISD::BUILD_VECTOR)
5014 return V.getOperand(Index);
5019 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5020 /// shuffle operation which come from a consecutively from a zero. The
5021 /// search can start in two different directions, from left or right.
5022 /// We count undefs as zeros until PreferredNum is reached.
5023 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5024 unsigned NumElems, bool ZerosFromLeft,
5026 unsigned PreferredNum = -1U) {
5027 unsigned NumZeros = 0;
5028 for (unsigned i = 0; i != NumElems; ++i) {
5029 unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5030 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5034 if (X86::isZeroNode(Elt))
5036 else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5037 NumZeros = std::min(NumZeros + 1, PreferredNum);
5045 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5046 /// correspond consecutively to elements from one of the vector operands,
5047 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5049 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5050 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5051 unsigned NumElems, unsigned &OpNum) {
5052 bool SeenV1 = false;
5053 bool SeenV2 = false;
5055 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5056 int Idx = SVOp->getMaskElt(i);
5057 // Ignore undef indicies
5061 if (Idx < (int)NumElems)
5066 // Only accept consecutive elements from the same vector
5067 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5071 OpNum = SeenV1 ? 0 : 1;
5075 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5076 /// logical left shift of a vector.
5077 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5078 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5079 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
5080 unsigned NumZeros = getNumOfConsecutiveZeros(
5081 SVOp, NumElems, false /* check zeros from right */, DAG,
5082 SVOp->getMaskElt(0));
5088 // Considering the elements in the mask that are not consecutive zeros,
5089 // check if they consecutively come from only one of the source vectors.
5091 // V1 = {X, A, B, C} 0
5093 // vector_shuffle V1, V2 <1, 2, 3, X>
5095 if (!isShuffleMaskConsecutive(SVOp,
5096 0, // Mask Start Index
5097 NumElems-NumZeros, // Mask End Index(exclusive)
5098 NumZeros, // Where to start looking in the src vector
5099 NumElems, // Number of elements in vector
5100 OpSrc)) // Which source operand ?
5105 ShVal = SVOp->getOperand(OpSrc);
5109 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5110 /// logical left shift of a vector.
5111 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5112 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5113 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
5114 unsigned NumZeros = getNumOfConsecutiveZeros(
5115 SVOp, NumElems, true /* check zeros from left */, DAG,
5116 NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5122 // Considering the elements in the mask that are not consecutive zeros,
5123 // check if they consecutively come from only one of the source vectors.
5125 // 0 { A, B, X, X } = V2
5127 // vector_shuffle V1, V2 <X, X, 4, 5>
5129 if (!isShuffleMaskConsecutive(SVOp,
5130 NumZeros, // Mask Start Index
5131 NumElems, // Mask End Index(exclusive)
5132 0, // Where to start looking in the src vector
5133 NumElems, // Number of elements in vector
5134 OpSrc)) // Which source operand ?
5139 ShVal = SVOp->getOperand(OpSrc);
5143 /// isVectorShift - Returns true if the shuffle can be implemented as a
5144 /// logical left or right shift of a vector.
5145 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5146 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5147 // Although the logic below support any bitwidth size, there are no
5148 // shift instructions which handle more than 128-bit vectors.
5149 if (!SVOp->getValueType(0).is128BitVector())
5152 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5153 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5159 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5161 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5162 unsigned NumNonZero, unsigned NumZero,
5164 const X86Subtarget* Subtarget,
5165 const TargetLowering &TLI) {
5172 for (unsigned i = 0; i < 16; ++i) {
5173 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5174 if (ThisIsNonZero && First) {
5176 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5178 V = DAG.getUNDEF(MVT::v8i16);
5183 SDValue ThisElt(0, 0), LastElt(0, 0);
5184 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5185 if (LastIsNonZero) {
5186 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5187 MVT::i16, Op.getOperand(i-1));
5189 if (ThisIsNonZero) {
5190 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5191 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5192 ThisElt, DAG.getConstant(8, MVT::i8));
5194 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5198 if (ThisElt.getNode())
5199 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5200 DAG.getIntPtrConstant(i/2));
5204 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5207 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5209 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5210 unsigned NumNonZero, unsigned NumZero,
5212 const X86Subtarget* Subtarget,
5213 const TargetLowering &TLI) {
5220 for (unsigned i = 0; i < 8; ++i) {
5221 bool isNonZero = (NonZeros & (1 << i)) != 0;
5225 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5227 V = DAG.getUNDEF(MVT::v8i16);
5230 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5231 MVT::v8i16, V, Op.getOperand(i),
5232 DAG.getIntPtrConstant(i));
5239 /// getVShift - Return a vector logical shift node.
5241 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5242 unsigned NumBits, SelectionDAG &DAG,
5243 const TargetLowering &TLI, SDLoc dl) {
5244 assert(VT.is128BitVector() && "Unknown type for VShift");
5245 EVT ShVT = MVT::v2i64;
5246 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5247 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5248 return DAG.getNode(ISD::BITCAST, dl, VT,
5249 DAG.getNode(Opc, dl, ShVT, SrcOp,
5250 DAG.getConstant(NumBits,
5251 TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5255 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, SDLoc dl,
5256 SelectionDAG &DAG) const {
5258 // Check if the scalar load can be widened into a vector load. And if
5259 // the address is "base + cst" see if the cst can be "absorbed" into
5260 // the shuffle mask.
5261 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5262 SDValue Ptr = LD->getBasePtr();
5263 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5265 EVT PVT = LD->getValueType(0);
5266 if (PVT != MVT::i32 && PVT != MVT::f32)
5271 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5272 FI = FINode->getIndex();
5274 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5275 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5276 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5277 Offset = Ptr.getConstantOperandVal(1);
5278 Ptr = Ptr.getOperand(0);
5283 // FIXME: 256-bit vector instructions don't require a strict alignment,
5284 // improve this code to support it better.
5285 unsigned RequiredAlign = VT.getSizeInBits()/8;
5286 SDValue Chain = LD->getChain();
5287 // Make sure the stack object alignment is at least 16 or 32.
5288 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5289 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5290 if (MFI->isFixedObjectIndex(FI)) {
5291 // Can't change the alignment. FIXME: It's possible to compute
5292 // the exact stack offset and reference FI + adjust offset instead.
5293 // If someone *really* cares about this. That's the way to implement it.
5296 MFI->setObjectAlignment(FI, RequiredAlign);
5300 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5301 // Ptr + (Offset & ~15).
5304 if ((Offset % RequiredAlign) & 3)
5306 int64_t StartOffset = Offset & ~(RequiredAlign-1);
5308 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5309 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5311 int EltNo = (Offset - StartOffset) >> 2;
5312 unsigned NumElems = VT.getVectorNumElements();
5314 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5315 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5316 LD->getPointerInfo().getWithOffset(StartOffset),
5317 false, false, false, 0);
5319 SmallVector<int, 8> Mask;
5320 for (unsigned i = 0; i != NumElems; ++i)
5321 Mask.push_back(EltNo);
5323 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5329 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5330 /// vector of type 'VT', see if the elements can be replaced by a single large
5331 /// load which has the same value as a build_vector whose operands are 'elts'.
5333 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5335 /// FIXME: we'd also like to handle the case where the last elements are zero
5336 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5337 /// There's even a handy isZeroNode for that purpose.
5338 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5339 SDLoc &DL, SelectionDAG &DAG) {
5340 EVT EltVT = VT.getVectorElementType();
5341 unsigned NumElems = Elts.size();
5343 LoadSDNode *LDBase = NULL;
5344 unsigned LastLoadedElt = -1U;
5346 // For each element in the initializer, see if we've found a load or an undef.
5347 // If we don't find an initial load element, or later load elements are
5348 // non-consecutive, bail out.
5349 for (unsigned i = 0; i < NumElems; ++i) {
5350 SDValue Elt = Elts[i];
5352 if (!Elt.getNode() ||
5353 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5356 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5358 LDBase = cast<LoadSDNode>(Elt.getNode());
5362 if (Elt.getOpcode() == ISD::UNDEF)
5365 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5366 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5371 // If we have found an entire vector of loads and undefs, then return a large
5372 // load of the entire vector width starting at the base pointer. If we found
5373 // consecutive loads for the low half, generate a vzext_load node.
5374 if (LastLoadedElt == NumElems - 1) {
5375 SDValue NewLd = SDValue();
5376 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5377 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5378 LDBase->getPointerInfo(),
5379 LDBase->isVolatile(), LDBase->isNonTemporal(),
5380 LDBase->isInvariant(), 0);
5381 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5382 LDBase->getPointerInfo(),
5383 LDBase->isVolatile(), LDBase->isNonTemporal(),
5384 LDBase->isInvariant(), LDBase->getAlignment());
5386 if (LDBase->hasAnyUseOfValue(1)) {
5387 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5389 SDValue(NewLd.getNode(), 1));
5390 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5391 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5392 SDValue(NewLd.getNode(), 1));
5397 if (NumElems == 4 && LastLoadedElt == 1 &&
5398 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5399 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5400 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5402 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops,
5403 array_lengthof(Ops), MVT::i64,
5404 LDBase->getPointerInfo(),
5405 LDBase->getAlignment(),
5406 false/*isVolatile*/, true/*ReadMem*/,
5409 // Make sure the newly-created LOAD is in the same position as LDBase in
5410 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5411 // update uses of LDBase's output chain to use the TokenFactor.
5412 if (LDBase->hasAnyUseOfValue(1)) {
5413 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5414 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5415 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5416 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5417 SDValue(ResNode.getNode(), 1));
5420 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5425 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5426 /// to generate a splat value for the following cases:
5427 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5428 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5429 /// a scalar load, or a constant.
5430 /// The VBROADCAST node is returned when a pattern is found,
5431 /// or SDValue() otherwise.
5433 X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5434 if (!Subtarget->hasFp256())
5437 MVT VT = Op.getValueType().getSimpleVT();
5440 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5441 "Unsupported vector type for broadcast.");
5446 switch (Op.getOpcode()) {
5448 // Unknown pattern found.
5451 case ISD::BUILD_VECTOR: {
5452 // The BUILD_VECTOR node must be a splat.
5453 if (!isSplatVector(Op.getNode()))
5456 Ld = Op.getOperand(0);
5457 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5458 Ld.getOpcode() == ISD::ConstantFP);
5460 // The suspected load node has several users. Make sure that all
5461 // of its users are from the BUILD_VECTOR node.
5462 // Constants may have multiple users.
5463 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5468 case ISD::VECTOR_SHUFFLE: {
5469 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5471 // Shuffles must have a splat mask where the first element is
5473 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5476 SDValue Sc = Op.getOperand(0);
5477 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5478 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5480 if (!Subtarget->hasInt256())
5483 // Use the register form of the broadcast instruction available on AVX2.
5484 if (VT.getSizeInBits() >= 256)
5485 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5486 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5489 Ld = Sc.getOperand(0);
5490 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5491 Ld.getOpcode() == ISD::ConstantFP);
5493 // The scalar_to_vector node and the suspected
5494 // load node must have exactly one user.
5495 // Constants may have multiple users.
5497 // AVX-512 has register version of the broadcast
5498 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5499 Ld.getValueType().getSizeInBits() >= 32;
5500 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5507 bool IsGE256 = (VT.getSizeInBits() >= 256);
5509 // Handle the broadcasting a single constant scalar from the constant pool
5510 // into a vector. On Sandybridge it is still better to load a constant vector
5511 // from the constant pool and not to broadcast it from a scalar.
5512 if (ConstSplatVal && Subtarget->hasInt256()) {
5513 EVT CVT = Ld.getValueType();
5514 assert(!CVT.isVector() && "Must not broadcast a vector type");
5515 unsigned ScalarSize = CVT.getSizeInBits();
5517 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5518 const Constant *C = 0;
5519 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5520 C = CI->getConstantIntValue();
5521 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5522 C = CF->getConstantFPValue();
5524 assert(C && "Invalid constant type");
5526 SDValue CP = DAG.getConstantPool(C, getPointerTy());
5527 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5528 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5529 MachinePointerInfo::getConstantPool(),
5530 false, false, false, Alignment);
5532 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5536 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5537 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5539 // Handle AVX2 in-register broadcasts.
5540 if (!IsLoad && Subtarget->hasInt256() &&
5541 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5542 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5544 // The scalar source must be a normal load.
5548 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5549 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5551 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5552 // double since there is no vbroadcastsd xmm
5553 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5554 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5555 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5558 // Unsupported broadcast.
5563 X86TargetLowering::buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) const {
5564 EVT VT = Op.getValueType();
5566 // Skip if insert_vec_elt is not supported.
5567 if (!isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5571 unsigned NumElems = Op.getNumOperands();
5575 SmallVector<unsigned, 4> InsertIndices;
5576 SmallVector<int, 8> Mask(NumElems, -1);
5578 for (unsigned i = 0; i != NumElems; ++i) {
5579 unsigned Opc = Op.getOperand(i).getOpcode();
5581 if (Opc == ISD::UNDEF)
5584 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5585 // Quit if more than 1 elements need inserting.
5586 if (InsertIndices.size() > 1)
5589 InsertIndices.push_back(i);
5593 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5594 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5596 // Quit if extracted from vector of different type.
5597 if (ExtractedFromVec.getValueType() != VT)
5600 // Quit if non-constant index.
5601 if (!isa<ConstantSDNode>(ExtIdx))
5604 if (VecIn1.getNode() == 0)
5605 VecIn1 = ExtractedFromVec;
5606 else if (VecIn1 != ExtractedFromVec) {
5607 if (VecIn2.getNode() == 0)
5608 VecIn2 = ExtractedFromVec;
5609 else if (VecIn2 != ExtractedFromVec)
5610 // Quit if more than 2 vectors to shuffle
5614 unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5616 if (ExtractedFromVec == VecIn1)
5618 else if (ExtractedFromVec == VecIn2)
5619 Mask[i] = Idx + NumElems;
5622 if (VecIn1.getNode() == 0)
5625 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5626 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5627 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5628 unsigned Idx = InsertIndices[i];
5629 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5630 DAG.getIntPtrConstant(Idx));
5636 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5638 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5640 EVT VT = Op.getValueType();
5641 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5642 "Unexpected type in LowerBUILD_VECTORvXi1!");
5645 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5646 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5647 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5648 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5649 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5650 Ops, VT.getVectorNumElements());
5653 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5654 SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5655 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5656 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5657 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5658 Ops, VT.getVectorNumElements());
5661 bool AllContants = true;
5662 uint64_t Immediate = 0;
5663 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5664 SDValue In = Op.getOperand(idx);
5665 if (In.getOpcode() == ISD::UNDEF)
5667 if (!isa<ConstantSDNode>(In)) {
5668 AllContants = false;
5671 if (cast<ConstantSDNode>(In)->getZExtValue())
5672 Immediate |= (1ULL << idx);
5676 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5677 DAG.getConstant(Immediate, MVT::i16));
5678 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5679 DAG.getIntPtrConstant(0));
5682 if (!isSplatVector(Op.getNode()))
5683 llvm_unreachable("Unsupported predicate operation");
5685 SDValue In = Op.getOperand(0);
5686 SDValue EFLAGS, X86CC;
5687 if (In.getOpcode() == ISD::SETCC) {
5688 SDValue Op0 = In.getOperand(0);
5689 SDValue Op1 = In.getOperand(1);
5690 ISD::CondCode CC = cast<CondCodeSDNode>(In.getOperand(2))->get();
5691 bool isFP = Op1.getValueType().isFloatingPoint();
5692 unsigned X86CCVal = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
5694 assert(X86CCVal != X86::COND_INVALID && "Unsupported predicate operation");
5696 X86CC = DAG.getConstant(X86CCVal, MVT::i8);
5697 EFLAGS = EmitCmp(Op0, Op1, X86CCVal, DAG);
5698 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
5699 } else if (In.getOpcode() == X86ISD::SETCC) {
5700 X86CC = In.getOperand(0);
5701 EFLAGS = In.getOperand(1);
5710 // res = allOnes ### CMOVNE -1, %res
5713 MVT InVT = In.getValueType().getSimpleVT();
5714 SDValue Bit1 = DAG.getNode(ISD::AND, dl, InVT, In, DAG.getConstant(1, InVT));
5715 EFLAGS = EmitTest(Bit1, X86::COND_NE, DAG);
5716 X86CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5719 if (VT == MVT::v16i1) {
5720 SDValue Cst1 = DAG.getConstant(-1, MVT::i16);
5721 SDValue Cst0 = DAG.getConstant(0, MVT::i16);
5722 SDValue CmovOp = DAG.getNode(X86ISD::CMOV, dl, MVT::i16,
5723 Cst0, Cst1, X86CC, EFLAGS);
5724 return DAG.getNode(ISD::BITCAST, dl, VT, CmovOp);
5727 if (VT == MVT::v8i1) {
5728 SDValue Cst1 = DAG.getConstant(-1, MVT::i32);
5729 SDValue Cst0 = DAG.getConstant(0, MVT::i32);
5730 SDValue CmovOp = DAG.getNode(X86ISD::CMOV, dl, MVT::i32,
5731 Cst0, Cst1, X86CC, EFLAGS);
5732 CmovOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CmovOp);
5733 return DAG.getNode(ISD::BITCAST, dl, VT, CmovOp);
5735 llvm_unreachable("Unsupported predicate operation");
5739 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5742 MVT VT = Op.getValueType().getSimpleVT();
5743 MVT ExtVT = VT.getVectorElementType();
5744 unsigned NumElems = Op.getNumOperands();
5746 // Generate vectors for predicate vectors.
5747 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5748 return LowerBUILD_VECTORvXi1(Op, DAG);
5750 // Vectors containing all zeros can be matched by pxor and xorps later
5751 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5752 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5753 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5754 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5757 return getZeroVector(VT, Subtarget, DAG, dl);
5760 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5761 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5762 // vpcmpeqd on 256-bit vectors.
5763 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5764 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5767 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5770 SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5771 if (Broadcast.getNode())
5774 unsigned EVTBits = ExtVT.getSizeInBits();
5776 unsigned NumZero = 0;
5777 unsigned NumNonZero = 0;
5778 unsigned NonZeros = 0;
5779 bool IsAllConstants = true;
5780 SmallSet<SDValue, 8> Values;
5781 for (unsigned i = 0; i < NumElems; ++i) {
5782 SDValue Elt = Op.getOperand(i);
5783 if (Elt.getOpcode() == ISD::UNDEF)
5786 if (Elt.getOpcode() != ISD::Constant &&
5787 Elt.getOpcode() != ISD::ConstantFP)
5788 IsAllConstants = false;
5789 if (X86::isZeroNode(Elt))
5792 NonZeros |= (1 << i);
5797 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5798 if (NumNonZero == 0)
5799 return DAG.getUNDEF(VT);
5801 // Special case for single non-zero, non-undef, element.
5802 if (NumNonZero == 1) {
5803 unsigned Idx = countTrailingZeros(NonZeros);
5804 SDValue Item = Op.getOperand(Idx);
5806 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5807 // the value are obviously zero, truncate the value to i32 and do the
5808 // insertion that way. Only do this if the value is non-constant or if the
5809 // value is a constant being inserted into element 0. It is cheaper to do
5810 // a constant pool load than it is to do a movd + shuffle.
5811 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5812 (!IsAllConstants || Idx == 0)) {
5813 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5815 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5816 EVT VecVT = MVT::v4i32;
5817 unsigned VecElts = 4;
5819 // Truncate the value (which may itself be a constant) to i32, and
5820 // convert it to a vector with movd (S2V+shuffle to zero extend).
5821 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5822 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5823 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5825 // Now we have our 32-bit value zero extended in the low element of
5826 // a vector. If Idx != 0, swizzle it into place.
5828 SmallVector<int, 4> Mask;
5829 Mask.push_back(Idx);
5830 for (unsigned i = 1; i != VecElts; ++i)
5832 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5835 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5839 // If we have a constant or non-constant insertion into the low element of
5840 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5841 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5842 // depending on what the source datatype is.
5845 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5847 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5848 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5849 if (VT.is256BitVector()) {
5850 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5851 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5852 Item, DAG.getIntPtrConstant(0));
5854 assert(VT.is128BitVector() && "Expected an SSE value type!");
5855 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5856 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5857 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5860 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5861 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5862 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5863 if (VT.is256BitVector()) {
5864 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5865 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5867 assert(VT.is128BitVector() && "Expected an SSE value type!");
5868 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5870 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5874 // Is it a vector logical left shift?
5875 if (NumElems == 2 && Idx == 1 &&
5876 X86::isZeroNode(Op.getOperand(0)) &&
5877 !X86::isZeroNode(Op.getOperand(1))) {
5878 unsigned NumBits = VT.getSizeInBits();
5879 return getVShift(true, VT,
5880 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5881 VT, Op.getOperand(1)),
5882 NumBits/2, DAG, *this, dl);
5885 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5888 // Otherwise, if this is a vector with i32 or f32 elements, and the element
5889 // is a non-constant being inserted into an element other than the low one,
5890 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
5891 // movd/movss) to move this into the low element, then shuffle it into
5893 if (EVTBits == 32) {
5894 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5896 // Turn it into a shuffle of zero and zero-extended scalar to vector.
5897 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5898 SmallVector<int, 8> MaskVec;
5899 for (unsigned i = 0; i != NumElems; ++i)
5900 MaskVec.push_back(i == Idx ? 0 : 1);
5901 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5905 // Splat is obviously ok. Let legalizer expand it to a shuffle.
5906 if (Values.size() == 1) {
5907 if (EVTBits == 32) {
5908 // Instead of a shuffle like this:
5909 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5910 // Check if it's possible to issue this instead.
5911 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5912 unsigned Idx = countTrailingZeros(NonZeros);
5913 SDValue Item = Op.getOperand(Idx);
5914 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5915 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5920 // A vector full of immediates; various special cases are already
5921 // handled, so this is best done with a single constant-pool load.
5925 // For AVX-length vectors, build the individual 128-bit pieces and use
5926 // shuffles to put them in place.
5927 if (VT.is256BitVector()) {
5928 SmallVector<SDValue, 32> V;
5929 for (unsigned i = 0; i != NumElems; ++i)
5930 V.push_back(Op.getOperand(i));
5932 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5934 // Build both the lower and upper subvector.
5935 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5936 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5939 // Recreate the wider vector with the lower and upper part.
5940 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5943 // Let legalizer expand 2-wide build_vectors.
5944 if (EVTBits == 64) {
5945 if (NumNonZero == 1) {
5946 // One half is zero or undef.
5947 unsigned Idx = countTrailingZeros(NonZeros);
5948 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5949 Op.getOperand(Idx));
5950 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5955 // If element VT is < 32 bits, convert it to inserts into a zero vector.
5956 if (EVTBits == 8 && NumElems == 16) {
5957 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5959 if (V.getNode()) return V;
5962 if (EVTBits == 16 && NumElems == 8) {
5963 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5965 if (V.getNode()) return V;
5968 // If element VT is == 32 bits, turn it into a number of shuffles.
5969 SmallVector<SDValue, 8> V(NumElems);
5970 if (NumElems == 4 && NumZero > 0) {
5971 for (unsigned i = 0; i < 4; ++i) {
5972 bool isZero = !(NonZeros & (1 << i));
5974 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5976 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5979 for (unsigned i = 0; i < 2; ++i) {
5980 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5983 V[i] = V[i*2]; // Must be a zero vector.
5986 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5989 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5992 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5997 bool Reverse1 = (NonZeros & 0x3) == 2;
5998 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6002 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6003 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6005 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6008 if (Values.size() > 1 && VT.is128BitVector()) {
6009 // Check for a build vector of consecutive loads.
6010 for (unsigned i = 0; i < NumElems; ++i)
6011 V[i] = Op.getOperand(i);
6013 // Check for elements which are consecutive loads.
6014 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
6018 // Check for a build vector from mostly shuffle plus few inserting.
6019 SDValue Sh = buildFromShuffleMostly(Op, DAG);
6023 // For SSE 4.1, use insertps to put the high elements into the low element.
6024 if (getSubtarget()->hasSSE41()) {
6026 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6027 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6029 Result = DAG.getUNDEF(VT);
6031 for (unsigned i = 1; i < NumElems; ++i) {
6032 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6033 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6034 Op.getOperand(i), DAG.getIntPtrConstant(i));
6039 // Otherwise, expand into a number of unpckl*, start by extending each of
6040 // our (non-undef) elements to the full vector width with the element in the
6041 // bottom slot of the vector (which generates no code for SSE).
6042 for (unsigned i = 0; i < NumElems; ++i) {
6043 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6044 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6046 V[i] = DAG.getUNDEF(VT);
6049 // Next, we iteratively mix elements, e.g. for v4f32:
6050 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6051 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6052 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6053 unsigned EltStride = NumElems >> 1;
6054 while (EltStride != 0) {
6055 for (unsigned i = 0; i < EltStride; ++i) {
6056 // If V[i+EltStride] is undef and this is the first round of mixing,
6057 // then it is safe to just drop this shuffle: V[i] is already in the
6058 // right place, the one element (since it's the first round) being
6059 // inserted as undef can be dropped. This isn't safe for successive
6060 // rounds because they will permute elements within both vectors.
6061 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6062 EltStride == NumElems/2)
6065 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6074 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6075 // to create 256-bit vectors from two other 128-bit ones.
6076 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6078 MVT ResVT = Op.getValueType().getSimpleVT();
6080 assert((ResVT.is256BitVector() ||
6081 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6083 SDValue V1 = Op.getOperand(0);
6084 SDValue V2 = Op.getOperand(1);
6085 unsigned NumElems = ResVT.getVectorNumElements();
6086 if(ResVT.is256BitVector())
6087 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6089 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6092 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6093 assert(Op.getNumOperands() == 2);
6095 // AVX/AVX-512 can use the vinsertf128 instruction to create 256-bit vectors
6096 // from two other 128-bit ones.
6097 return LowerAVXCONCAT_VECTORS(Op, DAG);
6100 // Try to lower a shuffle node into a simple blend instruction.
6102 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6103 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6104 SDValue V1 = SVOp->getOperand(0);
6105 SDValue V2 = SVOp->getOperand(1);
6107 MVT VT = SVOp->getValueType(0).getSimpleVT();
6108 MVT EltVT = VT.getVectorElementType();
6109 unsigned NumElems = VT.getVectorNumElements();
6111 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
6113 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
6116 // Check the mask for BLEND and build the value.
6117 unsigned MaskValue = 0;
6118 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6119 unsigned NumLanes = (NumElems-1)/8 + 1;
6120 unsigned NumElemsInLane = NumElems / NumLanes;
6122 // Blend for v16i16 should be symetric for the both lanes.
6123 for (unsigned i = 0; i < NumElemsInLane; ++i) {
6125 int SndLaneEltIdx = (NumLanes == 2) ?
6126 SVOp->getMaskElt(i + NumElemsInLane) : -1;
6127 int EltIdx = SVOp->getMaskElt(i);
6129 if ((EltIdx < 0 || EltIdx == (int)i) &&
6130 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6133 if (((unsigned)EltIdx == (i + NumElems)) &&
6134 (SndLaneEltIdx < 0 ||
6135 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6136 MaskValue |= (1<<i);
6141 // Convert i32 vectors to floating point if it is not AVX2.
6142 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6144 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6145 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6147 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6148 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6151 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6152 DAG.getConstant(MaskValue, MVT::i32));
6153 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6156 // v8i16 shuffles - Prefer shuffles in the following order:
6157 // 1. [all] pshuflw, pshufhw, optional move
6158 // 2. [ssse3] 1 x pshufb
6159 // 3. [ssse3] 2 x pshufb + 1 x por
6160 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6162 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6163 SelectionDAG &DAG) {
6164 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6165 SDValue V1 = SVOp->getOperand(0);
6166 SDValue V2 = SVOp->getOperand(1);
6168 SmallVector<int, 8> MaskVals;
6170 // Determine if more than 1 of the words in each of the low and high quadwords
6171 // of the result come from the same quadword of one of the two inputs. Undef
6172 // mask values count as coming from any quadword, for better codegen.
6173 unsigned LoQuad[] = { 0, 0, 0, 0 };
6174 unsigned HiQuad[] = { 0, 0, 0, 0 };
6175 std::bitset<4> InputQuads;
6176 for (unsigned i = 0; i < 8; ++i) {
6177 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6178 int EltIdx = SVOp->getMaskElt(i);
6179 MaskVals.push_back(EltIdx);
6188 InputQuads.set(EltIdx / 4);
6191 int BestLoQuad = -1;
6192 unsigned MaxQuad = 1;
6193 for (unsigned i = 0; i < 4; ++i) {
6194 if (LoQuad[i] > MaxQuad) {
6196 MaxQuad = LoQuad[i];
6200 int BestHiQuad = -1;
6202 for (unsigned i = 0; i < 4; ++i) {
6203 if (HiQuad[i] > MaxQuad) {
6205 MaxQuad = HiQuad[i];
6209 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6210 // of the two input vectors, shuffle them into one input vector so only a
6211 // single pshufb instruction is necessary. If There are more than 2 input
6212 // quads, disable the next transformation since it does not help SSSE3.
6213 bool V1Used = InputQuads[0] || InputQuads[1];
6214 bool V2Used = InputQuads[2] || InputQuads[3];
6215 if (Subtarget->hasSSSE3()) {
6216 if (InputQuads.count() == 2 && V1Used && V2Used) {
6217 BestLoQuad = InputQuads[0] ? 0 : 1;
6218 BestHiQuad = InputQuads[2] ? 2 : 3;
6220 if (InputQuads.count() > 2) {
6226 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6227 // the shuffle mask. If a quad is scored as -1, that means that it contains
6228 // words from all 4 input quadwords.
6230 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6232 BestLoQuad < 0 ? 0 : BestLoQuad,
6233 BestHiQuad < 0 ? 1 : BestHiQuad
6235 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6236 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6237 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6238 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6240 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6241 // source words for the shuffle, to aid later transformations.
6242 bool AllWordsInNewV = true;
6243 bool InOrder[2] = { true, true };
6244 for (unsigned i = 0; i != 8; ++i) {
6245 int idx = MaskVals[i];
6247 InOrder[i/4] = false;
6248 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6250 AllWordsInNewV = false;
6254 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6255 if (AllWordsInNewV) {
6256 for (int i = 0; i != 8; ++i) {
6257 int idx = MaskVals[i];
6260 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6261 if ((idx != i) && idx < 4)
6263 if ((idx != i) && idx > 3)
6272 // If we've eliminated the use of V2, and the new mask is a pshuflw or
6273 // pshufhw, that's as cheap as it gets. Return the new shuffle.
6274 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6275 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6276 unsigned TargetMask = 0;
6277 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6278 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6279 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6280 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6281 getShufflePSHUFLWImmediate(SVOp);
6282 V1 = NewV.getOperand(0);
6283 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6287 // Promote splats to a larger type which usually leads to more efficient code.
6288 // FIXME: Is this true if pshufb is available?
6289 if (SVOp->isSplat())
6290 return PromoteSplat(SVOp, DAG);
6292 // If we have SSSE3, and all words of the result are from 1 input vector,
6293 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
6294 // is present, fall back to case 4.
6295 if (Subtarget->hasSSSE3()) {
6296 SmallVector<SDValue,16> pshufbMask;
6298 // If we have elements from both input vectors, set the high bit of the
6299 // shuffle mask element to zero out elements that come from V2 in the V1
6300 // mask, and elements that come from V1 in the V2 mask, so that the two
6301 // results can be OR'd together.
6302 bool TwoInputs = V1Used && V2Used;
6303 for (unsigned i = 0; i != 8; ++i) {
6304 int EltIdx = MaskVals[i] * 2;
6305 int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
6306 int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
6307 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
6308 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
6310 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
6311 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6312 DAG.getNode(ISD::BUILD_VECTOR, dl,
6313 MVT::v16i8, &pshufbMask[0], 16));
6315 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6317 // Calculate the shuffle mask for the second input, shuffle it, and
6318 // OR it with the first shuffled input.
6320 for (unsigned i = 0; i != 8; ++i) {
6321 int EltIdx = MaskVals[i] * 2;
6322 int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6323 int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
6324 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
6325 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
6327 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
6328 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6329 DAG.getNode(ISD::BUILD_VECTOR, dl,
6330 MVT::v16i8, &pshufbMask[0], 16));
6331 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6332 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6335 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6336 // and update MaskVals with new element order.
6337 std::bitset<8> InOrder;
6338 if (BestLoQuad >= 0) {
6339 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6340 for (int i = 0; i != 4; ++i) {
6341 int idx = MaskVals[i];
6344 } else if ((idx / 4) == BestLoQuad) {
6349 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6352 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6353 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6354 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6356 getShufflePSHUFLWImmediate(SVOp), DAG);
6360 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6361 // and update MaskVals with the new element order.
6362 if (BestHiQuad >= 0) {
6363 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6364 for (unsigned i = 4; i != 8; ++i) {
6365 int idx = MaskVals[i];
6368 } else if ((idx / 4) == BestHiQuad) {
6369 MaskV[i] = (idx & 3) + 4;
6373 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6376 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6377 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6378 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6380 getShufflePSHUFHWImmediate(SVOp), DAG);
6384 // In case BestHi & BestLo were both -1, which means each quadword has a word
6385 // from each of the four input quadwords, calculate the InOrder bitvector now
6386 // before falling through to the insert/extract cleanup.
6387 if (BestLoQuad == -1 && BestHiQuad == -1) {
6389 for (int i = 0; i != 8; ++i)
6390 if (MaskVals[i] < 0 || MaskVals[i] == i)
6394 // The other elements are put in the right place using pextrw and pinsrw.
6395 for (unsigned i = 0; i != 8; ++i) {
6398 int EltIdx = MaskVals[i];
6401 SDValue ExtOp = (EltIdx < 8) ?
6402 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6403 DAG.getIntPtrConstant(EltIdx)) :
6404 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6405 DAG.getIntPtrConstant(EltIdx - 8));
6406 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6407 DAG.getIntPtrConstant(i));
6412 // v16i8 shuffles - Prefer shuffles in the following order:
6413 // 1. [ssse3] 1 x pshufb
6414 // 2. [ssse3] 2 x pshufb + 1 x por
6415 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
6417 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6419 const X86TargetLowering &TLI) {
6420 SDValue V1 = SVOp->getOperand(0);
6421 SDValue V2 = SVOp->getOperand(1);
6423 ArrayRef<int> MaskVals = SVOp->getMask();
6425 // Promote splats to a larger type which usually leads to more efficient code.
6426 // FIXME: Is this true if pshufb is available?
6427 if (SVOp->isSplat())
6428 return PromoteSplat(SVOp, DAG);
6430 // If we have SSSE3, case 1 is generated when all result bytes come from
6431 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
6432 // present, fall back to case 3.
6434 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6435 if (TLI.getSubtarget()->hasSSSE3()) {
6436 SmallVector<SDValue,16> pshufbMask;
6438 // If all result elements are from one input vector, then only translate
6439 // undef mask values to 0x80 (zero out result) in the pshufb mask.
6441 // Otherwise, we have elements from both input vectors, and must zero out
6442 // elements that come from V2 in the first mask, and V1 in the second mask
6443 // so that we can OR them together.
6444 for (unsigned i = 0; i != 16; ++i) {
6445 int EltIdx = MaskVals[i];
6446 if (EltIdx < 0 || EltIdx >= 16)
6448 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6450 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6451 DAG.getNode(ISD::BUILD_VECTOR, dl,
6452 MVT::v16i8, &pshufbMask[0], 16));
6454 // As PSHUFB will zero elements with negative indices, it's safe to ignore
6455 // the 2nd operand if it's undefined or zero.
6456 if (V2.getOpcode() == ISD::UNDEF ||
6457 ISD::isBuildVectorAllZeros(V2.getNode()))
6460 // Calculate the shuffle mask for the second input, shuffle it, and
6461 // OR it with the first shuffled input.
6463 for (unsigned i = 0; i != 16; ++i) {
6464 int EltIdx = MaskVals[i];
6465 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6466 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6468 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6469 DAG.getNode(ISD::BUILD_VECTOR, dl,
6470 MVT::v16i8, &pshufbMask[0], 16));
6471 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6474 // No SSSE3 - Calculate in place words and then fix all out of place words
6475 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
6476 // the 16 different words that comprise the two doublequadword input vectors.
6477 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6478 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6480 for (int i = 0; i != 8; ++i) {
6481 int Elt0 = MaskVals[i*2];
6482 int Elt1 = MaskVals[i*2+1];
6484 // This word of the result is all undef, skip it.
6485 if (Elt0 < 0 && Elt1 < 0)
6488 // This word of the result is already in the correct place, skip it.
6489 if ((Elt0 == i*2) && (Elt1 == i*2+1))
6492 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6493 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6496 // If Elt0 and Elt1 are defined, are consecutive, and can be load
6497 // using a single extract together, load it and store it.
6498 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6499 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6500 DAG.getIntPtrConstant(Elt1 / 2));
6501 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6502 DAG.getIntPtrConstant(i));
6506 // If Elt1 is defined, extract it from the appropriate source. If the
6507 // source byte is not also odd, shift the extracted word left 8 bits
6508 // otherwise clear the bottom 8 bits if we need to do an or.
6510 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6511 DAG.getIntPtrConstant(Elt1 / 2));
6512 if ((Elt1 & 1) == 0)
6513 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6515 TLI.getShiftAmountTy(InsElt.getValueType())));
6517 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6518 DAG.getConstant(0xFF00, MVT::i16));
6520 // If Elt0 is defined, extract it from the appropriate source. If the
6521 // source byte is not also even, shift the extracted word right 8 bits. If
6522 // Elt1 was also defined, OR the extracted values together before
6523 // inserting them in the result.
6525 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6526 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6527 if ((Elt0 & 1) != 0)
6528 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6530 TLI.getShiftAmountTy(InsElt0.getValueType())));
6532 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6533 DAG.getConstant(0x00FF, MVT::i16));
6534 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6537 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6538 DAG.getIntPtrConstant(i));
6540 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6543 // v32i8 shuffles - Translate to VPSHUFB if possible.
6545 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6546 const X86Subtarget *Subtarget,
6547 SelectionDAG &DAG) {
6548 MVT VT = SVOp->getValueType(0).getSimpleVT();
6549 SDValue V1 = SVOp->getOperand(0);
6550 SDValue V2 = SVOp->getOperand(1);
6552 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6554 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6555 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6556 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6558 // VPSHUFB may be generated if
6559 // (1) one of input vector is undefined or zeroinitializer.
6560 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6561 // And (2) the mask indexes don't cross the 128-bit lane.
6562 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6563 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6566 if (V1IsAllZero && !V2IsAllZero) {
6567 CommuteVectorShuffleMask(MaskVals, 32);
6570 SmallVector<SDValue, 32> pshufbMask;
6571 for (unsigned i = 0; i != 32; i++) {
6572 int EltIdx = MaskVals[i];
6573 if (EltIdx < 0 || EltIdx >= 32)
6576 if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6577 // Cross lane is not allowed.
6581 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6583 return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6584 DAG.getNode(ISD::BUILD_VECTOR, dl,
6585 MVT::v32i8, &pshufbMask[0], 32));
6588 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6589 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6590 /// done when every pair / quad of shuffle mask elements point to elements in
6591 /// the right sequence. e.g.
6592 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6594 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6595 SelectionDAG &DAG) {
6596 MVT VT = SVOp->getValueType(0).getSimpleVT();
6598 unsigned NumElems = VT.getVectorNumElements();
6601 switch (VT.SimpleTy) {
6602 default: llvm_unreachable("Unexpected!");
6603 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
6604 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
6605 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
6606 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
6607 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6608 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
6611 SmallVector<int, 8> MaskVec;
6612 for (unsigned i = 0; i != NumElems; i += Scale) {
6614 for (unsigned j = 0; j != Scale; ++j) {
6615 int EltIdx = SVOp->getMaskElt(i+j);
6619 StartIdx = (EltIdx / Scale);
6620 if (EltIdx != (int)(StartIdx*Scale + j))
6623 MaskVec.push_back(StartIdx);
6626 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6627 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6628 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6631 /// getVZextMovL - Return a zero-extending vector move low node.
6633 static SDValue getVZextMovL(MVT VT, EVT OpVT,
6634 SDValue SrcOp, SelectionDAG &DAG,
6635 const X86Subtarget *Subtarget, SDLoc dl) {
6636 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6637 LoadSDNode *LD = NULL;
6638 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6639 LD = dyn_cast<LoadSDNode>(SrcOp);
6641 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6643 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6644 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6645 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6646 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6647 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6649 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6650 return DAG.getNode(ISD::BITCAST, dl, VT,
6651 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6652 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6660 return DAG.getNode(ISD::BITCAST, dl, VT,
6661 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6662 DAG.getNode(ISD::BITCAST, dl,
6666 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6667 /// which could not be matched by any known target speficic shuffle
6669 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6671 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6672 if (NewOp.getNode())
6675 MVT VT = SVOp->getValueType(0).getSimpleVT();
6677 unsigned NumElems = VT.getVectorNumElements();
6678 unsigned NumLaneElems = NumElems / 2;
6681 MVT EltVT = VT.getVectorElementType();
6682 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6685 SmallVector<int, 16> Mask;
6686 for (unsigned l = 0; l < 2; ++l) {
6687 // Build a shuffle mask for the output, discovering on the fly which
6688 // input vectors to use as shuffle operands (recorded in InputUsed).
6689 // If building a suitable shuffle vector proves too hard, then bail
6690 // out with UseBuildVector set.
6691 bool UseBuildVector = false;
6692 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6693 unsigned LaneStart = l * NumLaneElems;
6694 for (unsigned i = 0; i != NumLaneElems; ++i) {
6695 // The mask element. This indexes into the input.
6696 int Idx = SVOp->getMaskElt(i+LaneStart);
6698 // the mask element does not index into any input vector.
6703 // The input vector this mask element indexes into.
6704 int Input = Idx / NumLaneElems;
6706 // Turn the index into an offset from the start of the input vector.
6707 Idx -= Input * NumLaneElems;
6709 // Find or create a shuffle vector operand to hold this input.
6711 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6712 if (InputUsed[OpNo] == Input)
6713 // This input vector is already an operand.
6715 if (InputUsed[OpNo] < 0) {
6716 // Create a new operand for this input vector.
6717 InputUsed[OpNo] = Input;
6722 if (OpNo >= array_lengthof(InputUsed)) {
6723 // More than two input vectors used! Give up on trying to create a
6724 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
6725 UseBuildVector = true;
6729 // Add the mask index for the new shuffle vector.
6730 Mask.push_back(Idx + OpNo * NumLaneElems);
6733 if (UseBuildVector) {
6734 SmallVector<SDValue, 16> SVOps;
6735 for (unsigned i = 0; i != NumLaneElems; ++i) {
6736 // The mask element. This indexes into the input.
6737 int Idx = SVOp->getMaskElt(i+LaneStart);
6739 SVOps.push_back(DAG.getUNDEF(EltVT));
6743 // The input vector this mask element indexes into.
6744 int Input = Idx / NumElems;
6746 // Turn the index into an offset from the start of the input vector.
6747 Idx -= Input * NumElems;
6749 // Extract the vector element by hand.
6750 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6751 SVOp->getOperand(Input),
6752 DAG.getIntPtrConstant(Idx)));
6755 // Construct the output using a BUILD_VECTOR.
6756 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6758 } else if (InputUsed[0] < 0) {
6759 // No input vectors were used! The result is undefined.
6760 Output[l] = DAG.getUNDEF(NVT);
6762 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6763 (InputUsed[0] % 2) * NumLaneElems,
6765 // If only one input was used, use an undefined vector for the other.
6766 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6767 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6768 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6769 // At least one input vector was used. Create a new shuffle vector.
6770 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6776 // Concatenate the result back
6777 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6780 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6781 /// 4 elements, and match them with several different shuffle types.
6783 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6784 SDValue V1 = SVOp->getOperand(0);
6785 SDValue V2 = SVOp->getOperand(1);
6787 MVT VT = SVOp->getValueType(0).getSimpleVT();
6789 assert(VT.is128BitVector() && "Unsupported vector size");
6791 std::pair<int, int> Locs[4];
6792 int Mask1[] = { -1, -1, -1, -1 };
6793 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6797 for (unsigned i = 0; i != 4; ++i) {
6798 int Idx = PermMask[i];
6800 Locs[i] = std::make_pair(-1, -1);
6802 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6804 Locs[i] = std::make_pair(0, NumLo);
6808 Locs[i] = std::make_pair(1, NumHi);
6810 Mask1[2+NumHi] = Idx;
6816 if (NumLo <= 2 && NumHi <= 2) {
6817 // If no more than two elements come from either vector. This can be
6818 // implemented with two shuffles. First shuffle gather the elements.
6819 // The second shuffle, which takes the first shuffle as both of its
6820 // vector operands, put the elements into the right order.
6821 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6823 int Mask2[] = { -1, -1, -1, -1 };
6825 for (unsigned i = 0; i != 4; ++i)
6826 if (Locs[i].first != -1) {
6827 unsigned Idx = (i < 2) ? 0 : 4;
6828 Idx += Locs[i].first * 2 + Locs[i].second;
6832 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6835 if (NumLo == 3 || NumHi == 3) {
6836 // Otherwise, we must have three elements from one vector, call it X, and
6837 // one element from the other, call it Y. First, use a shufps to build an
6838 // intermediate vector with the one element from Y and the element from X
6839 // that will be in the same half in the final destination (the indexes don't
6840 // matter). Then, use a shufps to build the final vector, taking the half
6841 // containing the element from Y from the intermediate, and the other half
6844 // Normalize it so the 3 elements come from V1.
6845 CommuteVectorShuffleMask(PermMask, 4);
6849 // Find the element from V2.
6851 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6852 int Val = PermMask[HiIndex];
6859 Mask1[0] = PermMask[HiIndex];
6861 Mask1[2] = PermMask[HiIndex^1];
6863 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6866 Mask1[0] = PermMask[0];
6867 Mask1[1] = PermMask[1];
6868 Mask1[2] = HiIndex & 1 ? 6 : 4;
6869 Mask1[3] = HiIndex & 1 ? 4 : 6;
6870 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6873 Mask1[0] = HiIndex & 1 ? 2 : 0;
6874 Mask1[1] = HiIndex & 1 ? 0 : 2;
6875 Mask1[2] = PermMask[2];
6876 Mask1[3] = PermMask[3];
6881 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6884 // Break it into (shuffle shuffle_hi, shuffle_lo).
6885 int LoMask[] = { -1, -1, -1, -1 };
6886 int HiMask[] = { -1, -1, -1, -1 };
6888 int *MaskPtr = LoMask;
6889 unsigned MaskIdx = 0;
6892 for (unsigned i = 0; i != 4; ++i) {
6899 int Idx = PermMask[i];
6901 Locs[i] = std::make_pair(-1, -1);
6902 } else if (Idx < 4) {
6903 Locs[i] = std::make_pair(MaskIdx, LoIdx);
6904 MaskPtr[LoIdx] = Idx;
6907 Locs[i] = std::make_pair(MaskIdx, HiIdx);
6908 MaskPtr[HiIdx] = Idx;
6913 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6914 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6915 int MaskOps[] = { -1, -1, -1, -1 };
6916 for (unsigned i = 0; i != 4; ++i)
6917 if (Locs[i].first != -1)
6918 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6919 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6922 static bool MayFoldVectorLoad(SDValue V) {
6923 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6924 V = V.getOperand(0);
6926 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6927 V = V.getOperand(0);
6928 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6929 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6930 // BUILD_VECTOR (load), undef
6931 V = V.getOperand(0);
6933 return MayFoldLoad(V);
6937 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
6938 EVT VT = Op.getValueType();
6940 // Canonizalize to v2f64.
6941 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6942 return DAG.getNode(ISD::BITCAST, dl, VT,
6943 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6948 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
6950 SDValue V1 = Op.getOperand(0);
6951 SDValue V2 = Op.getOperand(1);
6952 EVT VT = Op.getValueType();
6954 assert(VT != MVT::v2i64 && "unsupported shuffle type");
6956 if (HasSSE2 && VT == MVT::v2f64)
6957 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6959 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6960 return DAG.getNode(ISD::BITCAST, dl, VT,
6961 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6962 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6963 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6967 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
6968 SDValue V1 = Op.getOperand(0);
6969 SDValue V2 = Op.getOperand(1);
6970 EVT VT = Op.getValueType();
6972 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6973 "unsupported shuffle type");
6975 if (V2.getOpcode() == ISD::UNDEF)
6979 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6983 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6984 SDValue V1 = Op.getOperand(0);
6985 SDValue V2 = Op.getOperand(1);
6986 EVT VT = Op.getValueType();
6987 unsigned NumElems = VT.getVectorNumElements();
6989 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6990 // operand of these instructions is only memory, so check if there's a
6991 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6993 bool CanFoldLoad = false;
6995 // Trivial case, when V2 comes from a load.
6996 if (MayFoldVectorLoad(V2))
6999 // When V1 is a load, it can be folded later into a store in isel, example:
7000 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7002 // (MOVLPSmr addr:$src1, VR128:$src2)
7003 // So, recognize this potential and also use MOVLPS or MOVLPD
7004 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7007 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7009 if (HasSSE2 && NumElems == 2)
7010 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7013 // If we don't care about the second element, proceed to use movss.
7014 if (SVOp->getMaskElt(1) != -1)
7015 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7018 // movl and movlp will both match v2i64, but v2i64 is never matched by
7019 // movl earlier because we make it strict to avoid messing with the movlp load
7020 // folding logic (see the code above getMOVLP call). Match it here then,
7021 // this is horrible, but will stay like this until we move all shuffle
7022 // matching to x86 specific nodes. Note that for the 1st condition all
7023 // types are matched with movsd.
7025 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7026 // as to remove this logic from here, as much as possible
7027 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7028 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7029 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7032 assert(VT != MVT::v4i32 && "unsupported shuffle type");
7034 // Invert the operand order and use SHUFPS to match it.
7035 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7036 getShuffleSHUFImmediate(SVOp), DAG);
7039 // Reduce a vector shuffle to zext.
7041 X86TargetLowering::LowerVectorIntExtend(SDValue Op, SelectionDAG &DAG) const {
7042 // PMOVZX is only available from SSE41.
7043 if (!Subtarget->hasSSE41())
7046 EVT VT = Op.getValueType();
7048 // Only AVX2 support 256-bit vector integer extending.
7049 if (!Subtarget->hasInt256() && VT.is256BitVector())
7052 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7054 SDValue V1 = Op.getOperand(0);
7055 SDValue V2 = Op.getOperand(1);
7056 unsigned NumElems = VT.getVectorNumElements();
7058 // Extending is an unary operation and the element type of the source vector
7059 // won't be equal to or larger than i64.
7060 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7061 VT.getVectorElementType() == MVT::i64)
7064 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7065 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7066 while ((1U << Shift) < NumElems) {
7067 if (SVOp->getMaskElt(1U << Shift) == 1)
7070 // The maximal ratio is 8, i.e. from i8 to i64.
7075 // Check the shuffle mask.
7076 unsigned Mask = (1U << Shift) - 1;
7077 for (unsigned i = 0; i != NumElems; ++i) {
7078 int EltIdx = SVOp->getMaskElt(i);
7079 if ((i & Mask) != 0 && EltIdx != -1)
7081 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7085 LLVMContext *Context = DAG.getContext();
7086 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7087 EVT NeVT = EVT::getIntegerVT(*Context, NBits);
7088 EVT NVT = EVT::getVectorVT(*Context, NeVT, NumElems >> Shift);
7090 if (!isTypeLegal(NVT))
7093 // Simplify the operand as it's prepared to be fed into shuffle.
7094 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7095 if (V1.getOpcode() == ISD::BITCAST &&
7096 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7097 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7099 .getOperand(0).getValueType().getSizeInBits() == SignificantBits) {
7100 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7101 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7102 ConstantSDNode *CIdx =
7103 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7104 // If it's foldable, i.e. normal load with single use, we will let code
7105 // selection to fold it. Otherwise, we will short the conversion sequence.
7106 if (CIdx && CIdx->getZExtValue() == 0 &&
7107 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7108 if (V.getValueSizeInBits() > V1.getValueSizeInBits()) {
7109 // The "ext_vec_elt" node is wider than the result node.
7110 // In this case we should extract subvector from V.
7111 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7112 unsigned Ratio = V.getValueSizeInBits() / V1.getValueSizeInBits();
7113 EVT FullVT = V.getValueType();
7114 EVT SubVecVT = EVT::getVectorVT(*Context,
7115 FullVT.getVectorElementType(),
7116 FullVT.getVectorNumElements()/Ratio);
7117 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7118 DAG.getIntPtrConstant(0));
7120 V1 = DAG.getNode(ISD::BITCAST, DL, V1.getValueType(), V);
7124 return DAG.getNode(ISD::BITCAST, DL, VT,
7125 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7129 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
7130 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7131 MVT VT = Op.getValueType().getSimpleVT();
7133 SDValue V1 = Op.getOperand(0);
7134 SDValue V2 = Op.getOperand(1);
7136 if (isZeroShuffle(SVOp))
7137 return getZeroVector(VT, Subtarget, DAG, dl);
7139 // Handle splat operations
7140 if (SVOp->isSplat()) {
7141 // Use vbroadcast whenever the splat comes from a foldable load
7142 SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
7143 if (Broadcast.getNode())
7147 // Check integer expanding shuffles.
7148 SDValue NewOp = LowerVectorIntExtend(Op, DAG);
7149 if (NewOp.getNode())
7152 // If the shuffle can be profitably rewritten as a narrower shuffle, then
7154 if (VT == MVT::v8i16 || VT == MVT::v16i8 ||
7155 VT == MVT::v16i16 || VT == MVT::v32i8) {
7156 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7157 if (NewOp.getNode())
7158 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7159 } else if ((VT == MVT::v4i32 ||
7160 (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
7161 // FIXME: Figure out a cleaner way to do this.
7162 // Try to make use of movq to zero out the top part.
7163 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7164 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7165 if (NewOp.getNode()) {
7166 MVT NewVT = NewOp.getValueType().getSimpleVT();
7167 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7168 NewVT, true, false))
7169 return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
7170 DAG, Subtarget, dl);
7172 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7173 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7174 if (NewOp.getNode()) {
7175 MVT NewVT = NewOp.getValueType().getSimpleVT();
7176 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7177 return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
7178 DAG, Subtarget, dl);
7186 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7187 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7188 SDValue V1 = Op.getOperand(0);
7189 SDValue V2 = Op.getOperand(1);
7190 MVT VT = Op.getValueType().getSimpleVT();
7192 unsigned NumElems = VT.getVectorNumElements();
7193 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7194 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7195 bool V1IsSplat = false;
7196 bool V2IsSplat = false;
7197 bool HasSSE2 = Subtarget->hasSSE2();
7198 bool HasFp256 = Subtarget->hasFp256();
7199 bool HasInt256 = Subtarget->hasInt256();
7200 MachineFunction &MF = DAG.getMachineFunction();
7201 bool OptForSize = MF.getFunction()->getAttributes().
7202 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7204 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7206 if (V1IsUndef && V2IsUndef)
7207 return DAG.getUNDEF(VT);
7209 assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
7211 // Vector shuffle lowering takes 3 steps:
7213 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7214 // narrowing and commutation of operands should be handled.
7215 // 2) Matching of shuffles with known shuffle masks to x86 target specific
7217 // 3) Rewriting of unmatched masks into new generic shuffle operations,
7218 // so the shuffle can be broken into other shuffles and the legalizer can
7219 // try the lowering again.
7221 // The general idea is that no vector_shuffle operation should be left to
7222 // be matched during isel, all of them must be converted to a target specific
7225 // Normalize the input vectors. Here splats, zeroed vectors, profitable
7226 // narrowing and commutation of operands should be handled. The actual code
7227 // doesn't include all of those, work in progress...
7228 SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
7229 if (NewOp.getNode())
7232 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7234 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7235 // unpckh_undef). Only use pshufd if speed is more important than size.
7236 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7237 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7238 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7239 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7241 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7242 V2IsUndef && MayFoldVectorLoad(V1))
7243 return getMOVDDup(Op, dl, V1, DAG);
7245 if (isMOVHLPS_v_undef_Mask(M, VT))
7246 return getMOVHighToLow(Op, dl, DAG);
7248 // Use to match splats
7249 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7250 (VT == MVT::v2f64 || VT == MVT::v2i64))
7251 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7253 if (isPSHUFDMask(M, VT)) {
7254 // The actual implementation will match the mask in the if above and then
7255 // during isel it can match several different instructions, not only pshufd
7256 // as its name says, sad but true, emulate the behavior for now...
7257 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7258 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7260 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7262 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7263 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7265 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7266 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7269 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7273 if (isPALIGNRMask(M, VT, Subtarget))
7274 return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7275 getShufflePALIGNRImmediate(SVOp),
7278 // Check if this can be converted into a logical shift.
7279 bool isLeft = false;
7282 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7283 if (isShift && ShVal.hasOneUse()) {
7284 // If the shifted value has multiple uses, it may be cheaper to use
7285 // v_set0 + movlhps or movhlps, etc.
7286 MVT EltVT = VT.getVectorElementType();
7287 ShAmt *= EltVT.getSizeInBits();
7288 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7291 if (isMOVLMask(M, VT)) {
7292 if (ISD::isBuildVectorAllZeros(V1.getNode()))
7293 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7294 if (!isMOVLPMask(M, VT)) {
7295 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7296 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7298 if (VT == MVT::v4i32 || VT == MVT::v4f32)
7299 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7303 // FIXME: fold these into legal mask.
7304 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7305 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7307 if (isMOVHLPSMask(M, VT))
7308 return getMOVHighToLow(Op, dl, DAG);
7310 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7311 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7313 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7314 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7316 if (isMOVLPMask(M, VT))
7317 return getMOVLP(Op, dl, DAG, HasSSE2);
7319 if (ShouldXformToMOVHLPS(M, VT) ||
7320 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7321 return CommuteVectorShuffle(SVOp, DAG);
7324 // No better options. Use a vshldq / vsrldq.
7325 MVT EltVT = VT.getVectorElementType();
7326 ShAmt *= EltVT.getSizeInBits();
7327 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7330 bool Commuted = false;
7331 // FIXME: This should also accept a bitcast of a splat? Be careful, not
7332 // 1,1,1,1 -> v8i16 though.
7333 V1IsSplat = isSplatVector(V1.getNode());
7334 V2IsSplat = isSplatVector(V2.getNode());
7336 // Canonicalize the splat or undef, if present, to be on the RHS.
7337 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7338 CommuteVectorShuffleMask(M, NumElems);
7340 std::swap(V1IsSplat, V2IsSplat);
7344 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7345 // Shuffling low element of v1 into undef, just return v1.
7348 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7349 // the instruction selector will not match, so get a canonical MOVL with
7350 // swapped operands to undo the commute.
7351 return getMOVL(DAG, dl, VT, V2, V1);
7354 if (isUNPCKLMask(M, VT, HasInt256))
7355 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7357 if (isUNPCKHMask(M, VT, HasInt256))
7358 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7361 // Normalize mask so all entries that point to V2 points to its first
7362 // element then try to match unpck{h|l} again. If match, return a
7363 // new vector_shuffle with the corrected mask.p
7364 SmallVector<int, 8> NewMask(M.begin(), M.end());
7365 NormalizeMask(NewMask, NumElems);
7366 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7367 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7368 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7369 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7373 // Commute is back and try unpck* again.
7374 // FIXME: this seems wrong.
7375 CommuteVectorShuffleMask(M, NumElems);
7377 std::swap(V1IsSplat, V2IsSplat);
7380 if (isUNPCKLMask(M, VT, HasInt256))
7381 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7383 if (isUNPCKHMask(M, VT, HasInt256))
7384 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7387 // Normalize the node to match x86 shuffle ops if needed
7388 if (!V2IsUndef && (isSHUFPMask(M, VT, HasFp256, /* Commuted */ true)))
7389 return CommuteVectorShuffle(SVOp, DAG);
7391 // The checks below are all present in isShuffleMaskLegal, but they are
7392 // inlined here right now to enable us to directly emit target specific
7393 // nodes, and remove one by one until they don't return Op anymore.
7395 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7396 SVOp->getSplatIndex() == 0 && V2IsUndef) {
7397 if (VT == MVT::v2f64 || VT == MVT::v2i64)
7398 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7401 if (isPSHUFHWMask(M, VT, HasInt256))
7402 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7403 getShufflePSHUFHWImmediate(SVOp),
7406 if (isPSHUFLWMask(M, VT, HasInt256))
7407 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7408 getShufflePSHUFLWImmediate(SVOp),
7411 if (isSHUFPMask(M, VT, HasFp256))
7412 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7413 getShuffleSHUFImmediate(SVOp), DAG);
7415 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7416 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7417 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7418 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7420 //===--------------------------------------------------------------------===//
7421 // Generate target specific nodes for 128 or 256-bit shuffles only
7422 // supported in the AVX instruction set.
7425 // Handle VMOVDDUPY permutations
7426 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7427 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7429 // Handle VPERMILPS/D* permutations
7430 if (isVPERMILPMask(M, VT, HasFp256)) {
7431 if (HasInt256 && VT == MVT::v8i32)
7432 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7433 getShuffleSHUFImmediate(SVOp), DAG);
7434 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7435 getShuffleSHUFImmediate(SVOp), DAG);
7438 // Handle VPERM2F128/VPERM2I128 permutations
7439 if (isVPERM2X128Mask(M, VT, HasFp256))
7440 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7441 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7443 SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7444 if (BlendOp.getNode())
7448 if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
7449 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
7451 if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
7452 VT.is512BitVector()) {
7453 EVT MaskEltVT = EVT::getIntegerVT(*DAG.getContext(),
7454 VT.getVectorElementType().getSizeInBits());
7456 EVT::getVectorVT(*DAG.getContext(),MaskEltVT, NumElems);
7457 SmallVector<SDValue, 16> permclMask;
7458 for (unsigned i = 0; i != NumElems; ++i) {
7459 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
7462 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT,
7463 &permclMask[0], NumElems);
7465 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7466 return DAG.getNode(X86ISD::VPERMV, dl, VT,
7467 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7468 return DAG.getNode(X86ISD::VPERMV3, dl, VT,
7469 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1, V2);
7472 //===--------------------------------------------------------------------===//
7473 // Since no target specific shuffle was selected for this generic one,
7474 // lower it into other known shuffles. FIXME: this isn't true yet, but
7475 // this is the plan.
7478 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7479 if (VT == MVT::v8i16) {
7480 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7481 if (NewOp.getNode())
7485 if (VT == MVT::v16i8) {
7486 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
7487 if (NewOp.getNode())
7491 if (VT == MVT::v32i8) {
7492 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7493 if (NewOp.getNode())
7497 // Handle all 128-bit wide vectors with 4 elements, and match them with
7498 // several different shuffle types.
7499 if (NumElems == 4 && VT.is128BitVector())
7500 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7502 // Handle general 256-bit shuffles
7503 if (VT.is256BitVector())
7504 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7509 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7510 MVT VT = Op.getValueType().getSimpleVT();
7513 if (!Op.getOperand(0).getValueType().getSimpleVT().is128BitVector())
7516 if (VT.getSizeInBits() == 8) {
7517 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7518 Op.getOperand(0), Op.getOperand(1));
7519 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7520 DAG.getValueType(VT));
7521 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7524 if (VT.getSizeInBits() == 16) {
7525 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7526 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7528 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7529 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7530 DAG.getNode(ISD::BITCAST, dl,
7534 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7535 Op.getOperand(0), Op.getOperand(1));
7536 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7537 DAG.getValueType(VT));
7538 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7541 if (VT == MVT::f32) {
7542 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7543 // the result back to FR32 register. It's only worth matching if the
7544 // result has a single use which is a store or a bitcast to i32. And in
7545 // the case of a store, it's not worth it if the index is a constant 0,
7546 // because a MOVSSmr can be used instead, which is smaller and faster.
7547 if (!Op.hasOneUse())
7549 SDNode *User = *Op.getNode()->use_begin();
7550 if ((User->getOpcode() != ISD::STORE ||
7551 (isa<ConstantSDNode>(Op.getOperand(1)) &&
7552 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7553 (User->getOpcode() != ISD::BITCAST ||
7554 User->getValueType(0) != MVT::i32))
7556 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7557 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7560 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7563 if (VT == MVT::i32 || VT == MVT::i64) {
7564 // ExtractPS/pextrq works with constant index.
7565 if (isa<ConstantSDNode>(Op.getOperand(1)))
7572 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7573 SelectionDAG &DAG) const {
7575 if (!isa<ConstantSDNode>(Op.getOperand(1)))
7578 SDValue Vec = Op.getOperand(0);
7579 MVT VecVT = Vec.getValueType().getSimpleVT();
7581 // If this is a 256-bit vector result, first extract the 128-bit vector and
7582 // then extract the element from the 128-bit vector.
7583 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
7584 SDValue Idx = Op.getOperand(1);
7585 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7587 // Get the 128-bit vector.
7588 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7589 EVT EltVT = VecVT.getVectorElementType();
7591 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
7593 //if (IdxVal >= NumElems/2)
7594 // IdxVal -= NumElems/2;
7595 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
7596 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7597 DAG.getConstant(IdxVal, MVT::i32));
7600 assert(VecVT.is128BitVector() && "Unexpected vector length");
7602 if (Subtarget->hasSSE41()) {
7603 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7608 MVT VT = Op.getValueType().getSimpleVT();
7609 // TODO: handle v16i8.
7610 if (VT.getSizeInBits() == 16) {
7611 SDValue Vec = Op.getOperand(0);
7612 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7614 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7615 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7616 DAG.getNode(ISD::BITCAST, dl,
7619 // Transform it so it match pextrw which produces a 32-bit result.
7620 MVT EltVT = MVT::i32;
7621 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7622 Op.getOperand(0), Op.getOperand(1));
7623 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7624 DAG.getValueType(VT));
7625 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7628 if (VT.getSizeInBits() == 32) {
7629 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7633 // SHUFPS the element to the lowest double word, then movss.
7634 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7635 MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7636 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7637 DAG.getUNDEF(VVT), Mask);
7638 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7639 DAG.getIntPtrConstant(0));
7642 if (VT.getSizeInBits() == 64) {
7643 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7644 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7645 // to match extract_elt for f64.
7646 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7650 // UNPCKHPD the element to the lowest double word, then movsd.
7651 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7652 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7653 int Mask[2] = { 1, -1 };
7654 MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7655 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7656 DAG.getUNDEF(VVT), Mask);
7657 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7658 DAG.getIntPtrConstant(0));
7664 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7665 MVT VT = Op.getValueType().getSimpleVT();
7666 MVT EltVT = VT.getVectorElementType();
7669 SDValue N0 = Op.getOperand(0);
7670 SDValue N1 = Op.getOperand(1);
7671 SDValue N2 = Op.getOperand(2);
7673 if (!VT.is128BitVector())
7676 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7677 isa<ConstantSDNode>(N2)) {
7679 if (VT == MVT::v8i16)
7680 Opc = X86ISD::PINSRW;
7681 else if (VT == MVT::v16i8)
7682 Opc = X86ISD::PINSRB;
7684 Opc = X86ISD::PINSRB;
7686 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7688 if (N1.getValueType() != MVT::i32)
7689 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7690 if (N2.getValueType() != MVT::i32)
7691 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7692 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7695 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7696 // Bits [7:6] of the constant are the source select. This will always be
7697 // zero here. The DAG Combiner may combine an extract_elt index into these
7698 // bits. For example (insert (extract, 3), 2) could be matched by putting
7699 // the '3' into bits [7:6] of X86ISD::INSERTPS.
7700 // Bits [5:4] of the constant are the destination select. This is the
7701 // value of the incoming immediate.
7702 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
7703 // combine either bitwise AND or insert of float 0.0 to set these bits.
7704 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7705 // Create this as a scalar to vector..
7706 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7707 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7710 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7711 // PINSR* works with constant index.
7718 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7719 MVT VT = Op.getValueType().getSimpleVT();
7720 MVT EltVT = VT.getVectorElementType();
7723 SDValue N0 = Op.getOperand(0);
7724 SDValue N1 = Op.getOperand(1);
7725 SDValue N2 = Op.getOperand(2);
7727 // If this is a 256-bit vector result, first extract the 128-bit vector,
7728 // insert the element into the extracted half and then place it back.
7729 if (VT.is256BitVector() || VT.is512BitVector()) {
7730 if (!isa<ConstantSDNode>(N2))
7733 // Get the desired 128-bit vector half.
7734 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7735 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7737 // Insert the element into the desired half.
7738 unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
7739 unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
7741 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7742 DAG.getConstant(IdxIn128, MVT::i32));
7744 // Insert the changed part back to the 256-bit vector
7745 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7748 if (Subtarget->hasSSE41())
7749 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7751 if (EltVT == MVT::i8)
7754 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7755 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7756 // as its second argument.
7757 if (N1.getValueType() != MVT::i32)
7758 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7759 if (N2.getValueType() != MVT::i32)
7760 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7761 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7766 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7767 LLVMContext *Context = DAG.getContext();
7769 MVT OpVT = Op.getValueType().getSimpleVT();
7771 // If this is a 256-bit vector result, first insert into a 128-bit
7772 // vector and then insert into the 256-bit vector.
7773 if (!OpVT.is128BitVector()) {
7774 // Insert into a 128-bit vector.
7775 unsigned SizeFactor = OpVT.getSizeInBits()/128;
7776 EVT VT128 = EVT::getVectorVT(*Context,
7777 OpVT.getVectorElementType(),
7778 OpVT.getVectorNumElements() / SizeFactor);
7780 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7782 // Insert the 128-bit vector.
7783 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7786 if (OpVT == MVT::v1i64 &&
7787 Op.getOperand(0).getValueType() == MVT::i64)
7788 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7790 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7791 assert(OpVT.is128BitVector() && "Expected an SSE type!");
7792 return DAG.getNode(ISD::BITCAST, dl, OpVT,
7793 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7796 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
7797 // a simple subregister reference or explicit instructions to grab
7798 // upper bits of a vector.
7799 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7800 SelectionDAG &DAG) {
7802 SDValue In = Op.getOperand(0);
7803 SDValue Idx = Op.getOperand(1);
7804 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7805 EVT ResVT = Op.getValueType();
7806 EVT InVT = In.getValueType();
7808 if (Subtarget->hasFp256()) {
7809 if (ResVT.is128BitVector() &&
7810 (InVT.is256BitVector() || InVT.is512BitVector()) &&
7811 isa<ConstantSDNode>(Idx)) {
7812 return Extract128BitVector(In, IdxVal, DAG, dl);
7814 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
7815 isa<ConstantSDNode>(Idx)) {
7816 return Extract256BitVector(In, IdxVal, DAG, dl);
7822 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
7823 // simple superregister reference or explicit instructions to insert
7824 // the upper bits of a vector.
7825 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7826 SelectionDAG &DAG) {
7827 if (Subtarget->hasFp256()) {
7828 SDLoc dl(Op.getNode());
7829 SDValue Vec = Op.getNode()->getOperand(0);
7830 SDValue SubVec = Op.getNode()->getOperand(1);
7831 SDValue Idx = Op.getNode()->getOperand(2);
7833 if ((Op.getNode()->getValueType(0).is256BitVector() ||
7834 Op.getNode()->getValueType(0).is512BitVector()) &&
7835 SubVec.getNode()->getValueType(0).is128BitVector() &&
7836 isa<ConstantSDNode>(Idx)) {
7837 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7838 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7841 if (Op.getNode()->getValueType(0).is512BitVector() &&
7842 SubVec.getNode()->getValueType(0).is256BitVector() &&
7843 isa<ConstantSDNode>(Idx)) {
7844 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7845 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
7851 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7852 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7853 // one of the above mentioned nodes. It has to be wrapped because otherwise
7854 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7855 // be used to form addressing mode. These wrapped nodes will be selected
7858 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7859 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7861 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7863 unsigned char OpFlag = 0;
7864 unsigned WrapperKind = X86ISD::Wrapper;
7865 CodeModel::Model M = getTargetMachine().getCodeModel();
7867 if (Subtarget->isPICStyleRIPRel() &&
7868 (M == CodeModel::Small || M == CodeModel::Kernel))
7869 WrapperKind = X86ISD::WrapperRIP;
7870 else if (Subtarget->isPICStyleGOT())
7871 OpFlag = X86II::MO_GOTOFF;
7872 else if (Subtarget->isPICStyleStubPIC())
7873 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7875 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7877 CP->getOffset(), OpFlag);
7879 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7880 // With PIC, the address is actually $g + Offset.
7882 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7883 DAG.getNode(X86ISD::GlobalBaseReg,
7884 SDLoc(), getPointerTy()),
7891 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7892 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7894 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7896 unsigned char OpFlag = 0;
7897 unsigned WrapperKind = X86ISD::Wrapper;
7898 CodeModel::Model M = getTargetMachine().getCodeModel();
7900 if (Subtarget->isPICStyleRIPRel() &&
7901 (M == CodeModel::Small || M == CodeModel::Kernel))
7902 WrapperKind = X86ISD::WrapperRIP;
7903 else if (Subtarget->isPICStyleGOT())
7904 OpFlag = X86II::MO_GOTOFF;
7905 else if (Subtarget->isPICStyleStubPIC())
7906 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7908 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7911 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7913 // With PIC, the address is actually $g + Offset.
7915 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7916 DAG.getNode(X86ISD::GlobalBaseReg,
7917 SDLoc(), getPointerTy()),
7924 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7925 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7927 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7929 unsigned char OpFlag = 0;
7930 unsigned WrapperKind = X86ISD::Wrapper;
7931 CodeModel::Model M = getTargetMachine().getCodeModel();
7933 if (Subtarget->isPICStyleRIPRel() &&
7934 (M == CodeModel::Small || M == CodeModel::Kernel)) {
7935 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7936 OpFlag = X86II::MO_GOTPCREL;
7937 WrapperKind = X86ISD::WrapperRIP;
7938 } else if (Subtarget->isPICStyleGOT()) {
7939 OpFlag = X86II::MO_GOT;
7940 } else if (Subtarget->isPICStyleStubPIC()) {
7941 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7942 } else if (Subtarget->isPICStyleStubNoDynamic()) {
7943 OpFlag = X86II::MO_DARWIN_NONLAZY;
7946 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7949 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7951 // With PIC, the address is actually $g + Offset.
7952 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7953 !Subtarget->is64Bit()) {
7954 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7955 DAG.getNode(X86ISD::GlobalBaseReg,
7956 SDLoc(), getPointerTy()),
7960 // For symbols that require a load from a stub to get the address, emit the
7962 if (isGlobalStubReference(OpFlag))
7963 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7964 MachinePointerInfo::getGOT(), false, false, false, 0);
7970 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7971 // Create the TargetBlockAddressAddress node.
7972 unsigned char OpFlags =
7973 Subtarget->ClassifyBlockAddressReference();
7974 CodeModel::Model M = getTargetMachine().getCodeModel();
7975 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7976 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7978 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7981 if (Subtarget->isPICStyleRIPRel() &&
7982 (M == CodeModel::Small || M == CodeModel::Kernel))
7983 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7985 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7987 // With PIC, the address is actually $g + Offset.
7988 if (isGlobalRelativeToPICBase(OpFlags)) {
7989 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7990 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7998 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
7999 int64_t Offset, SelectionDAG &DAG) const {
8000 // Create the TargetGlobalAddress node, folding in the constant
8001 // offset if it is legal.
8002 unsigned char OpFlags =
8003 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
8004 CodeModel::Model M = getTargetMachine().getCodeModel();
8006 if (OpFlags == X86II::MO_NO_FLAG &&
8007 X86::isOffsetSuitableForCodeModel(Offset, M)) {
8008 // A direct static reference to a global.
8009 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8012 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8015 if (Subtarget->isPICStyleRIPRel() &&
8016 (M == CodeModel::Small || M == CodeModel::Kernel))
8017 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8019 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8021 // With PIC, the address is actually $g + Offset.
8022 if (isGlobalRelativeToPICBase(OpFlags)) {
8023 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8024 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8028 // For globals that require a load from a stub to get the address, emit the
8030 if (isGlobalStubReference(OpFlags))
8031 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8032 MachinePointerInfo::getGOT(), false, false, false, 0);
8034 // If there was a non-zero offset that we didn't fold, create an explicit
8037 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8038 DAG.getConstant(Offset, getPointerTy()));
8044 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8045 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8046 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8047 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8051 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8052 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8053 unsigned char OperandFlags, bool LocalDynamic = false) {
8054 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8055 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8057 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8058 GA->getValueType(0),
8062 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8066 SDValue Ops[] = { Chain, TGA, *InFlag };
8067 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8069 SDValue Ops[] = { Chain, TGA };
8070 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8073 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8074 MFI->setAdjustsStack(true);
8076 SDValue Flag = Chain.getValue(1);
8077 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8080 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8082 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8085 SDLoc dl(GA); // ? function entry point might be better
8086 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8087 DAG.getNode(X86ISD::GlobalBaseReg,
8088 SDLoc(), PtrVT), InFlag);
8089 InFlag = Chain.getValue(1);
8091 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8094 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8096 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8098 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
8099 X86::RAX, X86II::MO_TLSGD);
8102 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8108 // Get the start address of the TLS block for this module.
8109 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8110 .getInfo<X86MachineFunctionInfo>();
8111 MFI->incNumLocalDynamicTLSAccesses();
8115 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
8116 X86II::MO_TLSLD, /*LocalDynamic=*/true);
8119 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8120 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8121 InFlag = Chain.getValue(1);
8122 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8123 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8126 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8130 unsigned char OperandFlags = X86II::MO_DTPOFF;
8131 unsigned WrapperKind = X86ISD::Wrapper;
8132 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8133 GA->getValueType(0),
8134 GA->getOffset(), OperandFlags);
8135 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8137 // Add x@dtpoff with the base.
8138 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8141 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8142 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8143 const EVT PtrVT, TLSModel::Model model,
8144 bool is64Bit, bool isPIC) {
8147 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8148 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8149 is64Bit ? 257 : 256));
8151 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
8152 DAG.getIntPtrConstant(0),
8153 MachinePointerInfo(Ptr),
8154 false, false, false, 0);
8156 unsigned char OperandFlags = 0;
8157 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
8159 unsigned WrapperKind = X86ISD::Wrapper;
8160 if (model == TLSModel::LocalExec) {
8161 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8162 } else if (model == TLSModel::InitialExec) {
8164 OperandFlags = X86II::MO_GOTTPOFF;
8165 WrapperKind = X86ISD::WrapperRIP;
8167 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8170 llvm_unreachable("Unexpected model");
8173 // emit "addl x@ntpoff,%eax" (local exec)
8174 // or "addl x@indntpoff,%eax" (initial exec)
8175 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8176 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8177 GA->getValueType(0),
8178 GA->getOffset(), OperandFlags);
8179 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8181 if (model == TLSModel::InitialExec) {
8182 if (isPIC && !is64Bit) {
8183 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8184 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8188 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8189 MachinePointerInfo::getGOT(), false, false, false,
8193 // The address of the thread local variable is the add of the thread
8194 // pointer with the offset of the variable.
8195 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8199 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8201 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8202 const GlobalValue *GV = GA->getGlobal();
8204 if (Subtarget->isTargetELF()) {
8205 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8208 case TLSModel::GeneralDynamic:
8209 if (Subtarget->is64Bit())
8210 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8211 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8212 case TLSModel::LocalDynamic:
8213 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8214 Subtarget->is64Bit());
8215 case TLSModel::InitialExec:
8216 case TLSModel::LocalExec:
8217 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8218 Subtarget->is64Bit(),
8219 getTargetMachine().getRelocationModel() == Reloc::PIC_);
8221 llvm_unreachable("Unknown TLS model.");
8224 if (Subtarget->isTargetDarwin()) {
8225 // Darwin only has one model of TLS. Lower to that.
8226 unsigned char OpFlag = 0;
8227 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8228 X86ISD::WrapperRIP : X86ISD::Wrapper;
8230 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8232 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8233 !Subtarget->is64Bit();
8235 OpFlag = X86II::MO_TLVP_PIC_BASE;
8237 OpFlag = X86II::MO_TLVP;
8239 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8240 GA->getValueType(0),
8241 GA->getOffset(), OpFlag);
8242 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8244 // With PIC32, the address is actually $g + Offset.
8246 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8247 DAG.getNode(X86ISD::GlobalBaseReg,
8248 SDLoc(), getPointerTy()),
8251 // Lowering the machine isd will make sure everything is in the right
8253 SDValue Chain = DAG.getEntryNode();
8254 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8255 SDValue Args[] = { Chain, Offset };
8256 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
8258 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8259 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8260 MFI->setAdjustsStack(true);
8262 // And our return value (tls address) is in the standard call return value
8264 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8265 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8269 if (Subtarget->isTargetWindows() || Subtarget->isTargetMingw()) {
8270 // Just use the implicit TLS architecture
8271 // Need to generate someting similar to:
8272 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8274 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
8275 // mov rcx, qword [rdx+rcx*8]
8276 // mov eax, .tls$:tlsvar
8277 // [rax+rcx] contains the address
8278 // Windows 64bit: gs:0x58
8279 // Windows 32bit: fs:__tls_array
8281 // If GV is an alias then use the aliasee for determining
8282 // thread-localness.
8283 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
8284 GV = GA->resolveAliasedGlobal(false);
8286 SDValue Chain = DAG.getEntryNode();
8288 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8289 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8290 // use its literal value of 0x2C.
8291 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8292 ? Type::getInt8PtrTy(*DAG.getContext(),
8294 : Type::getInt32PtrTy(*DAG.getContext(),
8297 SDValue TlsArray = Subtarget->is64Bit() ? DAG.getIntPtrConstant(0x58) :
8298 (Subtarget->isTargetMingw() ? DAG.getIntPtrConstant(0x2C) :
8299 DAG.getExternalSymbol("_tls_array", getPointerTy()));
8301 SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8302 MachinePointerInfo(Ptr),
8303 false, false, false, 0);
8305 // Load the _tls_index variable
8306 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8307 if (Subtarget->is64Bit())
8308 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8309 IDX, MachinePointerInfo(), MVT::i32,
8312 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
8313 false, false, false, 0);
8315 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
8317 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
8319 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
8320 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
8321 false, false, false, 0);
8323 // Get the offset of start of .tls section
8324 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8325 GA->getValueType(0),
8326 GA->getOffset(), X86II::MO_SECREL);
8327 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
8329 // The address of the thread local variable is the add of the thread
8330 // pointer with the offset of the variable.
8331 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
8334 llvm_unreachable("TLS not implemented for this target.");
8337 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
8338 /// and take a 2 x i32 value to shift plus a shift amount.
8339 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
8340 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
8341 EVT VT = Op.getValueType();
8342 unsigned VTBits = VT.getSizeInBits();
8344 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
8345 SDValue ShOpLo = Op.getOperand(0);
8346 SDValue ShOpHi = Op.getOperand(1);
8347 SDValue ShAmt = Op.getOperand(2);
8348 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
8349 DAG.getConstant(VTBits - 1, MVT::i8))
8350 : DAG.getConstant(0, VT);
8353 if (Op.getOpcode() == ISD::SHL_PARTS) {
8354 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
8355 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
8357 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
8358 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
8361 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8362 DAG.getConstant(VTBits, MVT::i8));
8363 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8364 AndNode, DAG.getConstant(0, MVT::i8));
8367 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8368 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
8369 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
8371 if (Op.getOpcode() == ISD::SHL_PARTS) {
8372 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8373 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8375 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8376 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8379 SDValue Ops[2] = { Lo, Hi };
8380 return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
8383 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
8384 SelectionDAG &DAG) const {
8385 EVT SrcVT = Op.getOperand(0).getValueType();
8387 if (SrcVT.isVector())
8390 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
8391 "Unknown SINT_TO_FP to lower!");
8393 // These are really Legal; return the operand so the caller accepts it as
8395 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
8397 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
8398 Subtarget->is64Bit()) {
8403 unsigned Size = SrcVT.getSizeInBits()/8;
8404 MachineFunction &MF = DAG.getMachineFunction();
8405 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8406 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8407 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8409 MachinePointerInfo::getFixedStack(SSFI),
8411 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8414 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8416 SelectionDAG &DAG) const {
8420 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8422 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8424 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8426 unsigned ByteSize = SrcVT.getSizeInBits()/8;
8428 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8429 MachineMemOperand *MMO;
8431 int SSFI = FI->getIndex();
8433 DAG.getMachineFunction()
8434 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8435 MachineMemOperand::MOLoad, ByteSize, ByteSize);
8437 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8438 StackSlot = StackSlot.getOperand(1);
8440 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8441 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8443 Tys, Ops, array_lengthof(Ops),
8447 Chain = Result.getValue(1);
8448 SDValue InFlag = Result.getValue(2);
8450 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8451 // shouldn't be necessary except that RFP cannot be live across
8452 // multiple blocks. When stackifier is fixed, they can be uncoupled.
8453 MachineFunction &MF = DAG.getMachineFunction();
8454 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8455 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8456 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8457 Tys = DAG.getVTList(MVT::Other);
8459 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8461 MachineMemOperand *MMO =
8462 DAG.getMachineFunction()
8463 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8464 MachineMemOperand::MOStore, SSFISize, SSFISize);
8466 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8467 Ops, array_lengthof(Ops),
8468 Op.getValueType(), MMO);
8469 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8470 MachinePointerInfo::getFixedStack(SSFI),
8471 false, false, false, 0);
8477 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8478 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8479 SelectionDAG &DAG) const {
8480 // This algorithm is not obvious. Here it is what we're trying to output:
8483 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8484 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8488 pshufd $0x4e, %xmm0, %xmm1
8494 LLVMContext *Context = DAG.getContext();
8496 // Build some magic constants.
8497 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8498 Constant *C0 = ConstantDataVector::get(*Context, CV0);
8499 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8501 SmallVector<Constant*,2> CV1;
8503 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8504 APInt(64, 0x4330000000000000ULL))));
8506 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8507 APInt(64, 0x4530000000000000ULL))));
8508 Constant *C1 = ConstantVector::get(CV1);
8509 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8511 // Load the 64-bit value into an XMM register.
8512 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8514 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8515 MachinePointerInfo::getConstantPool(),
8516 false, false, false, 16);
8517 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8518 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8521 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8522 MachinePointerInfo::getConstantPool(),
8523 false, false, false, 16);
8524 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8525 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8528 if (Subtarget->hasSSE3()) {
8529 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8530 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8532 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8533 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8535 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8536 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8540 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8541 DAG.getIntPtrConstant(0));
8544 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8545 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8546 SelectionDAG &DAG) const {
8548 // FP constant to bias correct the final result.
8549 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8552 // Load the 32-bit value into an XMM register.
8553 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8556 // Zero out the upper parts of the register.
8557 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8559 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8560 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8561 DAG.getIntPtrConstant(0));
8563 // Or the load with the bias.
8564 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8565 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8566 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8568 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8569 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8570 MVT::v2f64, Bias)));
8571 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8572 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8573 DAG.getIntPtrConstant(0));
8575 // Subtract the bias.
8576 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8578 // Handle final rounding.
8579 EVT DestVT = Op.getValueType();
8581 if (DestVT.bitsLT(MVT::f64))
8582 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8583 DAG.getIntPtrConstant(0));
8584 if (DestVT.bitsGT(MVT::f64))
8585 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8587 // Handle final rounding.
8591 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8592 SelectionDAG &DAG) const {
8593 SDValue N0 = Op.getOperand(0);
8594 EVT SVT = N0.getValueType();
8597 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8598 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8599 "Custom UINT_TO_FP is not supported!");
8601 EVT NVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
8602 SVT.getVectorNumElements());
8603 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8604 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8607 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8608 SelectionDAG &DAG) const {
8609 SDValue N0 = Op.getOperand(0);
8612 if (Op.getValueType().isVector())
8613 return lowerUINT_TO_FP_vec(Op, DAG);
8615 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8616 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8617 // the optimization here.
8618 if (DAG.SignBitIsZero(N0))
8619 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8621 EVT SrcVT = N0.getValueType();
8622 EVT DstVT = Op.getValueType();
8623 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8624 return LowerUINT_TO_FP_i64(Op, DAG);
8625 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8626 return LowerUINT_TO_FP_i32(Op, DAG);
8627 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8630 // Make a 64-bit buffer, and use it to build an FILD.
8631 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8632 if (SrcVT == MVT::i32) {
8633 SDValue WordOff = DAG.getConstant(4, getPointerTy());
8634 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8635 getPointerTy(), StackSlot, WordOff);
8636 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8637 StackSlot, MachinePointerInfo(),
8639 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8640 OffsetSlot, MachinePointerInfo(),
8642 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8646 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8647 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8648 StackSlot, MachinePointerInfo(),
8650 // For i64 source, we need to add the appropriate power of 2 if the input
8651 // was negative. This is the same as the optimization in
8652 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8653 // we must be careful to do the computation in x87 extended precision, not
8654 // in SSE. (The generic code can't know it's OK to do this, or how to.)
8655 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8656 MachineMemOperand *MMO =
8657 DAG.getMachineFunction()
8658 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8659 MachineMemOperand::MOLoad, 8, 8);
8661 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8662 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8663 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
8664 array_lengthof(Ops), MVT::i64, MMO);
8666 APInt FF(32, 0x5F800000ULL);
8668 // Check whether the sign bit is set.
8669 SDValue SignSet = DAG.getSetCC(dl,
8670 getSetCCResultType(*DAG.getContext(), MVT::i64),
8671 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8674 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8675 SDValue FudgePtr = DAG.getConstantPool(
8676 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8679 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8680 SDValue Zero = DAG.getIntPtrConstant(0);
8681 SDValue Four = DAG.getIntPtrConstant(4);
8682 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8684 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8686 // Load the value out, extending it from f32 to f80.
8687 // FIXME: Avoid the extend by constructing the right constant pool?
8688 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8689 FudgePtr, MachinePointerInfo::getConstantPool(),
8690 MVT::f32, false, false, 4);
8691 // Extend everything to 80 bits to force it to be done on x87.
8692 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8693 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8696 std::pair<SDValue,SDValue>
8697 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
8698 bool IsSigned, bool IsReplace) const {
8701 EVT DstTy = Op.getValueType();
8703 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8704 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8708 assert(DstTy.getSimpleVT() <= MVT::i64 &&
8709 DstTy.getSimpleVT() >= MVT::i16 &&
8710 "Unknown FP_TO_INT to lower!");
8712 // These are really Legal.
8713 if (DstTy == MVT::i32 &&
8714 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8715 return std::make_pair(SDValue(), SDValue());
8716 if (Subtarget->is64Bit() &&
8717 DstTy == MVT::i64 &&
8718 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8719 return std::make_pair(SDValue(), SDValue());
8721 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8722 // stack slot, or into the FTOL runtime function.
8723 MachineFunction &MF = DAG.getMachineFunction();
8724 unsigned MemSize = DstTy.getSizeInBits()/8;
8725 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8726 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8729 if (!IsSigned && isIntegerTypeFTOL(DstTy))
8730 Opc = X86ISD::WIN_FTOL;
8732 switch (DstTy.getSimpleVT().SimpleTy) {
8733 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8734 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8735 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8736 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8739 SDValue Chain = DAG.getEntryNode();
8740 SDValue Value = Op.getOperand(0);
8741 EVT TheVT = Op.getOperand(0).getValueType();
8742 // FIXME This causes a redundant load/store if the SSE-class value is already
8743 // in memory, such as if it is on the callstack.
8744 if (isScalarFPTypeInSSEReg(TheVT)) {
8745 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8746 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8747 MachinePointerInfo::getFixedStack(SSFI),
8749 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8751 Chain, StackSlot, DAG.getValueType(TheVT)
8754 MachineMemOperand *MMO =
8755 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8756 MachineMemOperand::MOLoad, MemSize, MemSize);
8757 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops,
8758 array_lengthof(Ops), DstTy, MMO);
8759 Chain = Value.getValue(1);
8760 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8761 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8764 MachineMemOperand *MMO =
8765 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8766 MachineMemOperand::MOStore, MemSize, MemSize);
8768 if (Opc != X86ISD::WIN_FTOL) {
8769 // Build the FP_TO_INT*_IN_MEM
8770 SDValue Ops[] = { Chain, Value, StackSlot };
8771 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8772 Ops, array_lengthof(Ops), DstTy,
8774 return std::make_pair(FIST, StackSlot);
8776 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8777 DAG.getVTList(MVT::Other, MVT::Glue),
8779 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8780 MVT::i32, ftol.getValue(1));
8781 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8782 MVT::i32, eax.getValue(2));
8783 SDValue Ops[] = { eax, edx };
8784 SDValue pair = IsReplace
8785 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, array_lengthof(Ops))
8786 : DAG.getMergeValues(Ops, array_lengthof(Ops), DL);
8787 return std::make_pair(pair, SDValue());
8791 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
8792 const X86Subtarget *Subtarget) {
8793 MVT VT = Op->getValueType(0).getSimpleVT();
8794 SDValue In = Op->getOperand(0);
8795 MVT InVT = In.getValueType().getSimpleVT();
8798 // Optimize vectors in AVX mode:
8801 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
8802 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
8803 // Concat upper and lower parts.
8806 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
8807 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
8808 // Concat upper and lower parts.
8811 if (((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
8812 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
8815 if (Subtarget->hasInt256())
8816 return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, In);
8818 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
8819 SDValue Undef = DAG.getUNDEF(InVT);
8820 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
8821 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8822 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8824 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
8825 VT.getVectorNumElements()/2);
8827 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
8828 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
8830 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
8833 SDValue X86TargetLowering::LowerANY_EXTEND(SDValue Op,
8834 SelectionDAG &DAG) const {
8835 if (Subtarget->hasFp256()) {
8836 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8843 SDValue X86TargetLowering::LowerZERO_EXTEND(SDValue Op,
8844 SelectionDAG &DAG) const {
8846 MVT VT = Op.getValueType().getSimpleVT();
8847 SDValue In = Op.getOperand(0);
8848 MVT SVT = In.getValueType().getSimpleVT();
8850 if (Subtarget->hasFp256()) {
8851 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8856 if (!VT.is256BitVector() || !SVT.is128BitVector() ||
8857 VT.getVectorNumElements() != SVT.getVectorNumElements())
8860 assert(Subtarget->hasFp256() && "256-bit vector is observed without AVX!");
8862 // AVX2 has better support of integer extending.
8863 if (Subtarget->hasInt256())
8864 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
8866 SDValue Lo = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32, In);
8867 static const int Mask[] = {4, 5, 6, 7, -1, -1, -1, -1};
8868 SDValue Hi = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32,
8869 DAG.getVectorShuffle(MVT::v8i16, DL, In,
8870 DAG.getUNDEF(MVT::v8i16),
8873 return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i32, Lo, Hi);
8876 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8878 MVT VT = Op.getValueType().getSimpleVT();
8879 SDValue In = Op.getOperand(0);
8880 MVT SVT = In.getValueType().getSimpleVT();
8882 if ((VT == MVT::v4i32) && (SVT == MVT::v4i64)) {
8883 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
8884 if (Subtarget->hasInt256()) {
8885 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
8886 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
8887 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
8889 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
8890 DAG.getIntPtrConstant(0));
8893 // On AVX, v4i64 -> v4i32 becomes a sequence that uses PSHUFD and MOVLHPS.
8894 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8895 DAG.getIntPtrConstant(0));
8896 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8897 DAG.getIntPtrConstant(2));
8899 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8900 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8903 static const int ShufMask1[] = {0, 2, 0, 0};
8904 SDValue Undef = DAG.getUNDEF(VT);
8905 OpLo = DAG.getVectorShuffle(VT, DL, OpLo, Undef, ShufMask1);
8906 OpHi = DAG.getVectorShuffle(VT, DL, OpHi, Undef, ShufMask1);
8908 // The MOVLHPS mask:
8909 static const int ShufMask2[] = {0, 1, 4, 5};
8910 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask2);
8913 if ((VT == MVT::v8i16) && (SVT == MVT::v8i32)) {
8914 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
8915 if (Subtarget->hasInt256()) {
8916 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
8918 SmallVector<SDValue,32> pshufbMask;
8919 for (unsigned i = 0; i < 2; ++i) {
8920 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
8921 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
8922 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
8923 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
8924 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
8925 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
8926 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
8927 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
8928 for (unsigned j = 0; j < 8; ++j)
8929 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
8931 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
8932 &pshufbMask[0], 32);
8933 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
8934 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
8936 static const int ShufMask[] = {0, 2, -1, -1};
8937 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
8939 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8940 DAG.getIntPtrConstant(0));
8941 return DAG.getNode(ISD::BITCAST, DL, VT, In);
8944 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8945 DAG.getIntPtrConstant(0));
8947 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8948 DAG.getIntPtrConstant(4));
8950 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
8951 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
8954 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
8955 -1, -1, -1, -1, -1, -1, -1, -1};
8957 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
8958 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
8959 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
8961 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8962 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8964 // The MOVLHPS Mask:
8965 static const int ShufMask2[] = {0, 1, 4, 5};
8966 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
8967 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
8970 // Handle truncation of V256 to V128 using shuffles.
8971 if (!VT.is128BitVector() || !SVT.is256BitVector())
8974 assert(VT.getVectorNumElements() != SVT.getVectorNumElements() &&
8976 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
8978 unsigned NumElems = VT.getVectorNumElements();
8979 EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8982 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
8983 // Prepare truncation shuffle mask
8984 for (unsigned i = 0; i != NumElems; ++i)
8986 SDValue V = DAG.getVectorShuffle(NVT, DL,
8987 DAG.getNode(ISD::BITCAST, DL, NVT, In),
8988 DAG.getUNDEF(NVT), &MaskVec[0]);
8989 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
8990 DAG.getIntPtrConstant(0));
8993 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8994 SelectionDAG &DAG) const {
8995 MVT VT = Op.getValueType().getSimpleVT();
8996 if (VT.isVector()) {
8997 if (VT == MVT::v8i16)
8998 return DAG.getNode(ISD::TRUNCATE, SDLoc(Op), VT,
8999 DAG.getNode(ISD::FP_TO_SINT, SDLoc(Op),
9000 MVT::v8i32, Op.getOperand(0)));
9004 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9005 /*IsSigned=*/ true, /*IsReplace=*/ false);
9006 SDValue FIST = Vals.first, StackSlot = Vals.second;
9007 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9008 if (FIST.getNode() == 0) return Op;
9010 if (StackSlot.getNode())
9012 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9013 FIST, StackSlot, MachinePointerInfo(),
9014 false, false, false, 0);
9016 // The node is the result.
9020 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9021 SelectionDAG &DAG) const {
9022 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9023 /*IsSigned=*/ false, /*IsReplace=*/ false);
9024 SDValue FIST = Vals.first, StackSlot = Vals.second;
9025 assert(FIST.getNode() && "Unexpected failure");
9027 if (StackSlot.getNode())
9029 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9030 FIST, StackSlot, MachinePointerInfo(),
9031 false, false, false, 0);
9033 // The node is the result.
9037 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9039 MVT VT = Op.getValueType().getSimpleVT();
9040 SDValue In = Op.getOperand(0);
9041 MVT SVT = In.getValueType().getSimpleVT();
9043 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9045 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9046 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9047 In, DAG.getUNDEF(SVT)));
9050 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
9051 LLVMContext *Context = DAG.getContext();
9053 MVT VT = Op.getValueType().getSimpleVT();
9055 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9056 if (VT.isVector()) {
9057 EltVT = VT.getVectorElementType();
9058 NumElts = VT.getVectorNumElements();
9061 if (EltVT == MVT::f64)
9062 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9063 APInt(64, ~(1ULL << 63))));
9065 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9066 APInt(32, ~(1U << 31))));
9067 C = ConstantVector::getSplat(NumElts, C);
9068 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
9069 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9070 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9071 MachinePointerInfo::getConstantPool(),
9072 false, false, false, Alignment);
9073 if (VT.isVector()) {
9074 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9075 return DAG.getNode(ISD::BITCAST, dl, VT,
9076 DAG.getNode(ISD::AND, dl, ANDVT,
9077 DAG.getNode(ISD::BITCAST, dl, ANDVT,
9079 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9081 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9084 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
9085 LLVMContext *Context = DAG.getContext();
9087 MVT VT = Op.getValueType().getSimpleVT();
9089 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9090 if (VT.isVector()) {
9091 EltVT = VT.getVectorElementType();
9092 NumElts = VT.getVectorNumElements();
9095 if (EltVT == MVT::f64)
9096 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9097 APInt(64, 1ULL << 63)));
9099 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9100 APInt(32, 1U << 31)));
9101 C = ConstantVector::getSplat(NumElts, C);
9102 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
9103 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9104 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9105 MachinePointerInfo::getConstantPool(),
9106 false, false, false, Alignment);
9107 if (VT.isVector()) {
9108 MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9109 return DAG.getNode(ISD::BITCAST, dl, VT,
9110 DAG.getNode(ISD::XOR, dl, XORVT,
9111 DAG.getNode(ISD::BITCAST, dl, XORVT,
9113 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9116 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9119 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
9120 LLVMContext *Context = DAG.getContext();
9121 SDValue Op0 = Op.getOperand(0);
9122 SDValue Op1 = Op.getOperand(1);
9124 MVT VT = Op.getValueType().getSimpleVT();
9125 MVT SrcVT = Op1.getValueType().getSimpleVT();
9127 // If second operand is smaller, extend it first.
9128 if (SrcVT.bitsLT(VT)) {
9129 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9132 // And if it is bigger, shrink it first.
9133 if (SrcVT.bitsGT(VT)) {
9134 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9138 // At this point the operands and the result should have the same
9139 // type, and that won't be f80 since that is not custom lowered.
9141 // First get the sign bit of second operand.
9142 SmallVector<Constant*,4> CV;
9143 if (SrcVT == MVT::f64) {
9144 const fltSemantics &Sem = APFloat::IEEEdouble;
9145 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9146 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9148 const fltSemantics &Sem = APFloat::IEEEsingle;
9149 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9150 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9151 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9152 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9154 Constant *C = ConstantVector::get(CV);
9155 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9156 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9157 MachinePointerInfo::getConstantPool(),
9158 false, false, false, 16);
9159 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9161 // Shift sign bit right or left if the two operands have different types.
9162 if (SrcVT.bitsGT(VT)) {
9163 // Op0 is MVT::f32, Op1 is MVT::f64.
9164 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9165 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9166 DAG.getConstant(32, MVT::i32));
9167 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9168 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9169 DAG.getIntPtrConstant(0));
9172 // Clear first operand sign bit.
9174 if (VT == MVT::f64) {
9175 const fltSemantics &Sem = APFloat::IEEEdouble;
9176 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9177 APInt(64, ~(1ULL << 63)))));
9178 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9180 const fltSemantics &Sem = APFloat::IEEEsingle;
9181 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9182 APInt(32, ~(1U << 31)))));
9183 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9184 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9185 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9187 C = ConstantVector::get(CV);
9188 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9189 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9190 MachinePointerInfo::getConstantPool(),
9191 false, false, false, 16);
9192 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9194 // Or the value with the sign bit.
9195 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9198 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9199 SDValue N0 = Op.getOperand(0);
9201 MVT VT = Op.getValueType().getSimpleVT();
9203 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9204 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9205 DAG.getConstant(1, VT));
9206 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9209 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9211 SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op,
9212 SelectionDAG &DAG) const {
9213 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9215 if (!Subtarget->hasSSE41())
9218 if (!Op->hasOneUse())
9221 SDNode *N = Op.getNode();
9224 SmallVector<SDValue, 8> Opnds;
9225 DenseMap<SDValue, unsigned> VecInMap;
9226 EVT VT = MVT::Other;
9228 // Recognize a special case where a vector is casted into wide integer to
9230 Opnds.push_back(N->getOperand(0));
9231 Opnds.push_back(N->getOperand(1));
9233 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9234 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9235 // BFS traverse all OR'd operands.
9236 if (I->getOpcode() == ISD::OR) {
9237 Opnds.push_back(I->getOperand(0));
9238 Opnds.push_back(I->getOperand(1));
9239 // Re-evaluate the number of nodes to be traversed.
9240 e += 2; // 2 more nodes (LHS and RHS) are pushed.
9244 // Quit if a non-EXTRACT_VECTOR_ELT
9245 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9248 // Quit if without a constant index.
9249 SDValue Idx = I->getOperand(1);
9250 if (!isa<ConstantSDNode>(Idx))
9253 SDValue ExtractedFromVec = I->getOperand(0);
9254 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9255 if (M == VecInMap.end()) {
9256 VT = ExtractedFromVec.getValueType();
9257 // Quit if not 128/256-bit vector.
9258 if (!VT.is128BitVector() && !VT.is256BitVector())
9260 // Quit if not the same type.
9261 if (VecInMap.begin() != VecInMap.end() &&
9262 VT != VecInMap.begin()->first.getValueType())
9264 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9266 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9269 assert((VT.is128BitVector() || VT.is256BitVector()) &&
9270 "Not extracted from 128-/256-bit vector.");
9272 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
9273 SmallVector<SDValue, 8> VecIns;
9275 for (DenseMap<SDValue, unsigned>::const_iterator
9276 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
9277 // Quit if not all elements are used.
9278 if (I->second != FullMask)
9280 VecIns.push_back(I->first);
9283 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9285 // Cast all vectors into TestVT for PTEST.
9286 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
9287 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
9289 // If more than one full vectors are evaluated, OR them first before PTEST.
9290 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
9291 // Each iteration will OR 2 nodes and append the result until there is only
9292 // 1 node left, i.e. the final OR'd value of all vectors.
9293 SDValue LHS = VecIns[Slot];
9294 SDValue RHS = VecIns[Slot + 1];
9295 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
9298 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
9299 VecIns.back(), VecIns.back());
9302 /// Emit nodes that will be selected as "test Op0,Op0", or something
9304 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
9305 SelectionDAG &DAG) const {
9308 // CF and OF aren't always set the way we want. Determine which
9309 // of these we need.
9310 bool NeedCF = false;
9311 bool NeedOF = false;
9314 case X86::COND_A: case X86::COND_AE:
9315 case X86::COND_B: case X86::COND_BE:
9318 case X86::COND_G: case X86::COND_GE:
9319 case X86::COND_L: case X86::COND_LE:
9320 case X86::COND_O: case X86::COND_NO:
9325 // See if we can use the EFLAGS value from the operand instead of
9326 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
9327 // we prove that the arithmetic won't overflow, we can't use OF or CF.
9328 if (Op.getResNo() != 0 || NeedOF || NeedCF)
9329 // Emit a CMP with 0, which is the TEST pattern.
9330 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9331 DAG.getConstant(0, Op.getValueType()));
9333 unsigned Opcode = 0;
9334 unsigned NumOperands = 0;
9336 // Truncate operations may prevent the merge of the SETCC instruction
9337 // and the arithmetic intruction before it. Attempt to truncate the operands
9338 // of the arithmetic instruction and use a reduced bit-width instruction.
9339 bool NeedTruncation = false;
9340 SDValue ArithOp = Op;
9341 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
9342 SDValue Arith = Op->getOperand(0);
9343 // Both the trunc and the arithmetic op need to have one user each.
9344 if (Arith->hasOneUse())
9345 switch (Arith.getOpcode()) {
9352 NeedTruncation = true;
9358 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
9359 // which may be the result of a CAST. We use the variable 'Op', which is the
9360 // non-casted variable when we check for possible users.
9361 switch (ArithOp.getOpcode()) {
9363 // Due to an isel shortcoming, be conservative if this add is likely to be
9364 // selected as part of a load-modify-store instruction. When the root node
9365 // in a match is a store, isel doesn't know how to remap non-chain non-flag
9366 // uses of other nodes in the match, such as the ADD in this case. This
9367 // leads to the ADD being left around and reselected, with the result being
9368 // two adds in the output. Alas, even if none our users are stores, that
9369 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
9370 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
9371 // climbing the DAG back to the root, and it doesn't seem to be worth the
9373 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9374 UE = Op.getNode()->use_end(); UI != UE; ++UI)
9375 if (UI->getOpcode() != ISD::CopyToReg &&
9376 UI->getOpcode() != ISD::SETCC &&
9377 UI->getOpcode() != ISD::STORE)
9380 if (ConstantSDNode *C =
9381 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
9382 // An add of one will be selected as an INC.
9383 if (C->getAPIntValue() == 1) {
9384 Opcode = X86ISD::INC;
9389 // An add of negative one (subtract of one) will be selected as a DEC.
9390 if (C->getAPIntValue().isAllOnesValue()) {
9391 Opcode = X86ISD::DEC;
9397 // Otherwise use a regular EFLAGS-setting add.
9398 Opcode = X86ISD::ADD;
9402 // If the primary and result isn't used, don't bother using X86ISD::AND,
9403 // because a TEST instruction will be better.
9404 bool NonFlagUse = false;
9405 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9406 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
9408 unsigned UOpNo = UI.getOperandNo();
9409 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9410 // Look pass truncate.
9411 UOpNo = User->use_begin().getOperandNo();
9412 User = *User->use_begin();
9415 if (User->getOpcode() != ISD::BRCOND &&
9416 User->getOpcode() != ISD::SETCC &&
9417 !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
9430 // Due to the ISEL shortcoming noted above, be conservative if this op is
9431 // likely to be selected as part of a load-modify-store instruction.
9432 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9433 UE = Op.getNode()->use_end(); UI != UE; ++UI)
9434 if (UI->getOpcode() == ISD::STORE)
9437 // Otherwise use a regular EFLAGS-setting instruction.
9438 switch (ArithOp.getOpcode()) {
9439 default: llvm_unreachable("unexpected operator!");
9440 case ISD::SUB: Opcode = X86ISD::SUB; break;
9441 case ISD::XOR: Opcode = X86ISD::XOR; break;
9442 case ISD::AND: Opcode = X86ISD::AND; break;
9444 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9445 SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
9446 if (EFLAGS.getNode())
9449 Opcode = X86ISD::OR;
9463 return SDValue(Op.getNode(), 1);
9469 // If we found that truncation is beneficial, perform the truncation and
9471 if (NeedTruncation) {
9472 EVT VT = Op.getValueType();
9473 SDValue WideVal = Op->getOperand(0);
9474 EVT WideVT = WideVal.getValueType();
9475 unsigned ConvertedOp = 0;
9476 // Use a target machine opcode to prevent further DAGCombine
9477 // optimizations that may separate the arithmetic operations
9478 // from the setcc node.
9479 switch (WideVal.getOpcode()) {
9481 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9482 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9483 case ISD::AND: ConvertedOp = X86ISD::AND; break;
9484 case ISD::OR: ConvertedOp = X86ISD::OR; break;
9485 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9489 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9490 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9491 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9492 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
9493 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
9499 // Emit a CMP with 0, which is the TEST pattern.
9500 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9501 DAG.getConstant(0, Op.getValueType()));
9503 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9504 SmallVector<SDValue, 4> Ops;
9505 for (unsigned i = 0; i != NumOperands; ++i)
9506 Ops.push_back(Op.getOperand(i));
9508 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
9509 DAG.ReplaceAllUsesWith(Op, New);
9510 return SDValue(New.getNode(), 1);
9513 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
9515 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
9516 SelectionDAG &DAG) const {
9517 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
9518 if (C->getAPIntValue() == 0)
9519 return EmitTest(Op0, X86CC, DAG);
9522 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
9523 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
9524 // Use SUB instead of CMP to enable CSE between SUB and CMP.
9525 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
9526 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
9528 return SDValue(Sub.getNode(), 1);
9530 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
9533 /// Convert a comparison if required by the subtarget.
9534 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
9535 SelectionDAG &DAG) const {
9536 // If the subtarget does not support the FUCOMI instruction, floating-point
9537 // comparisons have to be converted.
9538 if (Subtarget->hasCMov() ||
9539 Cmp.getOpcode() != X86ISD::CMP ||
9540 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
9541 !Cmp.getOperand(1).getValueType().isFloatingPoint())
9544 // The instruction selector will select an FUCOM instruction instead of
9545 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
9546 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
9547 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
9549 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
9550 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
9551 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
9552 DAG.getConstant(8, MVT::i8));
9553 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
9554 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
9557 static bool isAllOnes(SDValue V) {
9558 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9559 return C && C->isAllOnesValue();
9562 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
9563 /// if it's possible.
9564 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
9565 SDLoc dl, SelectionDAG &DAG) const {
9566 SDValue Op0 = And.getOperand(0);
9567 SDValue Op1 = And.getOperand(1);
9568 if (Op0.getOpcode() == ISD::TRUNCATE)
9569 Op0 = Op0.getOperand(0);
9570 if (Op1.getOpcode() == ISD::TRUNCATE)
9571 Op1 = Op1.getOperand(0);
9574 if (Op1.getOpcode() == ISD::SHL)
9575 std::swap(Op0, Op1);
9576 if (Op0.getOpcode() == ISD::SHL) {
9577 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
9578 if (And00C->getZExtValue() == 1) {
9579 // If we looked past a truncate, check that it's only truncating away
9581 unsigned BitWidth = Op0.getValueSizeInBits();
9582 unsigned AndBitWidth = And.getValueSizeInBits();
9583 if (BitWidth > AndBitWidth) {
9585 DAG.ComputeMaskedBits(Op0, Zeros, Ones);
9586 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
9590 RHS = Op0.getOperand(1);
9592 } else if (Op1.getOpcode() == ISD::Constant) {
9593 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
9594 uint64_t AndRHSVal = AndRHS->getZExtValue();
9595 SDValue AndLHS = Op0;
9597 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
9598 LHS = AndLHS.getOperand(0);
9599 RHS = AndLHS.getOperand(1);
9602 // Use BT if the immediate can't be encoded in a TEST instruction.
9603 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
9605 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
9609 if (LHS.getNode()) {
9610 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
9611 // instruction. Since the shift amount is in-range-or-undefined, we know
9612 // that doing a bittest on the i32 value is ok. We extend to i32 because
9613 // the encoding for the i16 version is larger than the i32 version.
9614 // Also promote i16 to i32 for performance / code size reason.
9615 if (LHS.getValueType() == MVT::i8 ||
9616 LHS.getValueType() == MVT::i16)
9617 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
9619 // If the operand types disagree, extend the shift amount to match. Since
9620 // BT ignores high bits (like shifts) we can use anyextend.
9621 if (LHS.getValueType() != RHS.getValueType())
9622 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
9624 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
9625 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
9626 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9627 DAG.getConstant(Cond, MVT::i8), BT);
9633 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
9635 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
9640 // SSE Condition code mapping:
9649 switch (SetCCOpcode) {
9650 default: llvm_unreachable("Unexpected SETCC condition");
9652 case ISD::SETEQ: SSECC = 0; break;
9654 case ISD::SETGT: Swap = true; // Fallthrough
9656 case ISD::SETOLT: SSECC = 1; break;
9658 case ISD::SETGE: Swap = true; // Fallthrough
9660 case ISD::SETOLE: SSECC = 2; break;
9661 case ISD::SETUO: SSECC = 3; break;
9663 case ISD::SETNE: SSECC = 4; break;
9664 case ISD::SETULE: Swap = true; // Fallthrough
9665 case ISD::SETUGE: SSECC = 5; break;
9666 case ISD::SETULT: Swap = true; // Fallthrough
9667 case ISD::SETUGT: SSECC = 6; break;
9668 case ISD::SETO: SSECC = 7; break;
9670 case ISD::SETONE: SSECC = 8; break;
9673 std::swap(Op0, Op1);
9678 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9679 // ones, and then concatenate the result back.
9680 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9681 MVT VT = Op.getValueType().getSimpleVT();
9683 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9684 "Unsupported value type for operation");
9686 unsigned NumElems = VT.getVectorNumElements();
9688 SDValue CC = Op.getOperand(2);
9690 // Extract the LHS vectors
9691 SDValue LHS = Op.getOperand(0);
9692 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9693 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9695 // Extract the RHS vectors
9696 SDValue RHS = Op.getOperand(1);
9697 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
9698 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
9700 // Issue the operation on the smaller types and concatenate the result back
9701 MVT EltVT = VT.getVectorElementType();
9702 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9703 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9704 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9705 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
9708 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
9710 SDValue Op0 = Op.getOperand(0);
9711 SDValue Op1 = Op.getOperand(1);
9712 SDValue CC = Op.getOperand(2);
9713 MVT VT = Op.getValueType().getSimpleVT();
9715 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
9716 Op.getValueType().getScalarType() == MVT::i1 &&
9717 "Cannot set masked compare for this operation");
9719 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9722 bool Unsigned = false;
9724 switch (SetCCOpcode) {
9725 default: llvm_unreachable("Unexpected SETCC condition");
9726 case ISD::SETNE: SSECC = 4; break;
9727 case ISD::SETEQ: SSECC = 0; break;
9728 case ISD::SETUGT: Unsigned = true;
9729 case ISD::SETGT: SSECC = 6; break; // NLE
9730 case ISD::SETULT: Unsigned = true;
9731 case ISD::SETLT: SSECC = 1; break;
9732 case ISD::SETUGE: Unsigned = true;
9733 case ISD::SETGE: SSECC = 5; break; // NLT
9734 case ISD::SETULE: Unsigned = true;
9735 case ISD::SETLE: SSECC = 2; break;
9737 unsigned Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
9738 return DAG.getNode(Opc, dl, VT, Op0, Op1,
9739 DAG.getConstant(SSECC, MVT::i8));
9743 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
9744 SelectionDAG &DAG) {
9746 SDValue Op0 = Op.getOperand(0);
9747 SDValue Op1 = Op.getOperand(1);
9748 SDValue CC = Op.getOperand(2);
9749 MVT VT = Op.getValueType().getSimpleVT();
9750 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9751 bool isFP = Op.getOperand(1).getValueType().getSimpleVT().isFloatingPoint();
9756 MVT EltVT = Op0.getValueType().getVectorElementType().getSimpleVT();
9757 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
9760 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
9761 unsigned Opc = X86ISD::CMPP;
9762 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
9763 assert(VT.getVectorNumElements() <= 16);
9766 // In the two special cases we can't handle, emit two comparisons.
9769 unsigned CombineOpc;
9770 if (SetCCOpcode == ISD::SETUEQ) {
9771 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
9773 assert(SetCCOpcode == ISD::SETONE);
9774 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
9777 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
9778 DAG.getConstant(CC0, MVT::i8));
9779 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
9780 DAG.getConstant(CC1, MVT::i8));
9781 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
9783 // Handle all other FP comparisons here.
9784 return DAG.getNode(Opc, dl, VT, Op0, Op1,
9785 DAG.getConstant(SSECC, MVT::i8));
9788 // Break 256-bit integer vector compare into smaller ones.
9789 if (VT.is256BitVector() && !Subtarget->hasInt256())
9790 return Lower256IntVSETCC(Op, DAG);
9792 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
9793 EVT OpVT = Op1.getValueType();
9794 if (Subtarget->hasAVX512()) {
9795 if (Op1.getValueType().is512BitVector() ||
9796 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
9797 return LowerIntVSETCC_AVX512(Op, DAG);
9799 // In AVX-512 architecture setcc returns mask with i1 elements,
9800 // But there is no compare instruction for i8 and i16 elements.
9801 // We are not talking about 512-bit operands in this case, these
9802 // types are illegal.
9804 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
9805 OpVT.getVectorElementType().getSizeInBits() >= 8))
9806 return DAG.getNode(ISD::TRUNCATE, dl, VT,
9807 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
9810 // We are handling one of the integer comparisons here. Since SSE only has
9811 // GT and EQ comparisons for integer, swapping operands and multiple
9812 // operations may be required for some comparisons.
9814 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
9816 switch (SetCCOpcode) {
9817 default: llvm_unreachable("Unexpected SETCC condition");
9818 case ISD::SETNE: Invert = true;
9819 case ISD::SETEQ: Opc = MaskResult? X86ISD::PCMPEQM: X86ISD::PCMPEQ; break;
9820 case ISD::SETLT: Swap = true;
9821 case ISD::SETGT: Opc = MaskResult? X86ISD::PCMPGTM: X86ISD::PCMPGT; break;
9822 case ISD::SETGE: Swap = true;
9823 case ISD::SETLE: Opc = MaskResult? X86ISD::PCMPGTM: X86ISD::PCMPGT;
9824 Invert = true; break;
9825 case ISD::SETULT: Swap = true;
9826 case ISD::SETUGT: Opc = MaskResult? X86ISD::PCMPGTM: X86ISD::PCMPGT;
9827 FlipSigns = true; break;
9828 case ISD::SETUGE: Swap = true;
9829 case ISD::SETULE: Opc = MaskResult? X86ISD::PCMPGTM: X86ISD::PCMPGT;
9830 FlipSigns = true; Invert = true; break;
9833 // Special case: Use min/max operations for SETULE/SETUGE
9834 MVT VET = VT.getVectorElementType();
9836 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
9837 || (Subtarget->hasSSE2() && (VET == MVT::i8));
9840 switch (SetCCOpcode) {
9842 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
9843 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
9846 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
9850 std::swap(Op0, Op1);
9852 // Check that the operation in question is available (most are plain SSE2,
9853 // but PCMPGTQ and PCMPEQQ have different requirements).
9854 if (VT == MVT::v2i64) {
9855 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
9856 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
9858 // First cast everything to the right type.
9859 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9860 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9862 // Since SSE has no unsigned integer comparisons, we need to flip the sign
9863 // bits of the inputs before performing those operations. The lower
9864 // compare is always unsigned.
9867 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
9869 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
9870 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
9871 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
9872 Sign, Zero, Sign, Zero);
9874 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
9875 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
9877 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
9878 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
9879 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
9881 // Create masks for only the low parts/high parts of the 64 bit integers.
9882 static const int MaskHi[] = { 1, 1, 3, 3 };
9883 static const int MaskLo[] = { 0, 0, 2, 2 };
9884 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
9885 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
9886 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
9888 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
9889 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
9892 Result = DAG.getNOT(dl, Result, MVT::v4i32);
9894 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9897 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
9898 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
9899 // pcmpeqd + pshufd + pand.
9900 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
9902 // First cast everything to the right type.
9903 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9904 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9907 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
9909 // Make sure the lower and upper halves are both all-ones.
9910 static const int Mask[] = { 1, 0, 3, 2 };
9911 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
9912 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
9915 Result = DAG.getNOT(dl, Result, MVT::v4i32);
9917 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9921 // Since SSE has no unsigned integer comparisons, we need to flip the sign
9922 // bits of the inputs before performing those operations.
9924 EVT EltVT = VT.getVectorElementType();
9925 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
9926 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
9927 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
9930 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
9932 // If the logical-not of the result is required, perform that now.
9934 Result = DAG.getNOT(dl, Result, VT);
9937 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
9942 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
9944 MVT VT = Op.getValueType().getSimpleVT();
9946 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
9948 assert(VT == MVT::i8 && "SetCC type must be 8-bit integer");
9949 SDValue Op0 = Op.getOperand(0);
9950 SDValue Op1 = Op.getOperand(1);
9952 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9954 // Optimize to BT if possible.
9955 // Lower (X & (1 << N)) == 0 to BT(X, N).
9956 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
9957 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
9958 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
9959 Op1.getOpcode() == ISD::Constant &&
9960 cast<ConstantSDNode>(Op1)->isNullValue() &&
9961 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9962 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
9963 if (NewSetCC.getNode())
9967 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
9969 if (Op1.getOpcode() == ISD::Constant &&
9970 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
9971 cast<ConstantSDNode>(Op1)->isNullValue()) &&
9972 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9974 // If the input is a setcc, then reuse the input setcc or use a new one with
9975 // the inverted condition.
9976 if (Op0.getOpcode() == X86ISD::SETCC) {
9977 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
9978 bool Invert = (CC == ISD::SETNE) ^
9979 cast<ConstantSDNode>(Op1)->isNullValue();
9980 if (!Invert) return Op0;
9982 CCode = X86::GetOppositeBranchCondition(CCode);
9983 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9984 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
9988 bool isFP = Op1.getValueType().getSimpleVT().isFloatingPoint();
9989 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
9990 if (X86CC == X86::COND_INVALID)
9993 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
9994 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
9995 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9996 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
9999 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10000 static bool isX86LogicalCmp(SDValue Op) {
10001 unsigned Opc = Op.getNode()->getOpcode();
10002 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10003 Opc == X86ISD::SAHF)
10005 if (Op.getResNo() == 1 &&
10006 (Opc == X86ISD::ADD ||
10007 Opc == X86ISD::SUB ||
10008 Opc == X86ISD::ADC ||
10009 Opc == X86ISD::SBB ||
10010 Opc == X86ISD::SMUL ||
10011 Opc == X86ISD::UMUL ||
10012 Opc == X86ISD::INC ||
10013 Opc == X86ISD::DEC ||
10014 Opc == X86ISD::OR ||
10015 Opc == X86ISD::XOR ||
10016 Opc == X86ISD::AND))
10019 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
10025 static bool isZero(SDValue V) {
10026 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10027 return C && C->isNullValue();
10030 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
10031 if (V.getOpcode() != ISD::TRUNCATE)
10034 SDValue VOp0 = V.getOperand(0);
10035 unsigned InBits = VOp0.getValueSizeInBits();
10036 unsigned Bits = V.getValueSizeInBits();
10037 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
10040 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
10041 bool addTest = true;
10042 SDValue Cond = Op.getOperand(0);
10043 SDValue Op1 = Op.getOperand(1);
10044 SDValue Op2 = Op.getOperand(2);
10046 EVT VT = Op1.getValueType();
10049 // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
10050 // are available. Otherwise fp cmovs get lowered into a less efficient branch
10051 // sequence later on.
10052 if (Cond.getOpcode() == ISD::SETCC &&
10053 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
10054 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
10055 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
10056 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
10057 int SSECC = translateX86FSETCC(
10058 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
10061 unsigned Opcode = VT == MVT::f32 ? X86ISD::FSETCCss : X86ISD::FSETCCsd;
10062 SDValue Cmp = DAG.getNode(Opcode, DL, VT, CondOp0, CondOp1,
10063 DAG.getConstant(SSECC, MVT::i8));
10064 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
10065 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
10066 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
10070 if (Cond.getOpcode() == ISD::SETCC) {
10071 SDValue NewCond = LowerSETCC(Cond, DAG);
10072 if (NewCond.getNode())
10076 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
10077 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
10078 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
10079 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
10080 if (Cond.getOpcode() == X86ISD::SETCC &&
10081 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
10082 isZero(Cond.getOperand(1).getOperand(1))) {
10083 SDValue Cmp = Cond.getOperand(1);
10085 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
10087 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
10088 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
10089 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
10091 SDValue CmpOp0 = Cmp.getOperand(0);
10092 // Apply further optimizations for special cases
10093 // (select (x != 0), -1, 0) -> neg & sbb
10094 // (select (x == 0), 0, -1) -> neg & sbb
10095 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
10096 if (YC->isNullValue() &&
10097 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
10098 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
10099 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
10100 DAG.getConstant(0, CmpOp0.getValueType()),
10102 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10103 DAG.getConstant(X86::COND_B, MVT::i8),
10104 SDValue(Neg.getNode(), 1));
10108 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10109 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10110 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10112 SDValue Res = // Res = 0 or -1.
10113 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10114 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
10116 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
10117 Res = DAG.getNOT(DL, Res, Res.getValueType());
10119 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
10120 if (N2C == 0 || !N2C->isNullValue())
10121 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
10126 // Look past (and (setcc_carry (cmp ...)), 1).
10127 if (Cond.getOpcode() == ISD::AND &&
10128 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10129 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10130 if (C && C->getAPIntValue() == 1)
10131 Cond = Cond.getOperand(0);
10134 // If condition flag is set by a X86ISD::CMP, then use it as the condition
10135 // setting operand in place of the X86ISD::SETCC.
10136 unsigned CondOpcode = Cond.getOpcode();
10137 if (CondOpcode == X86ISD::SETCC ||
10138 CondOpcode == X86ISD::SETCC_CARRY) {
10139 CC = Cond.getOperand(0);
10141 SDValue Cmp = Cond.getOperand(1);
10142 unsigned Opc = Cmp.getOpcode();
10143 MVT VT = Op.getValueType().getSimpleVT();
10145 bool IllegalFPCMov = false;
10146 if (VT.isFloatingPoint() && !VT.isVector() &&
10147 !isScalarFPTypeInSSEReg(VT)) // FPStack?
10148 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
10150 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
10151 Opc == X86ISD::BT) { // FIXME
10155 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10156 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10157 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10158 Cond.getOperand(0).getValueType() != MVT::i8)) {
10159 SDValue LHS = Cond.getOperand(0);
10160 SDValue RHS = Cond.getOperand(1);
10161 unsigned X86Opcode;
10164 switch (CondOpcode) {
10165 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10166 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10167 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10168 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10169 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10170 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10171 default: llvm_unreachable("unexpected overflowing operator");
10173 if (CondOpcode == ISD::UMULO)
10174 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10177 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10179 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
10181 if (CondOpcode == ISD::UMULO)
10182 Cond = X86Op.getValue(2);
10184 Cond = X86Op.getValue(1);
10186 CC = DAG.getConstant(X86Cond, MVT::i8);
10191 // Look pass the truncate if the high bits are known zero.
10192 if (isTruncWithZeroHighBitsInput(Cond, DAG))
10193 Cond = Cond.getOperand(0);
10195 // We know the result of AND is compared against zero. Try to match
10197 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10198 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
10199 if (NewSetCC.getNode()) {
10200 CC = NewSetCC.getOperand(0);
10201 Cond = NewSetCC.getOperand(1);
10208 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10209 Cond = EmitTest(Cond, X86::COND_NE, DAG);
10212 // a < b ? -1 : 0 -> RES = ~setcc_carry
10213 // a < b ? 0 : -1 -> RES = setcc_carry
10214 // a >= b ? -1 : 0 -> RES = setcc_carry
10215 // a >= b ? 0 : -1 -> RES = ~setcc_carry
10216 if (Cond.getOpcode() == X86ISD::SUB) {
10217 Cond = ConvertCmpIfNecessary(Cond, DAG);
10218 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
10220 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
10221 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
10222 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10223 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
10224 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
10225 return DAG.getNOT(DL, Res, Res.getValueType());
10230 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
10231 // widen the cmov and push the truncate through. This avoids introducing a new
10232 // branch during isel and doesn't add any extensions.
10233 if (Op.getValueType() == MVT::i8 &&
10234 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
10235 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
10236 if (T1.getValueType() == T2.getValueType() &&
10237 // Blacklist CopyFromReg to avoid partial register stalls.
10238 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
10239 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
10240 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
10241 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
10245 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
10246 // condition is true.
10247 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
10248 SDValue Ops[] = { Op2, Op1, CC, Cond };
10249 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
10252 SDValue X86TargetLowering::LowerSIGN_EXTEND_AVX512(SDValue Op,
10253 SelectionDAG &DAG) const {
10254 EVT VT = Op->getValueType(0);
10255 SDValue In = Op->getOperand(0);
10256 EVT InVT = In.getValueType();
10259 if (InVT.getVectorElementType().getSizeInBits() >=8 &&
10260 VT.getVectorElementType().getSizeInBits() >= 32)
10261 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10263 if (InVT.getVectorElementType() == MVT::i1) {
10264 unsigned int NumElts = InVT.getVectorNumElements();
10265 assert ((NumElts == 8 || NumElts == 16) &&
10266 "Unsupported SIGN_EXTEND operation");
10267 if (VT.getVectorElementType().getSizeInBits() >= 32) {
10269 ConstantInt::get(*DAG.getContext(),
10270 (NumElts == 8)? APInt(64, ~0ULL): APInt(32, ~0U));
10271 SDValue CP = DAG.getConstantPool(C, getPointerTy());
10272 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
10273 SDValue Ld = DAG.getLoad(VT.getScalarType(), dl, DAG.getEntryNode(), CP,
10274 MachinePointerInfo::getConstantPool(),
10275 false, false, false, Alignment);
10276 return DAG.getNode(X86ISD::VBROADCASTM, dl, VT, In, Ld);
10282 SDValue X86TargetLowering::LowerSIGN_EXTEND(SDValue Op,
10283 SelectionDAG &DAG) const {
10284 MVT VT = Op->getValueType(0).getSimpleVT();
10285 SDValue In = Op->getOperand(0);
10286 MVT InVT = In.getValueType().getSimpleVT();
10289 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
10290 return LowerSIGN_EXTEND_AVX512(Op, DAG);
10292 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
10293 (VT != MVT::v8i32 || InVT != MVT::v8i16))
10296 if (Subtarget->hasInt256())
10297 return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, In);
10299 // Optimize vectors in AVX mode
10300 // Sign extend v8i16 to v8i32 and
10303 // Divide input vector into two parts
10304 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
10305 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
10306 // concat the vectors to original VT
10308 unsigned NumElems = InVT.getVectorNumElements();
10309 SDValue Undef = DAG.getUNDEF(InVT);
10311 SmallVector<int,8> ShufMask1(NumElems, -1);
10312 for (unsigned i = 0; i != NumElems/2; ++i)
10315 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
10317 SmallVector<int,8> ShufMask2(NumElems, -1);
10318 for (unsigned i = 0; i != NumElems/2; ++i)
10319 ShufMask2[i] = i + NumElems/2;
10321 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
10323 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
10324 VT.getVectorNumElements()/2);
10326 OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
10327 OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
10329 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
10332 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
10333 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
10334 // from the AND / OR.
10335 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
10336 Opc = Op.getOpcode();
10337 if (Opc != ISD::OR && Opc != ISD::AND)
10339 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10340 Op.getOperand(0).hasOneUse() &&
10341 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
10342 Op.getOperand(1).hasOneUse());
10345 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
10346 // 1 and that the SETCC node has a single use.
10347 static bool isXor1OfSetCC(SDValue Op) {
10348 if (Op.getOpcode() != ISD::XOR)
10350 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10351 if (N1C && N1C->getAPIntValue() == 1) {
10352 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10353 Op.getOperand(0).hasOneUse();
10358 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
10359 bool addTest = true;
10360 SDValue Chain = Op.getOperand(0);
10361 SDValue Cond = Op.getOperand(1);
10362 SDValue Dest = Op.getOperand(2);
10365 bool Inverted = false;
10367 if (Cond.getOpcode() == ISD::SETCC) {
10368 // Check for setcc([su]{add,sub,mul}o == 0).
10369 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
10370 isa<ConstantSDNode>(Cond.getOperand(1)) &&
10371 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
10372 Cond.getOperand(0).getResNo() == 1 &&
10373 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
10374 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
10375 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
10376 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
10377 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
10378 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
10380 Cond = Cond.getOperand(0);
10382 SDValue NewCond = LowerSETCC(Cond, DAG);
10383 if (NewCond.getNode())
10388 // FIXME: LowerXALUO doesn't handle these!!
10389 else if (Cond.getOpcode() == X86ISD::ADD ||
10390 Cond.getOpcode() == X86ISD::SUB ||
10391 Cond.getOpcode() == X86ISD::SMUL ||
10392 Cond.getOpcode() == X86ISD::UMUL)
10393 Cond = LowerXALUO(Cond, DAG);
10396 // Look pass (and (setcc_carry (cmp ...)), 1).
10397 if (Cond.getOpcode() == ISD::AND &&
10398 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10399 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10400 if (C && C->getAPIntValue() == 1)
10401 Cond = Cond.getOperand(0);
10404 // If condition flag is set by a X86ISD::CMP, then use it as the condition
10405 // setting operand in place of the X86ISD::SETCC.
10406 unsigned CondOpcode = Cond.getOpcode();
10407 if (CondOpcode == X86ISD::SETCC ||
10408 CondOpcode == X86ISD::SETCC_CARRY) {
10409 CC = Cond.getOperand(0);
10411 SDValue Cmp = Cond.getOperand(1);
10412 unsigned Opc = Cmp.getOpcode();
10413 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
10414 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
10418 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
10422 // These can only come from an arithmetic instruction with overflow,
10423 // e.g. SADDO, UADDO.
10424 Cond = Cond.getNode()->getOperand(1);
10430 CondOpcode = Cond.getOpcode();
10431 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10432 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10433 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10434 Cond.getOperand(0).getValueType() != MVT::i8)) {
10435 SDValue LHS = Cond.getOperand(0);
10436 SDValue RHS = Cond.getOperand(1);
10437 unsigned X86Opcode;
10440 switch (CondOpcode) {
10441 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10442 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10443 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10444 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10445 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10446 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10447 default: llvm_unreachable("unexpected overflowing operator");
10450 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
10451 if (CondOpcode == ISD::UMULO)
10452 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10455 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10457 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
10459 if (CondOpcode == ISD::UMULO)
10460 Cond = X86Op.getValue(2);
10462 Cond = X86Op.getValue(1);
10464 CC = DAG.getConstant(X86Cond, MVT::i8);
10468 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
10469 SDValue Cmp = Cond.getOperand(0).getOperand(1);
10470 if (CondOpc == ISD::OR) {
10471 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
10472 // two branches instead of an explicit OR instruction with a
10474 if (Cmp == Cond.getOperand(1).getOperand(1) &&
10475 isX86LogicalCmp(Cmp)) {
10476 CC = Cond.getOperand(0).getOperand(0);
10477 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10478 Chain, Dest, CC, Cmp);
10479 CC = Cond.getOperand(1).getOperand(0);
10483 } else { // ISD::AND
10484 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
10485 // two branches instead of an explicit AND instruction with a
10486 // separate test. However, we only do this if this block doesn't
10487 // have a fall-through edge, because this requires an explicit
10488 // jmp when the condition is false.
10489 if (Cmp == Cond.getOperand(1).getOperand(1) &&
10490 isX86LogicalCmp(Cmp) &&
10491 Op.getNode()->hasOneUse()) {
10492 X86::CondCode CCode =
10493 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
10494 CCode = X86::GetOppositeBranchCondition(CCode);
10495 CC = DAG.getConstant(CCode, MVT::i8);
10496 SDNode *User = *Op.getNode()->use_begin();
10497 // Look for an unconditional branch following this conditional branch.
10498 // We need this because we need to reverse the successors in order
10499 // to implement FCMP_OEQ.
10500 if (User->getOpcode() == ISD::BR) {
10501 SDValue FalseBB = User->getOperand(1);
10503 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10504 assert(NewBR == User);
10508 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10509 Chain, Dest, CC, Cmp);
10510 X86::CondCode CCode =
10511 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
10512 CCode = X86::GetOppositeBranchCondition(CCode);
10513 CC = DAG.getConstant(CCode, MVT::i8);
10519 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
10520 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
10521 // It should be transformed during dag combiner except when the condition
10522 // is set by a arithmetics with overflow node.
10523 X86::CondCode CCode =
10524 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
10525 CCode = X86::GetOppositeBranchCondition(CCode);
10526 CC = DAG.getConstant(CCode, MVT::i8);
10527 Cond = Cond.getOperand(0).getOperand(1);
10529 } else if (Cond.getOpcode() == ISD::SETCC &&
10530 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
10531 // For FCMP_OEQ, we can emit
10532 // two branches instead of an explicit AND instruction with a
10533 // separate test. However, we only do this if this block doesn't
10534 // have a fall-through edge, because this requires an explicit
10535 // jmp when the condition is false.
10536 if (Op.getNode()->hasOneUse()) {
10537 SDNode *User = *Op.getNode()->use_begin();
10538 // Look for an unconditional branch following this conditional branch.
10539 // We need this because we need to reverse the successors in order
10540 // to implement FCMP_OEQ.
10541 if (User->getOpcode() == ISD::BR) {
10542 SDValue FalseBB = User->getOperand(1);
10544 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10545 assert(NewBR == User);
10549 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10550 Cond.getOperand(0), Cond.getOperand(1));
10551 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10552 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10553 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10554 Chain, Dest, CC, Cmp);
10555 CC = DAG.getConstant(X86::COND_P, MVT::i8);
10560 } else if (Cond.getOpcode() == ISD::SETCC &&
10561 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
10562 // For FCMP_UNE, we can emit
10563 // two branches instead of an explicit AND instruction with a
10564 // separate test. However, we only do this if this block doesn't
10565 // have a fall-through edge, because this requires an explicit
10566 // jmp when the condition is false.
10567 if (Op.getNode()->hasOneUse()) {
10568 SDNode *User = *Op.getNode()->use_begin();
10569 // Look for an unconditional branch following this conditional branch.
10570 // We need this because we need to reverse the successors in order
10571 // to implement FCMP_UNE.
10572 if (User->getOpcode() == ISD::BR) {
10573 SDValue FalseBB = User->getOperand(1);
10575 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10576 assert(NewBR == User);
10579 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10580 Cond.getOperand(0), Cond.getOperand(1));
10581 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10582 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10583 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10584 Chain, Dest, CC, Cmp);
10585 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
10595 // Look pass the truncate if the high bits are known zero.
10596 if (isTruncWithZeroHighBitsInput(Cond, DAG))
10597 Cond = Cond.getOperand(0);
10599 // We know the result of AND is compared against zero. Try to match
10601 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10602 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
10603 if (NewSetCC.getNode()) {
10604 CC = NewSetCC.getOperand(0);
10605 Cond = NewSetCC.getOperand(1);
10612 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10613 Cond = EmitTest(Cond, X86::COND_NE, DAG);
10615 Cond = ConvertCmpIfNecessary(Cond, DAG);
10616 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10617 Chain, Dest, CC, Cond);
10620 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
10621 // Calls to _alloca is needed to probe the stack when allocating more than 4k
10622 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
10623 // that the guard pages used by the OS virtual memory manager are allocated in
10624 // correct sequence.
10626 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
10627 SelectionDAG &DAG) const {
10628 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
10629 getTargetMachine().Options.EnableSegmentedStacks) &&
10630 "This should be used only on Windows targets or when segmented stacks "
10632 assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
10636 SDValue Chain = Op.getOperand(0);
10637 SDValue Size = Op.getOperand(1);
10638 // FIXME: Ensure alignment here
10640 bool Is64Bit = Subtarget->is64Bit();
10641 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
10643 if (getTargetMachine().Options.EnableSegmentedStacks) {
10644 MachineFunction &MF = DAG.getMachineFunction();
10645 MachineRegisterInfo &MRI = MF.getRegInfo();
10648 // The 64 bit implementation of segmented stacks needs to clobber both r10
10649 // r11. This makes it impossible to use it along with nested parameters.
10650 const Function *F = MF.getFunction();
10652 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
10654 if (I->hasNestAttr())
10655 report_fatal_error("Cannot use segmented stacks with functions that "
10656 "have nested arguments.");
10659 const TargetRegisterClass *AddrRegClass =
10660 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
10661 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
10662 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
10663 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
10664 DAG.getRegister(Vreg, SPTy));
10665 SDValue Ops1[2] = { Value, Chain };
10666 return DAG.getMergeValues(Ops1, 2, dl);
10669 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
10671 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
10672 Flag = Chain.getValue(1);
10673 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10675 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
10676 Flag = Chain.getValue(1);
10678 const X86RegisterInfo *RegInfo =
10679 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
10680 Chain = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
10683 SDValue Ops1[2] = { Chain.getValue(0), Chain };
10684 return DAG.getMergeValues(Ops1, 2, dl);
10688 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
10689 MachineFunction &MF = DAG.getMachineFunction();
10690 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
10692 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10695 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
10696 // vastart just stores the address of the VarArgsFrameIndex slot into the
10697 // memory location argument.
10698 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10700 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
10701 MachinePointerInfo(SV), false, false, 0);
10705 // gp_offset (0 - 6 * 8)
10706 // fp_offset (48 - 48 + 8 * 16)
10707 // overflow_arg_area (point to parameters coming in memory).
10709 SmallVector<SDValue, 8> MemOps;
10710 SDValue FIN = Op.getOperand(1);
10712 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
10713 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
10715 FIN, MachinePointerInfo(SV), false, false, 0);
10716 MemOps.push_back(Store);
10719 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10720 FIN, DAG.getIntPtrConstant(4));
10721 Store = DAG.getStore(Op.getOperand(0), DL,
10722 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
10724 FIN, MachinePointerInfo(SV, 4), false, false, 0);
10725 MemOps.push_back(Store);
10727 // Store ptr to overflow_arg_area
10728 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10729 FIN, DAG.getIntPtrConstant(4));
10730 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10732 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
10733 MachinePointerInfo(SV, 8),
10735 MemOps.push_back(Store);
10737 // Store ptr to reg_save_area.
10738 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10739 FIN, DAG.getIntPtrConstant(8));
10740 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
10742 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
10743 MachinePointerInfo(SV, 16), false, false, 0);
10744 MemOps.push_back(Store);
10745 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
10746 &MemOps[0], MemOps.size());
10749 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
10750 assert(Subtarget->is64Bit() &&
10751 "LowerVAARG only handles 64-bit va_arg!");
10752 assert((Subtarget->isTargetLinux() ||
10753 Subtarget->isTargetDarwin()) &&
10754 "Unhandled target in LowerVAARG");
10755 assert(Op.getNode()->getNumOperands() == 4);
10756 SDValue Chain = Op.getOperand(0);
10757 SDValue SrcPtr = Op.getOperand(1);
10758 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10759 unsigned Align = Op.getConstantOperandVal(3);
10762 EVT ArgVT = Op.getNode()->getValueType(0);
10763 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10764 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
10767 // Decide which area this value should be read from.
10768 // TODO: Implement the AMD64 ABI in its entirety. This simple
10769 // selection mechanism works only for the basic types.
10770 if (ArgVT == MVT::f80) {
10771 llvm_unreachable("va_arg for f80 not yet implemented");
10772 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
10773 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
10774 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
10775 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
10777 llvm_unreachable("Unhandled argument type in LowerVAARG");
10780 if (ArgMode == 2) {
10781 // Sanity Check: Make sure using fp_offset makes sense.
10782 assert(!getTargetMachine().Options.UseSoftFloat &&
10783 !(DAG.getMachineFunction()
10784 .getFunction()->getAttributes()
10785 .hasAttribute(AttributeSet::FunctionIndex,
10786 Attribute::NoImplicitFloat)) &&
10787 Subtarget->hasSSE1());
10790 // Insert VAARG_64 node into the DAG
10791 // VAARG_64 returns two values: Variable Argument Address, Chain
10792 SmallVector<SDValue, 11> InstOps;
10793 InstOps.push_back(Chain);
10794 InstOps.push_back(SrcPtr);
10795 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
10796 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
10797 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
10798 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
10799 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
10800 VTs, &InstOps[0], InstOps.size(),
10802 MachinePointerInfo(SV),
10804 /*Volatile=*/false,
10806 /*WriteMem=*/true);
10807 Chain = VAARG.getValue(1);
10809 // Load the next argument and return it
10810 return DAG.getLoad(ArgVT, dl,
10813 MachinePointerInfo(),
10814 false, false, false, 0);
10817 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
10818 SelectionDAG &DAG) {
10819 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
10820 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
10821 SDValue Chain = Op.getOperand(0);
10822 SDValue DstPtr = Op.getOperand(1);
10823 SDValue SrcPtr = Op.getOperand(2);
10824 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
10825 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10828 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
10829 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
10831 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
10834 // getTargetVShiftNode - Handle vector element shifts where the shift amount
10835 // may or may not be a constant. Takes immediate version of shift as input.
10836 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, EVT VT,
10837 SDValue SrcOp, SDValue ShAmt,
10838 SelectionDAG &DAG) {
10839 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
10841 if (isa<ConstantSDNode>(ShAmt)) {
10842 // Constant may be a TargetConstant. Use a regular constant.
10843 uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
10845 default: llvm_unreachable("Unknown target vector shift node");
10846 case X86ISD::VSHLI:
10847 case X86ISD::VSRLI:
10848 case X86ISD::VSRAI:
10849 return DAG.getNode(Opc, dl, VT, SrcOp,
10850 DAG.getConstant(ShiftAmt, MVT::i32));
10854 // Change opcode to non-immediate version
10856 default: llvm_unreachable("Unknown target vector shift node");
10857 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
10858 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
10859 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
10862 // Need to build a vector containing shift amount
10863 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
10866 ShOps[1] = DAG.getConstant(0, MVT::i32);
10867 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
10868 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
10870 // The return type has to be a 128-bit type with the same element
10871 // type as the input type.
10872 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10873 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
10875 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
10876 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
10879 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
10881 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10883 default: return SDValue(); // Don't custom lower most intrinsics.
10884 // Comparison intrinsics.
10885 case Intrinsic::x86_sse_comieq_ss:
10886 case Intrinsic::x86_sse_comilt_ss:
10887 case Intrinsic::x86_sse_comile_ss:
10888 case Intrinsic::x86_sse_comigt_ss:
10889 case Intrinsic::x86_sse_comige_ss:
10890 case Intrinsic::x86_sse_comineq_ss:
10891 case Intrinsic::x86_sse_ucomieq_ss:
10892 case Intrinsic::x86_sse_ucomilt_ss:
10893 case Intrinsic::x86_sse_ucomile_ss:
10894 case Intrinsic::x86_sse_ucomigt_ss:
10895 case Intrinsic::x86_sse_ucomige_ss:
10896 case Intrinsic::x86_sse_ucomineq_ss:
10897 case Intrinsic::x86_sse2_comieq_sd:
10898 case Intrinsic::x86_sse2_comilt_sd:
10899 case Intrinsic::x86_sse2_comile_sd:
10900 case Intrinsic::x86_sse2_comigt_sd:
10901 case Intrinsic::x86_sse2_comige_sd:
10902 case Intrinsic::x86_sse2_comineq_sd:
10903 case Intrinsic::x86_sse2_ucomieq_sd:
10904 case Intrinsic::x86_sse2_ucomilt_sd:
10905 case Intrinsic::x86_sse2_ucomile_sd:
10906 case Intrinsic::x86_sse2_ucomigt_sd:
10907 case Intrinsic::x86_sse2_ucomige_sd:
10908 case Intrinsic::x86_sse2_ucomineq_sd: {
10912 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10913 case Intrinsic::x86_sse_comieq_ss:
10914 case Intrinsic::x86_sse2_comieq_sd:
10915 Opc = X86ISD::COMI;
10918 case Intrinsic::x86_sse_comilt_ss:
10919 case Intrinsic::x86_sse2_comilt_sd:
10920 Opc = X86ISD::COMI;
10923 case Intrinsic::x86_sse_comile_ss:
10924 case Intrinsic::x86_sse2_comile_sd:
10925 Opc = X86ISD::COMI;
10928 case Intrinsic::x86_sse_comigt_ss:
10929 case Intrinsic::x86_sse2_comigt_sd:
10930 Opc = X86ISD::COMI;
10933 case Intrinsic::x86_sse_comige_ss:
10934 case Intrinsic::x86_sse2_comige_sd:
10935 Opc = X86ISD::COMI;
10938 case Intrinsic::x86_sse_comineq_ss:
10939 case Intrinsic::x86_sse2_comineq_sd:
10940 Opc = X86ISD::COMI;
10943 case Intrinsic::x86_sse_ucomieq_ss:
10944 case Intrinsic::x86_sse2_ucomieq_sd:
10945 Opc = X86ISD::UCOMI;
10948 case Intrinsic::x86_sse_ucomilt_ss:
10949 case Intrinsic::x86_sse2_ucomilt_sd:
10950 Opc = X86ISD::UCOMI;
10953 case Intrinsic::x86_sse_ucomile_ss:
10954 case Intrinsic::x86_sse2_ucomile_sd:
10955 Opc = X86ISD::UCOMI;
10958 case Intrinsic::x86_sse_ucomigt_ss:
10959 case Intrinsic::x86_sse2_ucomigt_sd:
10960 Opc = X86ISD::UCOMI;
10963 case Intrinsic::x86_sse_ucomige_ss:
10964 case Intrinsic::x86_sse2_ucomige_sd:
10965 Opc = X86ISD::UCOMI;
10968 case Intrinsic::x86_sse_ucomineq_ss:
10969 case Intrinsic::x86_sse2_ucomineq_sd:
10970 Opc = X86ISD::UCOMI;
10975 SDValue LHS = Op.getOperand(1);
10976 SDValue RHS = Op.getOperand(2);
10977 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
10978 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
10979 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
10980 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10981 DAG.getConstant(X86CC, MVT::i8), Cond);
10982 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10985 // Arithmetic intrinsics.
10986 case Intrinsic::x86_sse2_pmulu_dq:
10987 case Intrinsic::x86_avx2_pmulu_dq:
10988 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
10989 Op.getOperand(1), Op.getOperand(2));
10991 // SSE2/AVX2 sub with unsigned saturation intrinsics
10992 case Intrinsic::x86_sse2_psubus_b:
10993 case Intrinsic::x86_sse2_psubus_w:
10994 case Intrinsic::x86_avx2_psubus_b:
10995 case Intrinsic::x86_avx2_psubus_w:
10996 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
10997 Op.getOperand(1), Op.getOperand(2));
10999 // SSE3/AVX horizontal add/sub intrinsics
11000 case Intrinsic::x86_sse3_hadd_ps:
11001 case Intrinsic::x86_sse3_hadd_pd:
11002 case Intrinsic::x86_avx_hadd_ps_256:
11003 case Intrinsic::x86_avx_hadd_pd_256:
11004 case Intrinsic::x86_sse3_hsub_ps:
11005 case Intrinsic::x86_sse3_hsub_pd:
11006 case Intrinsic::x86_avx_hsub_ps_256:
11007 case Intrinsic::x86_avx_hsub_pd_256:
11008 case Intrinsic::x86_ssse3_phadd_w_128:
11009 case Intrinsic::x86_ssse3_phadd_d_128:
11010 case Intrinsic::x86_avx2_phadd_w:
11011 case Intrinsic::x86_avx2_phadd_d:
11012 case Intrinsic::x86_ssse3_phsub_w_128:
11013 case Intrinsic::x86_ssse3_phsub_d_128:
11014 case Intrinsic::x86_avx2_phsub_w:
11015 case Intrinsic::x86_avx2_phsub_d: {
11018 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11019 case Intrinsic::x86_sse3_hadd_ps:
11020 case Intrinsic::x86_sse3_hadd_pd:
11021 case Intrinsic::x86_avx_hadd_ps_256:
11022 case Intrinsic::x86_avx_hadd_pd_256:
11023 Opcode = X86ISD::FHADD;
11025 case Intrinsic::x86_sse3_hsub_ps:
11026 case Intrinsic::x86_sse3_hsub_pd:
11027 case Intrinsic::x86_avx_hsub_ps_256:
11028 case Intrinsic::x86_avx_hsub_pd_256:
11029 Opcode = X86ISD::FHSUB;
11031 case Intrinsic::x86_ssse3_phadd_w_128:
11032 case Intrinsic::x86_ssse3_phadd_d_128:
11033 case Intrinsic::x86_avx2_phadd_w:
11034 case Intrinsic::x86_avx2_phadd_d:
11035 Opcode = X86ISD::HADD;
11037 case Intrinsic::x86_ssse3_phsub_w_128:
11038 case Intrinsic::x86_ssse3_phsub_d_128:
11039 case Intrinsic::x86_avx2_phsub_w:
11040 case Intrinsic::x86_avx2_phsub_d:
11041 Opcode = X86ISD::HSUB;
11044 return DAG.getNode(Opcode, dl, Op.getValueType(),
11045 Op.getOperand(1), Op.getOperand(2));
11048 // SSE2/SSE41/AVX2 integer max/min intrinsics.
11049 case Intrinsic::x86_sse2_pmaxu_b:
11050 case Intrinsic::x86_sse41_pmaxuw:
11051 case Intrinsic::x86_sse41_pmaxud:
11052 case Intrinsic::x86_avx2_pmaxu_b:
11053 case Intrinsic::x86_avx2_pmaxu_w:
11054 case Intrinsic::x86_avx2_pmaxu_d:
11055 case Intrinsic::x86_sse2_pminu_b:
11056 case Intrinsic::x86_sse41_pminuw:
11057 case Intrinsic::x86_sse41_pminud:
11058 case Intrinsic::x86_avx2_pminu_b:
11059 case Intrinsic::x86_avx2_pminu_w:
11060 case Intrinsic::x86_avx2_pminu_d:
11061 case Intrinsic::x86_sse41_pmaxsb:
11062 case Intrinsic::x86_sse2_pmaxs_w:
11063 case Intrinsic::x86_sse41_pmaxsd:
11064 case Intrinsic::x86_avx2_pmaxs_b:
11065 case Intrinsic::x86_avx2_pmaxs_w:
11066 case Intrinsic::x86_avx2_pmaxs_d:
11067 case Intrinsic::x86_sse41_pminsb:
11068 case Intrinsic::x86_sse2_pmins_w:
11069 case Intrinsic::x86_sse41_pminsd:
11070 case Intrinsic::x86_avx2_pmins_b:
11071 case Intrinsic::x86_avx2_pmins_w:
11072 case Intrinsic::x86_avx2_pmins_d: {
11075 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11076 case Intrinsic::x86_sse2_pmaxu_b:
11077 case Intrinsic::x86_sse41_pmaxuw:
11078 case Intrinsic::x86_sse41_pmaxud:
11079 case Intrinsic::x86_avx2_pmaxu_b:
11080 case Intrinsic::x86_avx2_pmaxu_w:
11081 case Intrinsic::x86_avx2_pmaxu_d:
11082 Opcode = X86ISD::UMAX;
11084 case Intrinsic::x86_sse2_pminu_b:
11085 case Intrinsic::x86_sse41_pminuw:
11086 case Intrinsic::x86_sse41_pminud:
11087 case Intrinsic::x86_avx2_pminu_b:
11088 case Intrinsic::x86_avx2_pminu_w:
11089 case Intrinsic::x86_avx2_pminu_d:
11090 Opcode = X86ISD::UMIN;
11092 case Intrinsic::x86_sse41_pmaxsb:
11093 case Intrinsic::x86_sse2_pmaxs_w:
11094 case Intrinsic::x86_sse41_pmaxsd:
11095 case Intrinsic::x86_avx2_pmaxs_b:
11096 case Intrinsic::x86_avx2_pmaxs_w:
11097 case Intrinsic::x86_avx2_pmaxs_d:
11098 Opcode = X86ISD::SMAX;
11100 case Intrinsic::x86_sse41_pminsb:
11101 case Intrinsic::x86_sse2_pmins_w:
11102 case Intrinsic::x86_sse41_pminsd:
11103 case Intrinsic::x86_avx2_pmins_b:
11104 case Intrinsic::x86_avx2_pmins_w:
11105 case Intrinsic::x86_avx2_pmins_d:
11106 Opcode = X86ISD::SMIN;
11109 return DAG.getNode(Opcode, dl, Op.getValueType(),
11110 Op.getOperand(1), Op.getOperand(2));
11113 // SSE/SSE2/AVX floating point max/min intrinsics.
11114 case Intrinsic::x86_sse_max_ps:
11115 case Intrinsic::x86_sse2_max_pd:
11116 case Intrinsic::x86_avx_max_ps_256:
11117 case Intrinsic::x86_avx_max_pd_256:
11118 case Intrinsic::x86_sse_min_ps:
11119 case Intrinsic::x86_sse2_min_pd:
11120 case Intrinsic::x86_avx_min_ps_256:
11121 case Intrinsic::x86_avx_min_pd_256: {
11124 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11125 case Intrinsic::x86_sse_max_ps:
11126 case Intrinsic::x86_sse2_max_pd:
11127 case Intrinsic::x86_avx_max_ps_256:
11128 case Intrinsic::x86_avx_max_pd_256:
11129 Opcode = X86ISD::FMAX;
11131 case Intrinsic::x86_sse_min_ps:
11132 case Intrinsic::x86_sse2_min_pd:
11133 case Intrinsic::x86_avx_min_ps_256:
11134 case Intrinsic::x86_avx_min_pd_256:
11135 Opcode = X86ISD::FMIN;
11138 return DAG.getNode(Opcode, dl, Op.getValueType(),
11139 Op.getOperand(1), Op.getOperand(2));
11142 // AVX2 variable shift intrinsics
11143 case Intrinsic::x86_avx2_psllv_d:
11144 case Intrinsic::x86_avx2_psllv_q:
11145 case Intrinsic::x86_avx2_psllv_d_256:
11146 case Intrinsic::x86_avx2_psllv_q_256:
11147 case Intrinsic::x86_avx2_psrlv_d:
11148 case Intrinsic::x86_avx2_psrlv_q:
11149 case Intrinsic::x86_avx2_psrlv_d_256:
11150 case Intrinsic::x86_avx2_psrlv_q_256:
11151 case Intrinsic::x86_avx2_psrav_d:
11152 case Intrinsic::x86_avx2_psrav_d_256: {
11155 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11156 case Intrinsic::x86_avx2_psllv_d:
11157 case Intrinsic::x86_avx2_psllv_q:
11158 case Intrinsic::x86_avx2_psllv_d_256:
11159 case Intrinsic::x86_avx2_psllv_q_256:
11162 case Intrinsic::x86_avx2_psrlv_d:
11163 case Intrinsic::x86_avx2_psrlv_q:
11164 case Intrinsic::x86_avx2_psrlv_d_256:
11165 case Intrinsic::x86_avx2_psrlv_q_256:
11168 case Intrinsic::x86_avx2_psrav_d:
11169 case Intrinsic::x86_avx2_psrav_d_256:
11173 return DAG.getNode(Opcode, dl, Op.getValueType(),
11174 Op.getOperand(1), Op.getOperand(2));
11177 case Intrinsic::x86_ssse3_pshuf_b_128:
11178 case Intrinsic::x86_avx2_pshuf_b:
11179 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
11180 Op.getOperand(1), Op.getOperand(2));
11182 case Intrinsic::x86_ssse3_psign_b_128:
11183 case Intrinsic::x86_ssse3_psign_w_128:
11184 case Intrinsic::x86_ssse3_psign_d_128:
11185 case Intrinsic::x86_avx2_psign_b:
11186 case Intrinsic::x86_avx2_psign_w:
11187 case Intrinsic::x86_avx2_psign_d:
11188 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
11189 Op.getOperand(1), Op.getOperand(2));
11191 case Intrinsic::x86_sse41_insertps:
11192 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
11193 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11195 case Intrinsic::x86_avx_vperm2f128_ps_256:
11196 case Intrinsic::x86_avx_vperm2f128_pd_256:
11197 case Intrinsic::x86_avx_vperm2f128_si_256:
11198 case Intrinsic::x86_avx2_vperm2i128:
11199 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
11200 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11202 case Intrinsic::x86_avx2_permd:
11203 case Intrinsic::x86_avx2_permps:
11204 // Operands intentionally swapped. Mask is last operand to intrinsic,
11205 // but second operand for node/intruction.
11206 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
11207 Op.getOperand(2), Op.getOperand(1));
11209 case Intrinsic::x86_sse_sqrt_ps:
11210 case Intrinsic::x86_sse2_sqrt_pd:
11211 case Intrinsic::x86_avx_sqrt_ps_256:
11212 case Intrinsic::x86_avx_sqrt_pd_256:
11213 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
11215 // ptest and testp intrinsics. The intrinsic these come from are designed to
11216 // return an integer value, not just an instruction so lower it to the ptest
11217 // or testp pattern and a setcc for the result.
11218 case Intrinsic::x86_sse41_ptestz:
11219 case Intrinsic::x86_sse41_ptestc:
11220 case Intrinsic::x86_sse41_ptestnzc:
11221 case Intrinsic::x86_avx_ptestz_256:
11222 case Intrinsic::x86_avx_ptestc_256:
11223 case Intrinsic::x86_avx_ptestnzc_256:
11224 case Intrinsic::x86_avx_vtestz_ps:
11225 case Intrinsic::x86_avx_vtestc_ps:
11226 case Intrinsic::x86_avx_vtestnzc_ps:
11227 case Intrinsic::x86_avx_vtestz_pd:
11228 case Intrinsic::x86_avx_vtestc_pd:
11229 case Intrinsic::x86_avx_vtestnzc_pd:
11230 case Intrinsic::x86_avx_vtestz_ps_256:
11231 case Intrinsic::x86_avx_vtestc_ps_256:
11232 case Intrinsic::x86_avx_vtestnzc_ps_256:
11233 case Intrinsic::x86_avx_vtestz_pd_256:
11234 case Intrinsic::x86_avx_vtestc_pd_256:
11235 case Intrinsic::x86_avx_vtestnzc_pd_256: {
11236 bool IsTestPacked = false;
11239 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
11240 case Intrinsic::x86_avx_vtestz_ps:
11241 case Intrinsic::x86_avx_vtestz_pd:
11242 case Intrinsic::x86_avx_vtestz_ps_256:
11243 case Intrinsic::x86_avx_vtestz_pd_256:
11244 IsTestPacked = true; // Fallthrough
11245 case Intrinsic::x86_sse41_ptestz:
11246 case Intrinsic::x86_avx_ptestz_256:
11248 X86CC = X86::COND_E;
11250 case Intrinsic::x86_avx_vtestc_ps:
11251 case Intrinsic::x86_avx_vtestc_pd:
11252 case Intrinsic::x86_avx_vtestc_ps_256:
11253 case Intrinsic::x86_avx_vtestc_pd_256:
11254 IsTestPacked = true; // Fallthrough
11255 case Intrinsic::x86_sse41_ptestc:
11256 case Intrinsic::x86_avx_ptestc_256:
11258 X86CC = X86::COND_B;
11260 case Intrinsic::x86_avx_vtestnzc_ps:
11261 case Intrinsic::x86_avx_vtestnzc_pd:
11262 case Intrinsic::x86_avx_vtestnzc_ps_256:
11263 case Intrinsic::x86_avx_vtestnzc_pd_256:
11264 IsTestPacked = true; // Fallthrough
11265 case Intrinsic::x86_sse41_ptestnzc:
11266 case Intrinsic::x86_avx_ptestnzc_256:
11268 X86CC = X86::COND_A;
11272 SDValue LHS = Op.getOperand(1);
11273 SDValue RHS = Op.getOperand(2);
11274 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
11275 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
11276 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
11277 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
11278 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11281 // SSE/AVX shift intrinsics
11282 case Intrinsic::x86_sse2_psll_w:
11283 case Intrinsic::x86_sse2_psll_d:
11284 case Intrinsic::x86_sse2_psll_q:
11285 case Intrinsic::x86_avx2_psll_w:
11286 case Intrinsic::x86_avx2_psll_d:
11287 case Intrinsic::x86_avx2_psll_q:
11288 case Intrinsic::x86_sse2_psrl_w:
11289 case Intrinsic::x86_sse2_psrl_d:
11290 case Intrinsic::x86_sse2_psrl_q:
11291 case Intrinsic::x86_avx2_psrl_w:
11292 case Intrinsic::x86_avx2_psrl_d:
11293 case Intrinsic::x86_avx2_psrl_q:
11294 case Intrinsic::x86_sse2_psra_w:
11295 case Intrinsic::x86_sse2_psra_d:
11296 case Intrinsic::x86_avx2_psra_w:
11297 case Intrinsic::x86_avx2_psra_d: {
11300 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11301 case Intrinsic::x86_sse2_psll_w:
11302 case Intrinsic::x86_sse2_psll_d:
11303 case Intrinsic::x86_sse2_psll_q:
11304 case Intrinsic::x86_avx2_psll_w:
11305 case Intrinsic::x86_avx2_psll_d:
11306 case Intrinsic::x86_avx2_psll_q:
11307 Opcode = X86ISD::VSHL;
11309 case Intrinsic::x86_sse2_psrl_w:
11310 case Intrinsic::x86_sse2_psrl_d:
11311 case Intrinsic::x86_sse2_psrl_q:
11312 case Intrinsic::x86_avx2_psrl_w:
11313 case Intrinsic::x86_avx2_psrl_d:
11314 case Intrinsic::x86_avx2_psrl_q:
11315 Opcode = X86ISD::VSRL;
11317 case Intrinsic::x86_sse2_psra_w:
11318 case Intrinsic::x86_sse2_psra_d:
11319 case Intrinsic::x86_avx2_psra_w:
11320 case Intrinsic::x86_avx2_psra_d:
11321 Opcode = X86ISD::VSRA;
11324 return DAG.getNode(Opcode, dl, Op.getValueType(),
11325 Op.getOperand(1), Op.getOperand(2));
11328 // SSE/AVX immediate shift intrinsics
11329 case Intrinsic::x86_sse2_pslli_w:
11330 case Intrinsic::x86_sse2_pslli_d:
11331 case Intrinsic::x86_sse2_pslli_q:
11332 case Intrinsic::x86_avx2_pslli_w:
11333 case Intrinsic::x86_avx2_pslli_d:
11334 case Intrinsic::x86_avx2_pslli_q:
11335 case Intrinsic::x86_sse2_psrli_w:
11336 case Intrinsic::x86_sse2_psrli_d:
11337 case Intrinsic::x86_sse2_psrli_q:
11338 case Intrinsic::x86_avx2_psrli_w:
11339 case Intrinsic::x86_avx2_psrli_d:
11340 case Intrinsic::x86_avx2_psrli_q:
11341 case Intrinsic::x86_sse2_psrai_w:
11342 case Intrinsic::x86_sse2_psrai_d:
11343 case Intrinsic::x86_avx2_psrai_w:
11344 case Intrinsic::x86_avx2_psrai_d: {
11347 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11348 case Intrinsic::x86_sse2_pslli_w:
11349 case Intrinsic::x86_sse2_pslli_d:
11350 case Intrinsic::x86_sse2_pslli_q:
11351 case Intrinsic::x86_avx2_pslli_w:
11352 case Intrinsic::x86_avx2_pslli_d:
11353 case Intrinsic::x86_avx2_pslli_q:
11354 Opcode = X86ISD::VSHLI;
11356 case Intrinsic::x86_sse2_psrli_w:
11357 case Intrinsic::x86_sse2_psrli_d:
11358 case Intrinsic::x86_sse2_psrli_q:
11359 case Intrinsic::x86_avx2_psrli_w:
11360 case Intrinsic::x86_avx2_psrli_d:
11361 case Intrinsic::x86_avx2_psrli_q:
11362 Opcode = X86ISD::VSRLI;
11364 case Intrinsic::x86_sse2_psrai_w:
11365 case Intrinsic::x86_sse2_psrai_d:
11366 case Intrinsic::x86_avx2_psrai_w:
11367 case Intrinsic::x86_avx2_psrai_d:
11368 Opcode = X86ISD::VSRAI;
11371 return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
11372 Op.getOperand(1), Op.getOperand(2), DAG);
11375 case Intrinsic::x86_sse42_pcmpistria128:
11376 case Intrinsic::x86_sse42_pcmpestria128:
11377 case Intrinsic::x86_sse42_pcmpistric128:
11378 case Intrinsic::x86_sse42_pcmpestric128:
11379 case Intrinsic::x86_sse42_pcmpistrio128:
11380 case Intrinsic::x86_sse42_pcmpestrio128:
11381 case Intrinsic::x86_sse42_pcmpistris128:
11382 case Intrinsic::x86_sse42_pcmpestris128:
11383 case Intrinsic::x86_sse42_pcmpistriz128:
11384 case Intrinsic::x86_sse42_pcmpestriz128: {
11388 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11389 case Intrinsic::x86_sse42_pcmpistria128:
11390 Opcode = X86ISD::PCMPISTRI;
11391 X86CC = X86::COND_A;
11393 case Intrinsic::x86_sse42_pcmpestria128:
11394 Opcode = X86ISD::PCMPESTRI;
11395 X86CC = X86::COND_A;
11397 case Intrinsic::x86_sse42_pcmpistric128:
11398 Opcode = X86ISD::PCMPISTRI;
11399 X86CC = X86::COND_B;
11401 case Intrinsic::x86_sse42_pcmpestric128:
11402 Opcode = X86ISD::PCMPESTRI;
11403 X86CC = X86::COND_B;
11405 case Intrinsic::x86_sse42_pcmpistrio128:
11406 Opcode = X86ISD::PCMPISTRI;
11407 X86CC = X86::COND_O;
11409 case Intrinsic::x86_sse42_pcmpestrio128:
11410 Opcode = X86ISD::PCMPESTRI;
11411 X86CC = X86::COND_O;
11413 case Intrinsic::x86_sse42_pcmpistris128:
11414 Opcode = X86ISD::PCMPISTRI;
11415 X86CC = X86::COND_S;
11417 case Intrinsic::x86_sse42_pcmpestris128:
11418 Opcode = X86ISD::PCMPESTRI;
11419 X86CC = X86::COND_S;
11421 case Intrinsic::x86_sse42_pcmpistriz128:
11422 Opcode = X86ISD::PCMPISTRI;
11423 X86CC = X86::COND_E;
11425 case Intrinsic::x86_sse42_pcmpestriz128:
11426 Opcode = X86ISD::PCMPESTRI;
11427 X86CC = X86::COND_E;
11430 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
11431 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11432 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
11433 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11434 DAG.getConstant(X86CC, MVT::i8),
11435 SDValue(PCMP.getNode(), 1));
11436 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11439 case Intrinsic::x86_sse42_pcmpistri128:
11440 case Intrinsic::x86_sse42_pcmpestri128: {
11442 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
11443 Opcode = X86ISD::PCMPISTRI;
11445 Opcode = X86ISD::PCMPESTRI;
11447 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
11448 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11449 return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
11451 case Intrinsic::x86_fma_vfmadd_ps:
11452 case Intrinsic::x86_fma_vfmadd_pd:
11453 case Intrinsic::x86_fma_vfmsub_ps:
11454 case Intrinsic::x86_fma_vfmsub_pd:
11455 case Intrinsic::x86_fma_vfnmadd_ps:
11456 case Intrinsic::x86_fma_vfnmadd_pd:
11457 case Intrinsic::x86_fma_vfnmsub_ps:
11458 case Intrinsic::x86_fma_vfnmsub_pd:
11459 case Intrinsic::x86_fma_vfmaddsub_ps:
11460 case Intrinsic::x86_fma_vfmaddsub_pd:
11461 case Intrinsic::x86_fma_vfmsubadd_ps:
11462 case Intrinsic::x86_fma_vfmsubadd_pd:
11463 case Intrinsic::x86_fma_vfmadd_ps_256:
11464 case Intrinsic::x86_fma_vfmadd_pd_256:
11465 case Intrinsic::x86_fma_vfmsub_ps_256:
11466 case Intrinsic::x86_fma_vfmsub_pd_256:
11467 case Intrinsic::x86_fma_vfnmadd_ps_256:
11468 case Intrinsic::x86_fma_vfnmadd_pd_256:
11469 case Intrinsic::x86_fma_vfnmsub_ps_256:
11470 case Intrinsic::x86_fma_vfnmsub_pd_256:
11471 case Intrinsic::x86_fma_vfmaddsub_ps_256:
11472 case Intrinsic::x86_fma_vfmaddsub_pd_256:
11473 case Intrinsic::x86_fma_vfmsubadd_ps_256:
11474 case Intrinsic::x86_fma_vfmsubadd_pd_256: {
11477 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11478 case Intrinsic::x86_fma_vfmadd_ps:
11479 case Intrinsic::x86_fma_vfmadd_pd:
11480 case Intrinsic::x86_fma_vfmadd_ps_256:
11481 case Intrinsic::x86_fma_vfmadd_pd_256:
11482 Opc = X86ISD::FMADD;
11484 case Intrinsic::x86_fma_vfmsub_ps:
11485 case Intrinsic::x86_fma_vfmsub_pd:
11486 case Intrinsic::x86_fma_vfmsub_ps_256:
11487 case Intrinsic::x86_fma_vfmsub_pd_256:
11488 Opc = X86ISD::FMSUB;
11490 case Intrinsic::x86_fma_vfnmadd_ps:
11491 case Intrinsic::x86_fma_vfnmadd_pd:
11492 case Intrinsic::x86_fma_vfnmadd_ps_256:
11493 case Intrinsic::x86_fma_vfnmadd_pd_256:
11494 Opc = X86ISD::FNMADD;
11496 case Intrinsic::x86_fma_vfnmsub_ps:
11497 case Intrinsic::x86_fma_vfnmsub_pd:
11498 case Intrinsic::x86_fma_vfnmsub_ps_256:
11499 case Intrinsic::x86_fma_vfnmsub_pd_256:
11500 Opc = X86ISD::FNMSUB;
11502 case Intrinsic::x86_fma_vfmaddsub_ps:
11503 case Intrinsic::x86_fma_vfmaddsub_pd:
11504 case Intrinsic::x86_fma_vfmaddsub_ps_256:
11505 case Intrinsic::x86_fma_vfmaddsub_pd_256:
11506 Opc = X86ISD::FMADDSUB;
11508 case Intrinsic::x86_fma_vfmsubadd_ps:
11509 case Intrinsic::x86_fma_vfmsubadd_pd:
11510 case Intrinsic::x86_fma_vfmsubadd_ps_256:
11511 case Intrinsic::x86_fma_vfmsubadd_pd_256:
11512 Opc = X86ISD::FMSUBADD;
11516 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
11517 Op.getOperand(2), Op.getOperand(3));
11522 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
11524 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11526 default: return SDValue(); // Don't custom lower most intrinsics.
11528 // RDRAND/RDSEED intrinsics.
11529 case Intrinsic::x86_rdrand_16:
11530 case Intrinsic::x86_rdrand_32:
11531 case Intrinsic::x86_rdrand_64:
11532 case Intrinsic::x86_rdseed_16:
11533 case Intrinsic::x86_rdseed_32:
11534 case Intrinsic::x86_rdseed_64: {
11535 unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
11536 IntNo == Intrinsic::x86_rdseed_32 ||
11537 IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
11539 // Emit the node with the right value type.
11540 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
11541 SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
11543 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
11544 // Otherwise return the value from Rand, which is always 0, casted to i32.
11545 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
11546 DAG.getConstant(1, Op->getValueType(1)),
11547 DAG.getConstant(X86::COND_B, MVT::i32),
11548 SDValue(Result.getNode(), 1) };
11549 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
11550 DAG.getVTList(Op->getValueType(1), MVT::Glue),
11551 Ops, array_lengthof(Ops));
11553 // Return { result, isValid, chain }.
11554 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
11555 SDValue(Result.getNode(), 2));
11558 // XTEST intrinsics.
11559 case Intrinsic::x86_xtest: {
11560 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
11561 SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
11562 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11563 DAG.getConstant(X86::COND_NE, MVT::i8),
11565 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
11566 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
11567 Ret, SDValue(InTrans.getNode(), 1));
11572 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
11573 SelectionDAG &DAG) const {
11574 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11575 MFI->setReturnAddressIsTaken(true);
11577 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11579 EVT PtrVT = getPointerTy();
11582 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
11583 const X86RegisterInfo *RegInfo =
11584 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11585 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
11586 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11587 DAG.getNode(ISD::ADD, dl, PtrVT,
11588 FrameAddr, Offset),
11589 MachinePointerInfo(), false, false, false, 0);
11592 // Just load the return address.
11593 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
11594 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11595 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
11598 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
11599 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11600 MFI->setFrameAddressIsTaken(true);
11602 EVT VT = Op.getValueType();
11603 SDLoc dl(Op); // FIXME probably not meaningful
11604 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11605 const X86RegisterInfo *RegInfo =
11606 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11607 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
11608 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
11609 (FrameReg == X86::EBP && VT == MVT::i32)) &&
11610 "Invalid Frame Register!");
11611 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
11613 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
11614 MachinePointerInfo(),
11615 false, false, false, 0);
11619 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
11620 SelectionDAG &DAG) const {
11621 const X86RegisterInfo *RegInfo =
11622 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11623 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
11626 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
11627 SDValue Chain = Op.getOperand(0);
11628 SDValue Offset = Op.getOperand(1);
11629 SDValue Handler = Op.getOperand(2);
11632 EVT PtrVT = getPointerTy();
11633 const X86RegisterInfo *RegInfo =
11634 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11635 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
11636 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
11637 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
11638 "Invalid Frame Register!");
11639 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
11640 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
11642 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
11643 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
11644 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
11645 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
11647 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
11649 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
11650 DAG.getRegister(StoreAddrReg, PtrVT));
11653 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
11654 SelectionDAG &DAG) const {
11656 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
11657 DAG.getVTList(MVT::i32, MVT::Other),
11658 Op.getOperand(0), Op.getOperand(1));
11661 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
11662 SelectionDAG &DAG) const {
11664 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
11665 Op.getOperand(0), Op.getOperand(1));
11668 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
11669 return Op.getOperand(0);
11672 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
11673 SelectionDAG &DAG) const {
11674 SDValue Root = Op.getOperand(0);
11675 SDValue Trmp = Op.getOperand(1); // trampoline
11676 SDValue FPtr = Op.getOperand(2); // nested function
11677 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
11680 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11681 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
11683 if (Subtarget->is64Bit()) {
11684 SDValue OutChains[6];
11686 // Large code-model.
11687 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
11688 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
11690 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
11691 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
11693 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
11695 // Load the pointer to the nested function into R11.
11696 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
11697 SDValue Addr = Trmp;
11698 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11699 Addr, MachinePointerInfo(TrmpAddr),
11702 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11703 DAG.getConstant(2, MVT::i64));
11704 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
11705 MachinePointerInfo(TrmpAddr, 2),
11708 // Load the 'nest' parameter value into R10.
11709 // R10 is specified in X86CallingConv.td
11710 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
11711 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11712 DAG.getConstant(10, MVT::i64));
11713 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11714 Addr, MachinePointerInfo(TrmpAddr, 10),
11717 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11718 DAG.getConstant(12, MVT::i64));
11719 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
11720 MachinePointerInfo(TrmpAddr, 12),
11723 // Jump to the nested function.
11724 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
11725 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11726 DAG.getConstant(20, MVT::i64));
11727 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11728 Addr, MachinePointerInfo(TrmpAddr, 20),
11731 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
11732 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11733 DAG.getConstant(22, MVT::i64));
11734 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
11735 MachinePointerInfo(TrmpAddr, 22),
11738 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
11740 const Function *Func =
11741 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
11742 CallingConv::ID CC = Func->getCallingConv();
11747 llvm_unreachable("Unsupported calling convention");
11748 case CallingConv::C:
11749 case CallingConv::X86_StdCall: {
11750 // Pass 'nest' parameter in ECX.
11751 // Must be kept in sync with X86CallingConv.td
11752 NestReg = X86::ECX;
11754 // Check that ECX wasn't needed by an 'inreg' parameter.
11755 FunctionType *FTy = Func->getFunctionType();
11756 const AttributeSet &Attrs = Func->getAttributes();
11758 if (!Attrs.isEmpty() && !Func->isVarArg()) {
11759 unsigned InRegCount = 0;
11762 for (FunctionType::param_iterator I = FTy->param_begin(),
11763 E = FTy->param_end(); I != E; ++I, ++Idx)
11764 if (Attrs.hasAttribute(Idx, Attribute::InReg))
11765 // FIXME: should only count parameters that are lowered to integers.
11766 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
11768 if (InRegCount > 2) {
11769 report_fatal_error("Nest register in use - reduce number of inreg"
11775 case CallingConv::X86_FastCall:
11776 case CallingConv::X86_ThisCall:
11777 case CallingConv::Fast:
11778 // Pass 'nest' parameter in EAX.
11779 // Must be kept in sync with X86CallingConv.td
11780 NestReg = X86::EAX;
11784 SDValue OutChains[4];
11785 SDValue Addr, Disp;
11787 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11788 DAG.getConstant(10, MVT::i32));
11789 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
11791 // This is storing the opcode for MOV32ri.
11792 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
11793 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
11794 OutChains[0] = DAG.getStore(Root, dl,
11795 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
11796 Trmp, MachinePointerInfo(TrmpAddr),
11799 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11800 DAG.getConstant(1, MVT::i32));
11801 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
11802 MachinePointerInfo(TrmpAddr, 1),
11805 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
11806 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11807 DAG.getConstant(5, MVT::i32));
11808 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
11809 MachinePointerInfo(TrmpAddr, 5),
11812 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11813 DAG.getConstant(6, MVT::i32));
11814 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
11815 MachinePointerInfo(TrmpAddr, 6),
11818 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
11822 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
11823 SelectionDAG &DAG) const {
11825 The rounding mode is in bits 11:10 of FPSR, and has the following
11827 00 Round to nearest
11832 FLT_ROUNDS, on the other hand, expects the following:
11839 To perform the conversion, we do:
11840 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
11843 MachineFunction &MF = DAG.getMachineFunction();
11844 const TargetMachine &TM = MF.getTarget();
11845 const TargetFrameLowering &TFI = *TM.getFrameLowering();
11846 unsigned StackAlignment = TFI.getStackAlignment();
11847 EVT VT = Op.getValueType();
11850 // Save FP Control Word to stack slot
11851 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
11852 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11854 MachineMemOperand *MMO =
11855 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11856 MachineMemOperand::MOStore, 2, 2);
11858 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
11859 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
11860 DAG.getVTList(MVT::Other),
11861 Ops, array_lengthof(Ops), MVT::i16,
11864 // Load FP Control Word from stack slot
11865 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
11866 MachinePointerInfo(), false, false, false, 0);
11868 // Transform as necessary
11870 DAG.getNode(ISD::SRL, DL, MVT::i16,
11871 DAG.getNode(ISD::AND, DL, MVT::i16,
11872 CWD, DAG.getConstant(0x800, MVT::i16)),
11873 DAG.getConstant(11, MVT::i8));
11875 DAG.getNode(ISD::SRL, DL, MVT::i16,
11876 DAG.getNode(ISD::AND, DL, MVT::i16,
11877 CWD, DAG.getConstant(0x400, MVT::i16)),
11878 DAG.getConstant(9, MVT::i8));
11881 DAG.getNode(ISD::AND, DL, MVT::i16,
11882 DAG.getNode(ISD::ADD, DL, MVT::i16,
11883 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
11884 DAG.getConstant(1, MVT::i16)),
11885 DAG.getConstant(3, MVT::i16));
11887 return DAG.getNode((VT.getSizeInBits() < 16 ?
11888 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
11891 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
11892 EVT VT = Op.getValueType();
11894 unsigned NumBits = VT.getSizeInBits();
11897 Op = Op.getOperand(0);
11898 if (VT == MVT::i8) {
11899 // Zero extend to i32 since there is not an i8 bsr.
11901 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11904 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
11905 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11906 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11908 // If src is zero (i.e. bsr sets ZF), returns NumBits.
11911 DAG.getConstant(NumBits+NumBits-1, OpVT),
11912 DAG.getConstant(X86::COND_E, MVT::i8),
11915 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
11917 // Finally xor with NumBits-1.
11918 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11921 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11925 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
11926 EVT VT = Op.getValueType();
11928 unsigned NumBits = VT.getSizeInBits();
11931 Op = Op.getOperand(0);
11932 if (VT == MVT::i8) {
11933 // Zero extend to i32 since there is not an i8 bsr.
11935 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11938 // Issue a bsr (scan bits in reverse).
11939 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11940 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11942 // And xor with NumBits-1.
11943 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11946 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11950 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
11951 EVT VT = Op.getValueType();
11952 unsigned NumBits = VT.getSizeInBits();
11954 Op = Op.getOperand(0);
11956 // Issue a bsf (scan bits forward) which also sets EFLAGS.
11957 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11958 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
11960 // If src is zero (i.e. bsf sets ZF), returns NumBits.
11963 DAG.getConstant(NumBits, VT),
11964 DAG.getConstant(X86::COND_E, MVT::i8),
11967 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
11970 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
11971 // ones, and then concatenate the result back.
11972 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
11973 EVT VT = Op.getValueType();
11975 assert(VT.is256BitVector() && VT.isInteger() &&
11976 "Unsupported value type for operation");
11978 unsigned NumElems = VT.getVectorNumElements();
11981 // Extract the LHS vectors
11982 SDValue LHS = Op.getOperand(0);
11983 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11984 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11986 // Extract the RHS vectors
11987 SDValue RHS = Op.getOperand(1);
11988 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
11989 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
11991 MVT EltVT = VT.getVectorElementType().getSimpleVT();
11992 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11994 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
11995 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
11996 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
11999 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
12000 assert(Op.getValueType().is256BitVector() &&
12001 Op.getValueType().isInteger() &&
12002 "Only handle AVX 256-bit vector integer operation");
12003 return Lower256IntArith(Op, DAG);
12006 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
12007 assert(Op.getValueType().is256BitVector() &&
12008 Op.getValueType().isInteger() &&
12009 "Only handle AVX 256-bit vector integer operation");
12010 return Lower256IntArith(Op, DAG);
12013 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
12014 SelectionDAG &DAG) {
12016 EVT VT = Op.getValueType();
12018 // Decompose 256-bit ops into smaller 128-bit ops.
12019 if (VT.is256BitVector() && !Subtarget->hasInt256())
12020 return Lower256IntArith(Op, DAG);
12022 SDValue A = Op.getOperand(0);
12023 SDValue B = Op.getOperand(1);
12025 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
12026 if (VT == MVT::v4i32) {
12027 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
12028 "Should not custom lower when pmuldq is available!");
12030 // Extract the odd parts.
12031 static const int UnpackMask[] = { 1, -1, 3, -1 };
12032 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
12033 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
12035 // Multiply the even parts.
12036 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
12037 // Now multiply odd parts.
12038 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
12040 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
12041 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
12043 // Merge the two vectors back together with a shuffle. This expands into 2
12045 static const int ShufMask[] = { 0, 4, 2, 6 };
12046 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
12049 assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
12050 "Only know how to lower V2I64/V4I64 multiply");
12052 // Ahi = psrlqi(a, 32);
12053 // Bhi = psrlqi(b, 32);
12055 // AloBlo = pmuludq(a, b);
12056 // AloBhi = pmuludq(a, Bhi);
12057 // AhiBlo = pmuludq(Ahi, b);
12059 // AloBhi = psllqi(AloBhi, 32);
12060 // AhiBlo = psllqi(AhiBlo, 32);
12061 // return AloBlo + AloBhi + AhiBlo;
12063 SDValue ShAmt = DAG.getConstant(32, MVT::i32);
12065 SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
12066 SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
12068 // Bit cast to 32-bit vectors for MULUDQ
12069 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
12070 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
12071 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
12072 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
12073 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
12075 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
12076 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
12077 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
12079 AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
12080 AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
12082 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
12083 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
12086 SDValue X86TargetLowering::LowerSDIV(SDValue Op, SelectionDAG &DAG) const {
12087 EVT VT = Op.getValueType();
12088 EVT EltTy = VT.getVectorElementType();
12089 unsigned NumElts = VT.getVectorNumElements();
12090 SDValue N0 = Op.getOperand(0);
12093 // Lower sdiv X, pow2-const.
12094 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
12098 APInt SplatValue, SplatUndef;
12099 unsigned SplatBitSize;
12101 if (!C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
12103 EltTy.getSizeInBits() < SplatBitSize)
12106 if ((SplatValue != 0) &&
12107 (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
12108 unsigned lg2 = SplatValue.countTrailingZeros();
12109 // Splat the sign bit.
12110 SDValue Sz = DAG.getConstant(EltTy.getSizeInBits()-1, MVT::i32);
12111 SDValue SGN = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, N0, Sz, DAG);
12112 // Add (N0 < 0) ? abs2 - 1 : 0;
12113 SDValue Amt = DAG.getConstant(EltTy.getSizeInBits() - lg2, MVT::i32);
12114 SDValue SRL = getTargetVShiftNode(X86ISD::VSRLI, dl, VT, SGN, Amt, DAG);
12115 SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
12116 SDValue Lg2Amt = DAG.getConstant(lg2, MVT::i32);
12117 SDValue SRA = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, ADD, Lg2Amt, DAG);
12119 // If we're dividing by a positive value, we're done. Otherwise, we must
12120 // negate the result.
12121 if (SplatValue.isNonNegative())
12124 SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
12125 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
12126 return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
12131 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
12132 const X86Subtarget *Subtarget) {
12133 EVT VT = Op.getValueType();
12135 SDValue R = Op.getOperand(0);
12136 SDValue Amt = Op.getOperand(1);
12138 // Optimize shl/srl/sra with constant shift amount.
12139 if (isSplatVector(Amt.getNode())) {
12140 SDValue SclrAmt = Amt->getOperand(0);
12141 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
12142 uint64_t ShiftAmt = C->getZExtValue();
12144 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
12145 (Subtarget->hasInt256() &&
12146 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
12147 if (Op.getOpcode() == ISD::SHL)
12148 return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
12149 DAG.getConstant(ShiftAmt, MVT::i32));
12150 if (Op.getOpcode() == ISD::SRL)
12151 return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
12152 DAG.getConstant(ShiftAmt, MVT::i32));
12153 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
12154 return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
12155 DAG.getConstant(ShiftAmt, MVT::i32));
12158 if (VT == MVT::v16i8) {
12159 if (Op.getOpcode() == ISD::SHL) {
12160 // Make a large shift.
12161 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
12162 DAG.getConstant(ShiftAmt, MVT::i32));
12163 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
12164 // Zero out the rightmost bits.
12165 SmallVector<SDValue, 16> V(16,
12166 DAG.getConstant(uint8_t(-1U << ShiftAmt),
12168 return DAG.getNode(ISD::AND, dl, VT, SHL,
12169 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
12171 if (Op.getOpcode() == ISD::SRL) {
12172 // Make a large shift.
12173 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
12174 DAG.getConstant(ShiftAmt, MVT::i32));
12175 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
12176 // Zero out the leftmost bits.
12177 SmallVector<SDValue, 16> V(16,
12178 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
12180 return DAG.getNode(ISD::AND, dl, VT, SRL,
12181 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
12183 if (Op.getOpcode() == ISD::SRA) {
12184 if (ShiftAmt == 7) {
12185 // R s>> 7 === R s< 0
12186 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
12187 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
12190 // R s>> a === ((R u>> a) ^ m) - m
12191 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
12192 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
12194 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
12195 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
12196 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
12199 llvm_unreachable("Unknown shift opcode.");
12202 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
12203 if (Op.getOpcode() == ISD::SHL) {
12204 // Make a large shift.
12205 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
12206 DAG.getConstant(ShiftAmt, MVT::i32));
12207 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
12208 // Zero out the rightmost bits.
12209 SmallVector<SDValue, 32> V(32,
12210 DAG.getConstant(uint8_t(-1U << ShiftAmt),
12212 return DAG.getNode(ISD::AND, dl, VT, SHL,
12213 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
12215 if (Op.getOpcode() == ISD::SRL) {
12216 // Make a large shift.
12217 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
12218 DAG.getConstant(ShiftAmt, MVT::i32));
12219 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
12220 // Zero out the leftmost bits.
12221 SmallVector<SDValue, 32> V(32,
12222 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
12224 return DAG.getNode(ISD::AND, dl, VT, SRL,
12225 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
12227 if (Op.getOpcode() == ISD::SRA) {
12228 if (ShiftAmt == 7) {
12229 // R s>> 7 === R s< 0
12230 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
12231 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
12234 // R s>> a === ((R u>> a) ^ m) - m
12235 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
12236 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
12238 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
12239 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
12240 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
12243 llvm_unreachable("Unknown shift opcode.");
12248 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
12249 if (!Subtarget->is64Bit() &&
12250 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
12251 Amt.getOpcode() == ISD::BITCAST &&
12252 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
12253 Amt = Amt.getOperand(0);
12254 unsigned Ratio = Amt.getValueType().getVectorNumElements() /
12255 VT.getVectorNumElements();
12256 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
12257 uint64_t ShiftAmt = 0;
12258 for (unsigned i = 0; i != Ratio; ++i) {
12259 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
12263 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
12265 // Check remaining shift amounts.
12266 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
12267 uint64_t ShAmt = 0;
12268 for (unsigned j = 0; j != Ratio; ++j) {
12269 ConstantSDNode *C =
12270 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
12274 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
12276 if (ShAmt != ShiftAmt)
12279 switch (Op.getOpcode()) {
12281 llvm_unreachable("Unknown shift opcode!");
12283 return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
12284 DAG.getConstant(ShiftAmt, MVT::i32));
12286 return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
12287 DAG.getConstant(ShiftAmt, MVT::i32));
12289 return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
12290 DAG.getConstant(ShiftAmt, MVT::i32));
12297 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
12298 const X86Subtarget* Subtarget) {
12299 EVT VT = Op.getValueType();
12301 SDValue R = Op.getOperand(0);
12302 SDValue Amt = Op.getOperand(1);
12304 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
12305 VT == MVT::v4i32 || VT == MVT::v8i16 ||
12306 (Subtarget->hasInt256() &&
12307 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
12308 VT == MVT::v8i32 || VT == MVT::v16i16))) {
12310 EVT EltVT = VT.getVectorElementType();
12312 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
12313 unsigned NumElts = VT.getVectorNumElements();
12315 for (i = 0; i != NumElts; ++i) {
12316 if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
12320 for (j = i; j != NumElts; ++j) {
12321 SDValue Arg = Amt.getOperand(j);
12322 if (Arg.getOpcode() == ISD::UNDEF) continue;
12323 if (Arg != Amt.getOperand(i))
12326 if (i != NumElts && j == NumElts)
12327 BaseShAmt = Amt.getOperand(i);
12329 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
12330 Amt = Amt.getOperand(0);
12331 if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
12332 cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
12333 SDValue InVec = Amt.getOperand(0);
12334 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
12335 unsigned NumElts = InVec.getValueType().getVectorNumElements();
12337 for (; i != NumElts; ++i) {
12338 SDValue Arg = InVec.getOperand(i);
12339 if (Arg.getOpcode() == ISD::UNDEF) continue;
12343 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
12344 if (ConstantSDNode *C =
12345 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
12346 unsigned SplatIdx =
12347 cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
12348 if (C->getZExtValue() == SplatIdx)
12349 BaseShAmt = InVec.getOperand(1);
12352 if (BaseShAmt.getNode() == 0)
12353 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
12354 DAG.getIntPtrConstant(0));
12358 if (BaseShAmt.getNode()) {
12359 if (EltVT.bitsGT(MVT::i32))
12360 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
12361 else if (EltVT.bitsLT(MVT::i32))
12362 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
12364 switch (Op.getOpcode()) {
12366 llvm_unreachable("Unknown shift opcode!");
12368 switch (VT.getSimpleVT().SimpleTy) {
12369 default: return SDValue();
12376 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
12379 switch (VT.getSimpleVT().SimpleTy) {
12380 default: return SDValue();
12385 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
12388 switch (VT.getSimpleVT().SimpleTy) {
12389 default: return SDValue();
12396 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
12402 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
12403 if (!Subtarget->is64Bit() &&
12404 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
12405 Amt.getOpcode() == ISD::BITCAST &&
12406 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
12407 Amt = Amt.getOperand(0);
12408 unsigned Ratio = Amt.getValueType().getVectorNumElements() /
12409 VT.getVectorNumElements();
12410 std::vector<SDValue> Vals(Ratio);
12411 for (unsigned i = 0; i != Ratio; ++i)
12412 Vals[i] = Amt.getOperand(i);
12413 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
12414 for (unsigned j = 0; j != Ratio; ++j)
12415 if (Vals[j] != Amt.getOperand(i + j))
12418 switch (Op.getOpcode()) {
12420 llvm_unreachable("Unknown shift opcode!");
12422 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
12424 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
12426 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
12433 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
12435 EVT VT = Op.getValueType();
12437 SDValue R = Op.getOperand(0);
12438 SDValue Amt = Op.getOperand(1);
12441 if (!Subtarget->hasSSE2())
12444 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
12448 V = LowerScalarVariableShift(Op, DAG, Subtarget);
12452 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
12453 if (Subtarget->hasInt256()) {
12454 if (Op.getOpcode() == ISD::SRL &&
12455 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
12456 VT == MVT::v4i64 || VT == MVT::v8i32))
12458 if (Op.getOpcode() == ISD::SHL &&
12459 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
12460 VT == MVT::v4i64 || VT == MVT::v8i32))
12462 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
12466 // Lower SHL with variable shift amount.
12467 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
12468 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
12470 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
12471 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
12472 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
12473 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
12475 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
12476 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
12479 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
12480 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
12482 // Turn 'a' into a mask suitable for VSELECT
12483 SDValue VSelM = DAG.getConstant(0x80, VT);
12484 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
12485 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
12487 SDValue CM1 = DAG.getConstant(0x0f, VT);
12488 SDValue CM2 = DAG.getConstant(0x3f, VT);
12490 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
12491 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
12492 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
12493 DAG.getConstant(4, MVT::i32), DAG);
12494 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
12495 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
12498 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
12499 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
12500 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
12502 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
12503 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
12504 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
12505 DAG.getConstant(2, MVT::i32), DAG);
12506 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
12507 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
12510 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
12511 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
12512 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
12514 // return VSELECT(r, r+r, a);
12515 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
12516 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
12520 // Decompose 256-bit shifts into smaller 128-bit shifts.
12521 if (VT.is256BitVector()) {
12522 unsigned NumElems = VT.getVectorNumElements();
12523 MVT EltVT = VT.getVectorElementType().getSimpleVT();
12524 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12526 // Extract the two vectors
12527 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
12528 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
12530 // Recreate the shift amount vectors
12531 SDValue Amt1, Amt2;
12532 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
12533 // Constant shift amount
12534 SmallVector<SDValue, 4> Amt1Csts;
12535 SmallVector<SDValue, 4> Amt2Csts;
12536 for (unsigned i = 0; i != NumElems/2; ++i)
12537 Amt1Csts.push_back(Amt->getOperand(i));
12538 for (unsigned i = NumElems/2; i != NumElems; ++i)
12539 Amt2Csts.push_back(Amt->getOperand(i));
12541 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
12542 &Amt1Csts[0], NumElems/2);
12543 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
12544 &Amt2Csts[0], NumElems/2);
12546 // Variable shift amount
12547 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
12548 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
12551 // Issue new vector shifts for the smaller types
12552 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
12553 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
12555 // Concatenate the result back
12556 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
12562 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
12563 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
12564 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
12565 // looks for this combo and may remove the "setcc" instruction if the "setcc"
12566 // has only one use.
12567 SDNode *N = Op.getNode();
12568 SDValue LHS = N->getOperand(0);
12569 SDValue RHS = N->getOperand(1);
12570 unsigned BaseOp = 0;
12573 switch (Op.getOpcode()) {
12574 default: llvm_unreachable("Unknown ovf instruction!");
12576 // A subtract of one will be selected as a INC. Note that INC doesn't
12577 // set CF, so we can't do this for UADDO.
12578 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12580 BaseOp = X86ISD::INC;
12581 Cond = X86::COND_O;
12584 BaseOp = X86ISD::ADD;
12585 Cond = X86::COND_O;
12588 BaseOp = X86ISD::ADD;
12589 Cond = X86::COND_B;
12592 // A subtract of one will be selected as a DEC. Note that DEC doesn't
12593 // set CF, so we can't do this for USUBO.
12594 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12596 BaseOp = X86ISD::DEC;
12597 Cond = X86::COND_O;
12600 BaseOp = X86ISD::SUB;
12601 Cond = X86::COND_O;
12604 BaseOp = X86ISD::SUB;
12605 Cond = X86::COND_B;
12608 BaseOp = X86ISD::SMUL;
12609 Cond = X86::COND_O;
12611 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
12612 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
12614 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
12617 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12618 DAG.getConstant(X86::COND_O, MVT::i32),
12619 SDValue(Sum.getNode(), 2));
12621 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
12625 // Also sets EFLAGS.
12626 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
12627 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
12630 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
12631 DAG.getConstant(Cond, MVT::i32),
12632 SDValue(Sum.getNode(), 1));
12634 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
12637 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
12638 SelectionDAG &DAG) const {
12640 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
12641 EVT VT = Op.getValueType();
12643 if (!Subtarget->hasSSE2() || !VT.isVector())
12646 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
12647 ExtraVT.getScalarType().getSizeInBits();
12648 SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
12650 switch (VT.getSimpleVT().SimpleTy) {
12651 default: return SDValue();
12654 if (!Subtarget->hasFp256())
12656 if (!Subtarget->hasInt256()) {
12657 // needs to be split
12658 unsigned NumElems = VT.getVectorNumElements();
12660 // Extract the LHS vectors
12661 SDValue LHS = Op.getOperand(0);
12662 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12663 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12665 MVT EltVT = VT.getVectorElementType().getSimpleVT();
12666 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12668 EVT ExtraEltVT = ExtraVT.getVectorElementType();
12669 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
12670 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
12672 SDValue Extra = DAG.getValueType(ExtraVT);
12674 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
12675 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
12677 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
12682 // (sext (vzext x)) -> (vsext x)
12683 SDValue Op0 = Op.getOperand(0);
12684 SDValue Op00 = Op0.getOperand(0);
12686 // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
12687 if (Op0.getOpcode() == ISD::BITCAST &&
12688 Op00.getOpcode() == ISD::VECTOR_SHUFFLE)
12689 Tmp1 = LowerVectorIntExtend(Op00, DAG);
12690 if (Tmp1.getNode()) {
12691 SDValue Tmp1Op0 = Tmp1.getOperand(0);
12692 assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
12693 "This optimization is invalid without a VZEXT.");
12694 return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
12697 // If the above didn't work, then just use Shift-Left + Shift-Right.
12698 Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT, Op0, ShAmt, DAG);
12699 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
12704 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
12705 SelectionDAG &DAG) {
12707 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
12708 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
12709 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
12710 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
12712 // The only fence that needs an instruction is a sequentially-consistent
12713 // cross-thread fence.
12714 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
12715 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
12716 // no-sse2). There isn't any reason to disable it if the target processor
12718 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
12719 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
12721 SDValue Chain = Op.getOperand(0);
12722 SDValue Zero = DAG.getConstant(0, MVT::i32);
12724 DAG.getRegister(X86::ESP, MVT::i32), // Base
12725 DAG.getTargetConstant(1, MVT::i8), // Scale
12726 DAG.getRegister(0, MVT::i32), // Index
12727 DAG.getTargetConstant(0, MVT::i32), // Disp
12728 DAG.getRegister(0, MVT::i32), // Segment.
12732 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
12733 return SDValue(Res, 0);
12736 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
12737 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
12740 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
12741 SelectionDAG &DAG) {
12742 EVT T = Op.getValueType();
12746 switch(T.getSimpleVT().SimpleTy) {
12747 default: llvm_unreachable("Invalid value type!");
12748 case MVT::i8: Reg = X86::AL; size = 1; break;
12749 case MVT::i16: Reg = X86::AX; size = 2; break;
12750 case MVT::i32: Reg = X86::EAX; size = 4; break;
12752 assert(Subtarget->is64Bit() && "Node not type legal!");
12753 Reg = X86::RAX; size = 8;
12756 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
12757 Op.getOperand(2), SDValue());
12758 SDValue Ops[] = { cpIn.getValue(0),
12761 DAG.getTargetConstant(size, MVT::i8),
12762 cpIn.getValue(1) };
12763 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12764 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
12765 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
12766 Ops, array_lengthof(Ops), T, MMO);
12768 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
12772 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12773 SelectionDAG &DAG) {
12774 assert(Subtarget->is64Bit() && "Result not type legalized?");
12775 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12776 SDValue TheChain = Op.getOperand(0);
12778 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
12779 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
12780 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
12782 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
12783 DAG.getConstant(32, MVT::i8));
12785 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
12788 return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
12791 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
12792 EVT SrcVT = Op.getOperand(0).getValueType();
12793 EVT DstVT = Op.getValueType();
12794 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
12795 Subtarget->hasMMX() && "Unexpected custom BITCAST");
12796 assert((DstVT == MVT::i64 ||
12797 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
12798 "Unexpected custom BITCAST");
12799 // i64 <=> MMX conversions are Legal.
12800 if (SrcVT==MVT::i64 && DstVT.isVector())
12802 if (DstVT==MVT::i64 && SrcVT.isVector())
12804 // MMX <=> MMX conversions are Legal.
12805 if (SrcVT.isVector() && DstVT.isVector())
12807 // All other conversions need to be expanded.
12811 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
12812 SDNode *Node = Op.getNode();
12814 EVT T = Node->getValueType(0);
12815 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
12816 DAG.getConstant(0, T), Node->getOperand(2));
12817 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
12818 cast<AtomicSDNode>(Node)->getMemoryVT(),
12819 Node->getOperand(0),
12820 Node->getOperand(1), negOp,
12821 cast<AtomicSDNode>(Node)->getSrcValue(),
12822 cast<AtomicSDNode>(Node)->getAlignment(),
12823 cast<AtomicSDNode>(Node)->getOrdering(),
12824 cast<AtomicSDNode>(Node)->getSynchScope());
12827 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
12828 SDNode *Node = Op.getNode();
12830 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12832 // Convert seq_cst store -> xchg
12833 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
12834 // FIXME: On 32-bit, store -> fist or movq would be more efficient
12835 // (The only way to get a 16-byte store is cmpxchg16b)
12836 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
12837 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
12838 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
12839 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
12840 cast<AtomicSDNode>(Node)->getMemoryVT(),
12841 Node->getOperand(0),
12842 Node->getOperand(1), Node->getOperand(2),
12843 cast<AtomicSDNode>(Node)->getMemOperand(),
12844 cast<AtomicSDNode>(Node)->getOrdering(),
12845 cast<AtomicSDNode>(Node)->getSynchScope());
12846 return Swap.getValue(1);
12848 // Other atomic stores have a simple pattern.
12852 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
12853 EVT VT = Op.getNode()->getValueType(0);
12855 // Let legalize expand this if it isn't a legal type yet.
12856 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
12859 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12862 bool ExtraOp = false;
12863 switch (Op.getOpcode()) {
12864 default: llvm_unreachable("Invalid code");
12865 case ISD::ADDC: Opc = X86ISD::ADD; break;
12866 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
12867 case ISD::SUBC: Opc = X86ISD::SUB; break;
12868 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
12872 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
12874 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
12875 Op.getOperand(1), Op.getOperand(2));
12878 SDValue X86TargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
12879 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
12881 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
12882 // which returns the values as { float, float } (in XMM0) or
12883 // { double, double } (which is returned in XMM0, XMM1).
12885 SDValue Arg = Op.getOperand(0);
12886 EVT ArgVT = Arg.getValueType();
12887 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
12890 ArgListEntry Entry;
12894 Entry.isSExt = false;
12895 Entry.isZExt = false;
12896 Args.push_back(Entry);
12898 bool isF64 = ArgVT == MVT::f64;
12899 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
12900 // the small struct {f32, f32} is returned in (eax, edx). For f64,
12901 // the results are returned via SRet in memory.
12902 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
12903 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
12905 Type *RetTy = isF64
12906 ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
12907 : (Type*)VectorType::get(ArgTy, 4);
12909 CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
12910 false, false, false, false, 0,
12911 CallingConv::C, /*isTaillCall=*/false,
12912 /*doesNotRet=*/false, /*isReturnValueUsed*/true,
12913 Callee, Args, DAG, dl);
12914 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
12917 // Returned in xmm0 and xmm1.
12918 return CallResult.first;
12920 // Returned in bits 0:31 and 32:64 xmm0.
12921 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
12922 CallResult.first, DAG.getIntPtrConstant(0));
12923 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
12924 CallResult.first, DAG.getIntPtrConstant(1));
12925 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
12926 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
12929 /// LowerOperation - Provide custom lowering hooks for some operations.
12931 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
12932 switch (Op.getOpcode()) {
12933 default: llvm_unreachable("Should not custom lower this!");
12934 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
12935 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
12936 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op, Subtarget, DAG);
12937 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
12938 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
12939 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
12940 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
12941 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
12942 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
12943 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
12944 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
12945 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
12946 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
12947 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
12948 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
12949 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
12950 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
12951 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
12952 case ISD::SHL_PARTS:
12953 case ISD::SRA_PARTS:
12954 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
12955 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
12956 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
12957 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
12958 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, DAG);
12959 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, DAG);
12960 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, DAG);
12961 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
12962 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
12963 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
12964 case ISD::FABS: return LowerFABS(Op, DAG);
12965 case ISD::FNEG: return LowerFNEG(Op, DAG);
12966 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
12967 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
12968 case ISD::SETCC: return LowerSETCC(Op, DAG);
12969 case ISD::SELECT: return LowerSELECT(Op, DAG);
12970 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
12971 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
12972 case ISD::VASTART: return LowerVASTART(Op, DAG);
12973 case ISD::VAARG: return LowerVAARG(Op, DAG);
12974 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
12975 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
12976 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
12977 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
12978 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
12979 case ISD::FRAME_TO_ARGS_OFFSET:
12980 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
12981 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
12982 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
12983 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
12984 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
12985 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
12986 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
12987 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
12988 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
12989 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
12990 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
12991 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
12994 case ISD::SHL: return LowerShift(Op, DAG);
13000 case ISD::UMULO: return LowerXALUO(Op, DAG);
13001 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
13002 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
13006 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
13007 case ISD::ADD: return LowerADD(Op, DAG);
13008 case ISD::SUB: return LowerSUB(Op, DAG);
13009 case ISD::SDIV: return LowerSDIV(Op, DAG);
13010 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
13014 static void ReplaceATOMIC_LOAD(SDNode *Node,
13015 SmallVectorImpl<SDValue> &Results,
13016 SelectionDAG &DAG) {
13018 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
13020 // Convert wide load -> cmpxchg8b/cmpxchg16b
13021 // FIXME: On 32-bit, load -> fild or movq would be more efficient
13022 // (The only way to get a 16-byte load is cmpxchg16b)
13023 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
13024 SDValue Zero = DAG.getConstant(0, VT);
13025 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
13026 Node->getOperand(0),
13027 Node->getOperand(1), Zero, Zero,
13028 cast<AtomicSDNode>(Node)->getMemOperand(),
13029 cast<AtomicSDNode>(Node)->getOrdering(),
13030 cast<AtomicSDNode>(Node)->getSynchScope());
13031 Results.push_back(Swap.getValue(0));
13032 Results.push_back(Swap.getValue(1));
13036 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
13037 SelectionDAG &DAG, unsigned NewOp) {
13039 assert (Node->getValueType(0) == MVT::i64 &&
13040 "Only know how to expand i64 atomics");
13042 SDValue Chain = Node->getOperand(0);
13043 SDValue In1 = Node->getOperand(1);
13044 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
13045 Node->getOperand(2), DAG.getIntPtrConstant(0));
13046 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
13047 Node->getOperand(2), DAG.getIntPtrConstant(1));
13048 SDValue Ops[] = { Chain, In1, In2L, In2H };
13049 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
13051 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, array_lengthof(Ops), MVT::i64,
13052 cast<MemSDNode>(Node)->getMemOperand());
13053 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
13054 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
13055 Results.push_back(Result.getValue(2));
13058 /// ReplaceNodeResults - Replace a node with an illegal result type
13059 /// with a new node built out of custom code.
13060 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
13061 SmallVectorImpl<SDValue>&Results,
13062 SelectionDAG &DAG) const {
13064 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13065 switch (N->getOpcode()) {
13067 llvm_unreachable("Do not know how to custom type legalize this operation!");
13068 case ISD::SIGN_EXTEND_INREG:
13073 // We don't want to expand or promote these.
13075 case ISD::FP_TO_SINT:
13076 case ISD::FP_TO_UINT: {
13077 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
13079 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
13082 std::pair<SDValue,SDValue> Vals =
13083 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
13084 SDValue FIST = Vals.first, StackSlot = Vals.second;
13085 if (FIST.getNode() != 0) {
13086 EVT VT = N->getValueType(0);
13087 // Return a load from the stack slot.
13088 if (StackSlot.getNode() != 0)
13089 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
13090 MachinePointerInfo(),
13091 false, false, false, 0));
13093 Results.push_back(FIST);
13097 case ISD::UINT_TO_FP: {
13098 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
13099 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
13100 N->getValueType(0) != MVT::v2f32)
13102 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
13104 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
13106 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
13107 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
13108 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
13109 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
13110 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
13111 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
13114 case ISD::FP_ROUND: {
13115 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
13117 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
13118 Results.push_back(V);
13121 case ISD::READCYCLECOUNTER: {
13122 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13123 SDValue TheChain = N->getOperand(0);
13124 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
13125 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
13127 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
13129 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
13130 SDValue Ops[] = { eax, edx };
13131 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops,
13132 array_lengthof(Ops)));
13133 Results.push_back(edx.getValue(1));
13136 case ISD::ATOMIC_CMP_SWAP: {
13137 EVT T = N->getValueType(0);
13138 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
13139 bool Regs64bit = T == MVT::i128;
13140 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
13141 SDValue cpInL, cpInH;
13142 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
13143 DAG.getConstant(0, HalfT));
13144 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
13145 DAG.getConstant(1, HalfT));
13146 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
13147 Regs64bit ? X86::RAX : X86::EAX,
13149 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
13150 Regs64bit ? X86::RDX : X86::EDX,
13151 cpInH, cpInL.getValue(1));
13152 SDValue swapInL, swapInH;
13153 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
13154 DAG.getConstant(0, HalfT));
13155 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
13156 DAG.getConstant(1, HalfT));
13157 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
13158 Regs64bit ? X86::RBX : X86::EBX,
13159 swapInL, cpInH.getValue(1));
13160 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
13161 Regs64bit ? X86::RCX : X86::ECX,
13162 swapInH, swapInL.getValue(1));
13163 SDValue Ops[] = { swapInH.getValue(0),
13165 swapInH.getValue(1) };
13166 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13167 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
13168 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
13169 X86ISD::LCMPXCHG8_DAG;
13170 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
13171 Ops, array_lengthof(Ops), T, MMO);
13172 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
13173 Regs64bit ? X86::RAX : X86::EAX,
13174 HalfT, Result.getValue(1));
13175 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
13176 Regs64bit ? X86::RDX : X86::EDX,
13177 HalfT, cpOutL.getValue(2));
13178 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
13179 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
13180 Results.push_back(cpOutH.getValue(1));
13183 case ISD::ATOMIC_LOAD_ADD:
13184 case ISD::ATOMIC_LOAD_AND:
13185 case ISD::ATOMIC_LOAD_NAND:
13186 case ISD::ATOMIC_LOAD_OR:
13187 case ISD::ATOMIC_LOAD_SUB:
13188 case ISD::ATOMIC_LOAD_XOR:
13189 case ISD::ATOMIC_LOAD_MAX:
13190 case ISD::ATOMIC_LOAD_MIN:
13191 case ISD::ATOMIC_LOAD_UMAX:
13192 case ISD::ATOMIC_LOAD_UMIN:
13193 case ISD::ATOMIC_SWAP: {
13195 switch (N->getOpcode()) {
13196 default: llvm_unreachable("Unexpected opcode");
13197 case ISD::ATOMIC_LOAD_ADD:
13198 Opc = X86ISD::ATOMADD64_DAG;
13200 case ISD::ATOMIC_LOAD_AND:
13201 Opc = X86ISD::ATOMAND64_DAG;
13203 case ISD::ATOMIC_LOAD_NAND:
13204 Opc = X86ISD::ATOMNAND64_DAG;
13206 case ISD::ATOMIC_LOAD_OR:
13207 Opc = X86ISD::ATOMOR64_DAG;
13209 case ISD::ATOMIC_LOAD_SUB:
13210 Opc = X86ISD::ATOMSUB64_DAG;
13212 case ISD::ATOMIC_LOAD_XOR:
13213 Opc = X86ISD::ATOMXOR64_DAG;
13215 case ISD::ATOMIC_LOAD_MAX:
13216 Opc = X86ISD::ATOMMAX64_DAG;
13218 case ISD::ATOMIC_LOAD_MIN:
13219 Opc = X86ISD::ATOMMIN64_DAG;
13221 case ISD::ATOMIC_LOAD_UMAX:
13222 Opc = X86ISD::ATOMUMAX64_DAG;
13224 case ISD::ATOMIC_LOAD_UMIN:
13225 Opc = X86ISD::ATOMUMIN64_DAG;
13227 case ISD::ATOMIC_SWAP:
13228 Opc = X86ISD::ATOMSWAP64_DAG;
13231 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
13234 case ISD::ATOMIC_LOAD:
13235 ReplaceATOMIC_LOAD(N, Results, DAG);
13239 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
13241 default: return NULL;
13242 case X86ISD::BSF: return "X86ISD::BSF";
13243 case X86ISD::BSR: return "X86ISD::BSR";
13244 case X86ISD::SHLD: return "X86ISD::SHLD";
13245 case X86ISD::SHRD: return "X86ISD::SHRD";
13246 case X86ISD::FAND: return "X86ISD::FAND";
13247 case X86ISD::FANDN: return "X86ISD::FANDN";
13248 case X86ISD::FOR: return "X86ISD::FOR";
13249 case X86ISD::FXOR: return "X86ISD::FXOR";
13250 case X86ISD::FSRL: return "X86ISD::FSRL";
13251 case X86ISD::FILD: return "X86ISD::FILD";
13252 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
13253 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
13254 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
13255 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
13256 case X86ISD::FLD: return "X86ISD::FLD";
13257 case X86ISD::FST: return "X86ISD::FST";
13258 case X86ISD::CALL: return "X86ISD::CALL";
13259 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
13260 case X86ISD::BT: return "X86ISD::BT";
13261 case X86ISD::CMP: return "X86ISD::CMP";
13262 case X86ISD::COMI: return "X86ISD::COMI";
13263 case X86ISD::UCOMI: return "X86ISD::UCOMI";
13264 case X86ISD::CMPM: return "X86ISD::CMPM";
13265 case X86ISD::CMPMU: return "X86ISD::CMPMU";
13266 case X86ISD::SETCC: return "X86ISD::SETCC";
13267 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
13268 case X86ISD::FSETCCsd: return "X86ISD::FSETCCsd";
13269 case X86ISD::FSETCCss: return "X86ISD::FSETCCss";
13270 case X86ISD::CMOV: return "X86ISD::CMOV";
13271 case X86ISD::BRCOND: return "X86ISD::BRCOND";
13272 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
13273 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
13274 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
13275 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
13276 case X86ISD::Wrapper: return "X86ISD::Wrapper";
13277 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
13278 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
13279 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
13280 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
13281 case X86ISD::PINSRB: return "X86ISD::PINSRB";
13282 case X86ISD::PINSRW: return "X86ISD::PINSRW";
13283 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
13284 case X86ISD::ANDNP: return "X86ISD::ANDNP";
13285 case X86ISD::PSIGN: return "X86ISD::PSIGN";
13286 case X86ISD::BLENDV: return "X86ISD::BLENDV";
13287 case X86ISD::BLENDI: return "X86ISD::BLENDI";
13288 case X86ISD::SUBUS: return "X86ISD::SUBUS";
13289 case X86ISD::HADD: return "X86ISD::HADD";
13290 case X86ISD::HSUB: return "X86ISD::HSUB";
13291 case X86ISD::FHADD: return "X86ISD::FHADD";
13292 case X86ISD::FHSUB: return "X86ISD::FHSUB";
13293 case X86ISD::UMAX: return "X86ISD::UMAX";
13294 case X86ISD::UMIN: return "X86ISD::UMIN";
13295 case X86ISD::SMAX: return "X86ISD::SMAX";
13296 case X86ISD::SMIN: return "X86ISD::SMIN";
13297 case X86ISD::FMAX: return "X86ISD::FMAX";
13298 case X86ISD::FMIN: return "X86ISD::FMIN";
13299 case X86ISD::FMAXC: return "X86ISD::FMAXC";
13300 case X86ISD::FMINC: return "X86ISD::FMINC";
13301 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
13302 case X86ISD::FRCP: return "X86ISD::FRCP";
13303 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
13304 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
13305 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
13306 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
13307 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
13308 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
13309 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
13310 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
13311 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
13312 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
13313 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
13314 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
13315 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
13316 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
13317 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
13318 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
13319 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
13320 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
13321 case X86ISD::VSEXT_MOVL: return "X86ISD::VSEXT_MOVL";
13322 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
13323 case X86ISD::VZEXT: return "X86ISD::VZEXT";
13324 case X86ISD::VSEXT: return "X86ISD::VSEXT";
13325 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
13326 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
13327 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
13328 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
13329 case X86ISD::VSHL: return "X86ISD::VSHL";
13330 case X86ISD::VSRL: return "X86ISD::VSRL";
13331 case X86ISD::VSRA: return "X86ISD::VSRA";
13332 case X86ISD::VSHLI: return "X86ISD::VSHLI";
13333 case X86ISD::VSRLI: return "X86ISD::VSRLI";
13334 case X86ISD::VSRAI: return "X86ISD::VSRAI";
13335 case X86ISD::CMPP: return "X86ISD::CMPP";
13336 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
13337 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
13338 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
13339 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
13340 case X86ISD::ADD: return "X86ISD::ADD";
13341 case X86ISD::SUB: return "X86ISD::SUB";
13342 case X86ISD::ADC: return "X86ISD::ADC";
13343 case X86ISD::SBB: return "X86ISD::SBB";
13344 case X86ISD::SMUL: return "X86ISD::SMUL";
13345 case X86ISD::UMUL: return "X86ISD::UMUL";
13346 case X86ISD::INC: return "X86ISD::INC";
13347 case X86ISD::DEC: return "X86ISD::DEC";
13348 case X86ISD::OR: return "X86ISD::OR";
13349 case X86ISD::XOR: return "X86ISD::XOR";
13350 case X86ISD::AND: return "X86ISD::AND";
13351 case X86ISD::BLSI: return "X86ISD::BLSI";
13352 case X86ISD::BLSMSK: return "X86ISD::BLSMSK";
13353 case X86ISD::BLSR: return "X86ISD::BLSR";
13354 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
13355 case X86ISD::PTEST: return "X86ISD::PTEST";
13356 case X86ISD::TESTP: return "X86ISD::TESTP";
13357 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
13358 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
13359 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
13360 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
13361 case X86ISD::SHUFP: return "X86ISD::SHUFP";
13362 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
13363 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
13364 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
13365 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
13366 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
13367 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
13368 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
13369 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
13370 case X86ISD::MOVSD: return "X86ISD::MOVSD";
13371 case X86ISD::MOVSS: return "X86ISD::MOVSS";
13372 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
13373 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
13374 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
13375 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
13376 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
13377 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
13378 case X86ISD::VPERMV: return "X86ISD::VPERMV";
13379 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
13380 case X86ISD::VPERMI: return "X86ISD::VPERMI";
13381 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
13382 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
13383 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
13384 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
13385 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
13386 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
13387 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
13388 case X86ISD::SAHF: return "X86ISD::SAHF";
13389 case X86ISD::RDRAND: return "X86ISD::RDRAND";
13390 case X86ISD::RDSEED: return "X86ISD::RDSEED";
13391 case X86ISD::FMADD: return "X86ISD::FMADD";
13392 case X86ISD::FMSUB: return "X86ISD::FMSUB";
13393 case X86ISD::FNMADD: return "X86ISD::FNMADD";
13394 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
13395 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
13396 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
13397 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
13398 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
13399 case X86ISD::XTEST: return "X86ISD::XTEST";
13403 // isLegalAddressingMode - Return true if the addressing mode represented
13404 // by AM is legal for this target, for a load/store of the specified type.
13405 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
13407 // X86 supports extremely general addressing modes.
13408 CodeModel::Model M = getTargetMachine().getCodeModel();
13409 Reloc::Model R = getTargetMachine().getRelocationModel();
13411 // X86 allows a sign-extended 32-bit immediate field as a displacement.
13412 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
13417 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
13419 // If a reference to this global requires an extra load, we can't fold it.
13420 if (isGlobalStubReference(GVFlags))
13423 // If BaseGV requires a register for the PIC base, we cannot also have a
13424 // BaseReg specified.
13425 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
13428 // If lower 4G is not available, then we must use rip-relative addressing.
13429 if ((M != CodeModel::Small || R != Reloc::Static) &&
13430 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
13434 switch (AM.Scale) {
13440 // These scales always work.
13445 // These scales are formed with basereg+scalereg. Only accept if there is
13450 default: // Other stuff never works.
13457 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
13458 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
13460 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
13461 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
13462 return NumBits1 > NumBits2;
13465 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
13466 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
13469 if (!isTypeLegal(EVT::getEVT(Ty1)))
13472 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
13474 // Assuming the caller doesn't have a zeroext or signext return parameter,
13475 // truncation all the way down to i1 is valid.
13479 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
13480 return isInt<32>(Imm);
13483 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
13484 // Can also use sub to handle negated immediates.
13485 return isInt<32>(Imm);
13488 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
13489 if (!VT1.isInteger() || !VT2.isInteger())
13491 unsigned NumBits1 = VT1.getSizeInBits();
13492 unsigned NumBits2 = VT2.getSizeInBits();
13493 return NumBits1 > NumBits2;
13496 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
13497 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
13498 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
13501 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
13502 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
13503 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
13506 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
13507 EVT VT1 = Val.getValueType();
13508 if (isZExtFree(VT1, VT2))
13511 if (Val.getOpcode() != ISD::LOAD)
13514 if (!VT1.isSimple() || !VT1.isInteger() ||
13515 !VT2.isSimple() || !VT2.isInteger())
13518 switch (VT1.getSimpleVT().SimpleTy) {
13523 // X86 has 8, 16, and 32-bit zero-extending loads.
13531 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
13532 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
13535 VT = VT.getScalarType();
13537 if (!VT.isSimple())
13540 switch (VT.getSimpleVT().SimpleTy) {
13551 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
13552 // i16 instructions are longer (0x66 prefix) and potentially slower.
13553 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
13556 /// isShuffleMaskLegal - Targets can use this to indicate that they only
13557 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
13558 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
13559 /// are assumed to be legal.
13561 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
13563 if (!VT.isSimple())
13566 MVT SVT = VT.getSimpleVT();
13568 // Very little shuffling can be done for 64-bit vectors right now.
13569 if (VT.getSizeInBits() == 64)
13572 // FIXME: pshufb, blends, shifts.
13573 return (SVT.getVectorNumElements() == 2 ||
13574 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
13575 isMOVLMask(M, SVT) ||
13576 isSHUFPMask(M, SVT, Subtarget->hasFp256()) ||
13577 isPSHUFDMask(M, SVT) ||
13578 isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
13579 isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
13580 isPALIGNRMask(M, SVT, Subtarget) ||
13581 isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
13582 isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
13583 isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
13584 isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()));
13588 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
13590 if (!VT.isSimple())
13593 MVT SVT = VT.getSimpleVT();
13594 unsigned NumElts = SVT.getVectorNumElements();
13595 // FIXME: This collection of masks seems suspect.
13598 if (NumElts == 4 && SVT.is128BitVector()) {
13599 return (isMOVLMask(Mask, SVT) ||
13600 isCommutedMOVLMask(Mask, SVT, true) ||
13601 isSHUFPMask(Mask, SVT, Subtarget->hasFp256()) ||
13602 isSHUFPMask(Mask, SVT, Subtarget->hasFp256(), /* Commuted */ true));
13607 //===----------------------------------------------------------------------===//
13608 // X86 Scheduler Hooks
13609 //===----------------------------------------------------------------------===//
13611 /// Utility function to emit xbegin specifying the start of an RTM region.
13612 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
13613 const TargetInstrInfo *TII) {
13614 DebugLoc DL = MI->getDebugLoc();
13616 const BasicBlock *BB = MBB->getBasicBlock();
13617 MachineFunction::iterator I = MBB;
13620 // For the v = xbegin(), we generate
13631 MachineBasicBlock *thisMBB = MBB;
13632 MachineFunction *MF = MBB->getParent();
13633 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13634 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13635 MF->insert(I, mainMBB);
13636 MF->insert(I, sinkMBB);
13638 // Transfer the remainder of BB and its successor edges to sinkMBB.
13639 sinkMBB->splice(sinkMBB->begin(), MBB,
13640 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13641 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13645 // # fallthrough to mainMBB
13646 // # abortion to sinkMBB
13647 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
13648 thisMBB->addSuccessor(mainMBB);
13649 thisMBB->addSuccessor(sinkMBB);
13653 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
13654 mainMBB->addSuccessor(sinkMBB);
13657 // EAX is live into the sinkMBB
13658 sinkMBB->addLiveIn(X86::EAX);
13659 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13660 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13663 MI->eraseFromParent();
13667 // Get CMPXCHG opcode for the specified data type.
13668 static unsigned getCmpXChgOpcode(EVT VT) {
13669 switch (VT.getSimpleVT().SimpleTy) {
13670 case MVT::i8: return X86::LCMPXCHG8;
13671 case MVT::i16: return X86::LCMPXCHG16;
13672 case MVT::i32: return X86::LCMPXCHG32;
13673 case MVT::i64: return X86::LCMPXCHG64;
13677 llvm_unreachable("Invalid operand size!");
13680 // Get LOAD opcode for the specified data type.
13681 static unsigned getLoadOpcode(EVT VT) {
13682 switch (VT.getSimpleVT().SimpleTy) {
13683 case MVT::i8: return X86::MOV8rm;
13684 case MVT::i16: return X86::MOV16rm;
13685 case MVT::i32: return X86::MOV32rm;
13686 case MVT::i64: return X86::MOV64rm;
13690 llvm_unreachable("Invalid operand size!");
13693 // Get opcode of the non-atomic one from the specified atomic instruction.
13694 static unsigned getNonAtomicOpcode(unsigned Opc) {
13696 case X86::ATOMAND8: return X86::AND8rr;
13697 case X86::ATOMAND16: return X86::AND16rr;
13698 case X86::ATOMAND32: return X86::AND32rr;
13699 case X86::ATOMAND64: return X86::AND64rr;
13700 case X86::ATOMOR8: return X86::OR8rr;
13701 case X86::ATOMOR16: return X86::OR16rr;
13702 case X86::ATOMOR32: return X86::OR32rr;
13703 case X86::ATOMOR64: return X86::OR64rr;
13704 case X86::ATOMXOR8: return X86::XOR8rr;
13705 case X86::ATOMXOR16: return X86::XOR16rr;
13706 case X86::ATOMXOR32: return X86::XOR32rr;
13707 case X86::ATOMXOR64: return X86::XOR64rr;
13709 llvm_unreachable("Unhandled atomic-load-op opcode!");
13712 // Get opcode of the non-atomic one from the specified atomic instruction with
13714 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
13715 unsigned &ExtraOpc) {
13717 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr;
13718 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr;
13719 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr;
13720 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr;
13721 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr;
13722 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
13723 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
13724 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
13725 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr;
13726 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
13727 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
13728 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
13729 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr;
13730 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
13731 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
13732 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
13733 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr;
13734 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
13735 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
13736 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
13738 llvm_unreachable("Unhandled atomic-load-op opcode!");
13741 // Get opcode of the non-atomic one from the specified atomic instruction for
13742 // 64-bit data type on 32-bit target.
13743 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
13745 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr;
13746 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr;
13747 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr;
13748 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr;
13749 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr;
13750 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
13751 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr;
13752 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr;
13753 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr;
13754 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr;
13756 llvm_unreachable("Unhandled atomic-load-op opcode!");
13759 // Get opcode of the non-atomic one from the specified atomic instruction for
13760 // 64-bit data type on 32-bit target with extra opcode.
13761 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
13763 unsigned &ExtraOpc) {
13765 case X86::ATOMNAND6432:
13766 ExtraOpc = X86::NOT32r;
13767 HiOpc = X86::AND32rr;
13768 return X86::AND32rr;
13770 llvm_unreachable("Unhandled atomic-load-op opcode!");
13773 // Get pseudo CMOV opcode from the specified data type.
13774 static unsigned getPseudoCMOVOpc(EVT VT) {
13775 switch (VT.getSimpleVT().SimpleTy) {
13776 case MVT::i8: return X86::CMOV_GR8;
13777 case MVT::i16: return X86::CMOV_GR16;
13778 case MVT::i32: return X86::CMOV_GR32;
13782 llvm_unreachable("Unknown CMOV opcode!");
13785 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
13786 // They will be translated into a spin-loop or compare-exchange loop from
13789 // dst = atomic-fetch-op MI.addr, MI.val
13795 // t1 = LOAD MI.addr
13797 // t4 = phi(t1, t3 / loop)
13798 // t2 = OP MI.val, t4
13800 // LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
13806 MachineBasicBlock *
13807 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
13808 MachineBasicBlock *MBB) const {
13809 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13810 DebugLoc DL = MI->getDebugLoc();
13812 MachineFunction *MF = MBB->getParent();
13813 MachineRegisterInfo &MRI = MF->getRegInfo();
13815 const BasicBlock *BB = MBB->getBasicBlock();
13816 MachineFunction::iterator I = MBB;
13819 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
13820 "Unexpected number of operands");
13822 assert(MI->hasOneMemOperand() &&
13823 "Expected atomic-load-op to have one memoperand");
13825 // Memory Reference
13826 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13827 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13829 unsigned DstReg, SrcReg;
13830 unsigned MemOpndSlot;
13832 unsigned CurOp = 0;
13834 DstReg = MI->getOperand(CurOp++).getReg();
13835 MemOpndSlot = CurOp;
13836 CurOp += X86::AddrNumOperands;
13837 SrcReg = MI->getOperand(CurOp++).getReg();
13839 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
13840 MVT::SimpleValueType VT = *RC->vt_begin();
13841 unsigned t1 = MRI.createVirtualRegister(RC);
13842 unsigned t2 = MRI.createVirtualRegister(RC);
13843 unsigned t3 = MRI.createVirtualRegister(RC);
13844 unsigned t4 = MRI.createVirtualRegister(RC);
13845 unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
13847 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
13848 unsigned LOADOpc = getLoadOpcode(VT);
13850 // For the atomic load-arith operator, we generate
13853 // t1 = LOAD [MI.addr]
13855 // t4 = phi(t1 / thisMBB, t3 / mainMBB)
13856 // t1 = OP MI.val, EAX
13858 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
13864 MachineBasicBlock *thisMBB = MBB;
13865 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13866 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13867 MF->insert(I, mainMBB);
13868 MF->insert(I, sinkMBB);
13870 MachineInstrBuilder MIB;
13872 // Transfer the remainder of BB and its successor edges to sinkMBB.
13873 sinkMBB->splice(sinkMBB->begin(), MBB,
13874 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13875 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13878 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
13879 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13880 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13882 NewMO.setIsKill(false);
13883 MIB.addOperand(NewMO);
13885 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
13886 unsigned flags = (*MMOI)->getFlags();
13887 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
13888 MachineMemOperand *MMO =
13889 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
13890 (*MMOI)->getSize(),
13891 (*MMOI)->getBaseAlignment(),
13892 (*MMOI)->getTBAAInfo(),
13893 (*MMOI)->getRanges());
13894 MIB.addMemOperand(MMO);
13897 thisMBB->addSuccessor(mainMBB);
13900 MachineBasicBlock *origMainMBB = mainMBB;
13903 MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
13904 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
13906 unsigned Opc = MI->getOpcode();
13909 llvm_unreachable("Unhandled atomic-load-op opcode!");
13910 case X86::ATOMAND8:
13911 case X86::ATOMAND16:
13912 case X86::ATOMAND32:
13913 case X86::ATOMAND64:
13915 case X86::ATOMOR16:
13916 case X86::ATOMOR32:
13917 case X86::ATOMOR64:
13918 case X86::ATOMXOR8:
13919 case X86::ATOMXOR16:
13920 case X86::ATOMXOR32:
13921 case X86::ATOMXOR64: {
13922 unsigned ARITHOpc = getNonAtomicOpcode(Opc);
13923 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
13927 case X86::ATOMNAND8:
13928 case X86::ATOMNAND16:
13929 case X86::ATOMNAND32:
13930 case X86::ATOMNAND64: {
13931 unsigned Tmp = MRI.createVirtualRegister(RC);
13933 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
13934 BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
13936 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
13939 case X86::ATOMMAX8:
13940 case X86::ATOMMAX16:
13941 case X86::ATOMMAX32:
13942 case X86::ATOMMAX64:
13943 case X86::ATOMMIN8:
13944 case X86::ATOMMIN16:
13945 case X86::ATOMMIN32:
13946 case X86::ATOMMIN64:
13947 case X86::ATOMUMAX8:
13948 case X86::ATOMUMAX16:
13949 case X86::ATOMUMAX32:
13950 case X86::ATOMUMAX64:
13951 case X86::ATOMUMIN8:
13952 case X86::ATOMUMIN16:
13953 case X86::ATOMUMIN32:
13954 case X86::ATOMUMIN64: {
13956 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
13958 BuildMI(mainMBB, DL, TII->get(CMPOpc))
13962 if (Subtarget->hasCMov()) {
13963 if (VT != MVT::i8) {
13965 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
13969 // Promote i8 to i32 to use CMOV32
13970 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13971 const TargetRegisterClass *RC32 =
13972 TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
13973 unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
13974 unsigned AccReg32 = MRI.createVirtualRegister(RC32);
13975 unsigned Tmp = MRI.createVirtualRegister(RC32);
13977 unsigned Undef = MRI.createVirtualRegister(RC32);
13978 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
13980 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
13983 .addImm(X86::sub_8bit);
13984 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
13987 .addImm(X86::sub_8bit);
13989 BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
13993 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
13994 .addReg(Tmp, 0, X86::sub_8bit);
13997 // Use pseudo select and lower them.
13998 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
13999 "Invalid atomic-load-op transformation!");
14000 unsigned SelOpc = getPseudoCMOVOpc(VT);
14001 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
14002 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
14003 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
14004 .addReg(SrcReg).addReg(t4)
14006 mainMBB = EmitLoweredSelect(MIB, mainMBB);
14007 // Replace the original PHI node as mainMBB is changed after CMOV
14009 BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
14010 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
14011 Phi->eraseFromParent();
14017 // Copy PhyReg back from virtual register.
14018 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
14021 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
14022 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14023 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14025 NewMO.setIsKill(false);
14026 MIB.addOperand(NewMO);
14029 MIB.setMemRefs(MMOBegin, MMOEnd);
14031 // Copy PhyReg back to virtual register.
14032 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
14035 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
14037 mainMBB->addSuccessor(origMainMBB);
14038 mainMBB->addSuccessor(sinkMBB);
14041 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14042 TII->get(TargetOpcode::COPY), DstReg)
14045 MI->eraseFromParent();
14049 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
14050 // instructions. They will be translated into a spin-loop or compare-exchange
14054 // dst = atomic-fetch-op MI.addr, MI.val
14060 // t1L = LOAD [MI.addr + 0]
14061 // t1H = LOAD [MI.addr + 4]
14063 // t4L = phi(t1L, t3L / loop)
14064 // t4H = phi(t1H, t3H / loop)
14065 // t2L = OP MI.val.lo, t4L
14066 // t2H = OP MI.val.hi, t4H
14071 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
14079 MachineBasicBlock *
14080 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
14081 MachineBasicBlock *MBB) const {
14082 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14083 DebugLoc DL = MI->getDebugLoc();
14085 MachineFunction *MF = MBB->getParent();
14086 MachineRegisterInfo &MRI = MF->getRegInfo();
14088 const BasicBlock *BB = MBB->getBasicBlock();
14089 MachineFunction::iterator I = MBB;
14092 assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
14093 "Unexpected number of operands");
14095 assert(MI->hasOneMemOperand() &&
14096 "Expected atomic-load-op32 to have one memoperand");
14098 // Memory Reference
14099 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14100 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14102 unsigned DstLoReg, DstHiReg;
14103 unsigned SrcLoReg, SrcHiReg;
14104 unsigned MemOpndSlot;
14106 unsigned CurOp = 0;
14108 DstLoReg = MI->getOperand(CurOp++).getReg();
14109 DstHiReg = MI->getOperand(CurOp++).getReg();
14110 MemOpndSlot = CurOp;
14111 CurOp += X86::AddrNumOperands;
14112 SrcLoReg = MI->getOperand(CurOp++).getReg();
14113 SrcHiReg = MI->getOperand(CurOp++).getReg();
14115 const TargetRegisterClass *RC = &X86::GR32RegClass;
14116 const TargetRegisterClass *RC8 = &X86::GR8RegClass;
14118 unsigned t1L = MRI.createVirtualRegister(RC);
14119 unsigned t1H = MRI.createVirtualRegister(RC);
14120 unsigned t2L = MRI.createVirtualRegister(RC);
14121 unsigned t2H = MRI.createVirtualRegister(RC);
14122 unsigned t3L = MRI.createVirtualRegister(RC);
14123 unsigned t3H = MRI.createVirtualRegister(RC);
14124 unsigned t4L = MRI.createVirtualRegister(RC);
14125 unsigned t4H = MRI.createVirtualRegister(RC);
14127 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
14128 unsigned LOADOpc = X86::MOV32rm;
14130 // For the atomic load-arith operator, we generate
14133 // t1L = LOAD [MI.addr + 0]
14134 // t1H = LOAD [MI.addr + 4]
14136 // t4L = phi(t1L / thisMBB, t3L / mainMBB)
14137 // t4H = phi(t1H / thisMBB, t3H / mainMBB)
14138 // t2L = OP MI.val.lo, t4L
14139 // t2H = OP MI.val.hi, t4H
14142 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
14150 MachineBasicBlock *thisMBB = MBB;
14151 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14152 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14153 MF->insert(I, mainMBB);
14154 MF->insert(I, sinkMBB);
14156 MachineInstrBuilder MIB;
14158 // Transfer the remainder of BB and its successor edges to sinkMBB.
14159 sinkMBB->splice(sinkMBB->begin(), MBB,
14160 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14161 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14165 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
14166 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14167 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14169 NewMO.setIsKill(false);
14170 MIB.addOperand(NewMO);
14172 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
14173 unsigned flags = (*MMOI)->getFlags();
14174 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
14175 MachineMemOperand *MMO =
14176 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
14177 (*MMOI)->getSize(),
14178 (*MMOI)->getBaseAlignment(),
14179 (*MMOI)->getTBAAInfo(),
14180 (*MMOI)->getRanges());
14181 MIB.addMemOperand(MMO);
14183 MachineInstr *LowMI = MIB;
14186 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
14187 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14188 if (i == X86::AddrDisp) {
14189 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
14191 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14193 NewMO.setIsKill(false);
14194 MIB.addOperand(NewMO);
14197 MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
14199 thisMBB->addSuccessor(mainMBB);
14202 MachineBasicBlock *origMainMBB = mainMBB;
14205 MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
14206 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
14207 MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
14208 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
14210 unsigned Opc = MI->getOpcode();
14213 llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
14214 case X86::ATOMAND6432:
14215 case X86::ATOMOR6432:
14216 case X86::ATOMXOR6432:
14217 case X86::ATOMADD6432:
14218 case X86::ATOMSUB6432: {
14220 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
14221 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
14223 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
14227 case X86::ATOMNAND6432: {
14228 unsigned HiOpc, NOTOpc;
14229 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
14230 unsigned TmpL = MRI.createVirtualRegister(RC);
14231 unsigned TmpH = MRI.createVirtualRegister(RC);
14232 BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
14234 BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
14236 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
14237 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
14240 case X86::ATOMMAX6432:
14241 case X86::ATOMMIN6432:
14242 case X86::ATOMUMAX6432:
14243 case X86::ATOMUMIN6432: {
14245 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
14246 unsigned cL = MRI.createVirtualRegister(RC8);
14247 unsigned cH = MRI.createVirtualRegister(RC8);
14248 unsigned cL32 = MRI.createVirtualRegister(RC);
14249 unsigned cH32 = MRI.createVirtualRegister(RC);
14250 unsigned cc = MRI.createVirtualRegister(RC);
14251 // cl := cmp src_lo, lo
14252 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
14253 .addReg(SrcLoReg).addReg(t4L);
14254 BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
14255 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
14256 // ch := cmp src_hi, hi
14257 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
14258 .addReg(SrcHiReg).addReg(t4H);
14259 BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
14260 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
14261 // cc := if (src_hi == hi) ? cl : ch;
14262 if (Subtarget->hasCMov()) {
14263 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
14264 .addReg(cH32).addReg(cL32);
14266 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
14267 .addReg(cH32).addReg(cL32)
14268 .addImm(X86::COND_E);
14269 mainMBB = EmitLoweredSelect(MIB, mainMBB);
14271 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
14272 if (Subtarget->hasCMov()) {
14273 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
14274 .addReg(SrcLoReg).addReg(t4L);
14275 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
14276 .addReg(SrcHiReg).addReg(t4H);
14278 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
14279 .addReg(SrcLoReg).addReg(t4L)
14280 .addImm(X86::COND_NE);
14281 mainMBB = EmitLoweredSelect(MIB, mainMBB);
14282 // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
14283 // 2nd CMOV lowering.
14284 mainMBB->addLiveIn(X86::EFLAGS);
14285 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
14286 .addReg(SrcHiReg).addReg(t4H)
14287 .addImm(X86::COND_NE);
14288 mainMBB = EmitLoweredSelect(MIB, mainMBB);
14289 // Replace the original PHI node as mainMBB is changed after CMOV
14291 BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
14292 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
14293 BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
14294 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
14295 PhiL->eraseFromParent();
14296 PhiH->eraseFromParent();
14300 case X86::ATOMSWAP6432: {
14302 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
14303 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
14304 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
14309 // Copy EDX:EAX back from HiReg:LoReg
14310 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
14311 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
14312 // Copy ECX:EBX from t1H:t1L
14313 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
14314 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
14316 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
14317 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14318 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14320 NewMO.setIsKill(false);
14321 MIB.addOperand(NewMO);
14323 MIB.setMemRefs(MMOBegin, MMOEnd);
14325 // Copy EDX:EAX back to t3H:t3L
14326 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
14327 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
14329 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
14331 mainMBB->addSuccessor(origMainMBB);
14332 mainMBB->addSuccessor(sinkMBB);
14335 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14336 TII->get(TargetOpcode::COPY), DstLoReg)
14338 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14339 TII->get(TargetOpcode::COPY), DstHiReg)
14342 MI->eraseFromParent();
14346 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
14347 // or XMM0_V32I8 in AVX all of this code can be replaced with that
14348 // in the .td file.
14349 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
14350 const TargetInstrInfo *TII) {
14352 switch (MI->getOpcode()) {
14353 default: llvm_unreachable("illegal opcode!");
14354 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
14355 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
14356 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
14357 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
14358 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
14359 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
14360 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
14361 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
14364 DebugLoc dl = MI->getDebugLoc();
14365 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
14367 unsigned NumArgs = MI->getNumOperands();
14368 for (unsigned i = 1; i < NumArgs; ++i) {
14369 MachineOperand &Op = MI->getOperand(i);
14370 if (!(Op.isReg() && Op.isImplicit()))
14371 MIB.addOperand(Op);
14373 if (MI->hasOneMemOperand())
14374 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
14376 BuildMI(*BB, MI, dl,
14377 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14378 .addReg(X86::XMM0);
14380 MI->eraseFromParent();
14384 // FIXME: Custom handling because TableGen doesn't support multiple implicit
14385 // defs in an instruction pattern
14386 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
14387 const TargetInstrInfo *TII) {
14389 switch (MI->getOpcode()) {
14390 default: llvm_unreachable("illegal opcode!");
14391 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
14392 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
14393 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
14394 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
14395 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
14396 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
14397 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
14398 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
14401 DebugLoc dl = MI->getDebugLoc();
14402 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
14404 unsigned NumArgs = MI->getNumOperands(); // remove the results
14405 for (unsigned i = 1; i < NumArgs; ++i) {
14406 MachineOperand &Op = MI->getOperand(i);
14407 if (!(Op.isReg() && Op.isImplicit()))
14408 MIB.addOperand(Op);
14410 if (MI->hasOneMemOperand())
14411 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
14413 BuildMI(*BB, MI, dl,
14414 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14417 MI->eraseFromParent();
14421 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
14422 const TargetInstrInfo *TII,
14423 const X86Subtarget* Subtarget) {
14424 DebugLoc dl = MI->getDebugLoc();
14426 // Address into RAX/EAX, other two args into ECX, EDX.
14427 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
14428 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
14429 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
14430 for (int i = 0; i < X86::AddrNumOperands; ++i)
14431 MIB.addOperand(MI->getOperand(i));
14433 unsigned ValOps = X86::AddrNumOperands;
14434 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
14435 .addReg(MI->getOperand(ValOps).getReg());
14436 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
14437 .addReg(MI->getOperand(ValOps+1).getReg());
14439 // The instruction doesn't actually take any operands though.
14440 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
14442 MI->eraseFromParent(); // The pseudo is gone now.
14446 MachineBasicBlock *
14447 X86TargetLowering::EmitVAARG64WithCustomInserter(
14449 MachineBasicBlock *MBB) const {
14450 // Emit va_arg instruction on X86-64.
14452 // Operands to this pseudo-instruction:
14453 // 0 ) Output : destination address (reg)
14454 // 1-5) Input : va_list address (addr, i64mem)
14455 // 6 ) ArgSize : Size (in bytes) of vararg type
14456 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
14457 // 8 ) Align : Alignment of type
14458 // 9 ) EFLAGS (implicit-def)
14460 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
14461 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
14463 unsigned DestReg = MI->getOperand(0).getReg();
14464 MachineOperand &Base = MI->getOperand(1);
14465 MachineOperand &Scale = MI->getOperand(2);
14466 MachineOperand &Index = MI->getOperand(3);
14467 MachineOperand &Disp = MI->getOperand(4);
14468 MachineOperand &Segment = MI->getOperand(5);
14469 unsigned ArgSize = MI->getOperand(6).getImm();
14470 unsigned ArgMode = MI->getOperand(7).getImm();
14471 unsigned Align = MI->getOperand(8).getImm();
14473 // Memory Reference
14474 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
14475 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14476 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14478 // Machine Information
14479 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14480 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
14481 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
14482 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
14483 DebugLoc DL = MI->getDebugLoc();
14485 // struct va_list {
14488 // i64 overflow_area (address)
14489 // i64 reg_save_area (address)
14491 // sizeof(va_list) = 24
14492 // alignment(va_list) = 8
14494 unsigned TotalNumIntRegs = 6;
14495 unsigned TotalNumXMMRegs = 8;
14496 bool UseGPOffset = (ArgMode == 1);
14497 bool UseFPOffset = (ArgMode == 2);
14498 unsigned MaxOffset = TotalNumIntRegs * 8 +
14499 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
14501 /* Align ArgSize to a multiple of 8 */
14502 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
14503 bool NeedsAlign = (Align > 8);
14505 MachineBasicBlock *thisMBB = MBB;
14506 MachineBasicBlock *overflowMBB;
14507 MachineBasicBlock *offsetMBB;
14508 MachineBasicBlock *endMBB;
14510 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
14511 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
14512 unsigned OffsetReg = 0;
14514 if (!UseGPOffset && !UseFPOffset) {
14515 // If we only pull from the overflow region, we don't create a branch.
14516 // We don't need to alter control flow.
14517 OffsetDestReg = 0; // unused
14518 OverflowDestReg = DestReg;
14521 overflowMBB = thisMBB;
14524 // First emit code to check if gp_offset (or fp_offset) is below the bound.
14525 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
14526 // If not, pull from overflow_area. (branch to overflowMBB)
14531 // offsetMBB overflowMBB
14536 // Registers for the PHI in endMBB
14537 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
14538 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
14540 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
14541 MachineFunction *MF = MBB->getParent();
14542 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14543 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14544 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14546 MachineFunction::iterator MBBIter = MBB;
14549 // Insert the new basic blocks
14550 MF->insert(MBBIter, offsetMBB);
14551 MF->insert(MBBIter, overflowMBB);
14552 MF->insert(MBBIter, endMBB);
14554 // Transfer the remainder of MBB and its successor edges to endMBB.
14555 endMBB->splice(endMBB->begin(), thisMBB,
14556 llvm::next(MachineBasicBlock::iterator(MI)),
14558 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
14560 // Make offsetMBB and overflowMBB successors of thisMBB
14561 thisMBB->addSuccessor(offsetMBB);
14562 thisMBB->addSuccessor(overflowMBB);
14564 // endMBB is a successor of both offsetMBB and overflowMBB
14565 offsetMBB->addSuccessor(endMBB);
14566 overflowMBB->addSuccessor(endMBB);
14568 // Load the offset value into a register
14569 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
14570 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
14574 .addDisp(Disp, UseFPOffset ? 4 : 0)
14575 .addOperand(Segment)
14576 .setMemRefs(MMOBegin, MMOEnd);
14578 // Check if there is enough room left to pull this argument.
14579 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
14581 .addImm(MaxOffset + 8 - ArgSizeA8);
14583 // Branch to "overflowMBB" if offset >= max
14584 // Fall through to "offsetMBB" otherwise
14585 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
14586 .addMBB(overflowMBB);
14589 // In offsetMBB, emit code to use the reg_save_area.
14591 assert(OffsetReg != 0);
14593 // Read the reg_save_area address.
14594 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
14595 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
14600 .addOperand(Segment)
14601 .setMemRefs(MMOBegin, MMOEnd);
14603 // Zero-extend the offset
14604 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
14605 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
14608 .addImm(X86::sub_32bit);
14610 // Add the offset to the reg_save_area to get the final address.
14611 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
14612 .addReg(OffsetReg64)
14613 .addReg(RegSaveReg);
14615 // Compute the offset for the next argument
14616 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
14617 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
14619 .addImm(UseFPOffset ? 16 : 8);
14621 // Store it back into the va_list.
14622 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
14626 .addDisp(Disp, UseFPOffset ? 4 : 0)
14627 .addOperand(Segment)
14628 .addReg(NextOffsetReg)
14629 .setMemRefs(MMOBegin, MMOEnd);
14632 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
14637 // Emit code to use overflow area
14640 // Load the overflow_area address into a register.
14641 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
14642 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
14647 .addOperand(Segment)
14648 .setMemRefs(MMOBegin, MMOEnd);
14650 // If we need to align it, do so. Otherwise, just copy the address
14651 // to OverflowDestReg.
14653 // Align the overflow address
14654 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
14655 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
14657 // aligned_addr = (addr + (align-1)) & ~(align-1)
14658 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
14659 .addReg(OverflowAddrReg)
14662 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
14664 .addImm(~(uint64_t)(Align-1));
14666 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
14667 .addReg(OverflowAddrReg);
14670 // Compute the next overflow address after this argument.
14671 // (the overflow address should be kept 8-byte aligned)
14672 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
14673 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
14674 .addReg(OverflowDestReg)
14675 .addImm(ArgSizeA8);
14677 // Store the new overflow address.
14678 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
14683 .addOperand(Segment)
14684 .addReg(NextAddrReg)
14685 .setMemRefs(MMOBegin, MMOEnd);
14687 // If we branched, emit the PHI to the front of endMBB.
14689 BuildMI(*endMBB, endMBB->begin(), DL,
14690 TII->get(X86::PHI), DestReg)
14691 .addReg(OffsetDestReg).addMBB(offsetMBB)
14692 .addReg(OverflowDestReg).addMBB(overflowMBB);
14695 // Erase the pseudo instruction
14696 MI->eraseFromParent();
14701 MachineBasicBlock *
14702 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
14704 MachineBasicBlock *MBB) const {
14705 // Emit code to save XMM registers to the stack. The ABI says that the
14706 // number of registers to save is given in %al, so it's theoretically
14707 // possible to do an indirect jump trick to avoid saving all of them,
14708 // however this code takes a simpler approach and just executes all
14709 // of the stores if %al is non-zero. It's less code, and it's probably
14710 // easier on the hardware branch predictor, and stores aren't all that
14711 // expensive anyway.
14713 // Create the new basic blocks. One block contains all the XMM stores,
14714 // and one block is the final destination regardless of whether any
14715 // stores were performed.
14716 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
14717 MachineFunction *F = MBB->getParent();
14718 MachineFunction::iterator MBBIter = MBB;
14720 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
14721 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
14722 F->insert(MBBIter, XMMSaveMBB);
14723 F->insert(MBBIter, EndMBB);
14725 // Transfer the remainder of MBB and its successor edges to EndMBB.
14726 EndMBB->splice(EndMBB->begin(), MBB,
14727 llvm::next(MachineBasicBlock::iterator(MI)),
14729 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
14731 // The original block will now fall through to the XMM save block.
14732 MBB->addSuccessor(XMMSaveMBB);
14733 // The XMMSaveMBB will fall through to the end block.
14734 XMMSaveMBB->addSuccessor(EndMBB);
14736 // Now add the instructions.
14737 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14738 DebugLoc DL = MI->getDebugLoc();
14740 unsigned CountReg = MI->getOperand(0).getReg();
14741 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
14742 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
14744 if (!Subtarget->isTargetWin64()) {
14745 // If %al is 0, branch around the XMM save block.
14746 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
14747 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
14748 MBB->addSuccessor(EndMBB);
14751 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
14752 // In the XMM save block, save all the XMM argument registers.
14753 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
14754 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
14755 MachineMemOperand *MMO =
14756 F->getMachineMemOperand(
14757 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
14758 MachineMemOperand::MOStore,
14759 /*Size=*/16, /*Align=*/16);
14760 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
14761 .addFrameIndex(RegSaveFrameIndex)
14762 .addImm(/*Scale=*/1)
14763 .addReg(/*IndexReg=*/0)
14764 .addImm(/*Disp=*/Offset)
14765 .addReg(/*Segment=*/0)
14766 .addReg(MI->getOperand(i).getReg())
14767 .addMemOperand(MMO);
14770 MI->eraseFromParent(); // The pseudo instruction is gone now.
14775 // The EFLAGS operand of SelectItr might be missing a kill marker
14776 // because there were multiple uses of EFLAGS, and ISel didn't know
14777 // which to mark. Figure out whether SelectItr should have had a
14778 // kill marker, and set it if it should. Returns the correct kill
14780 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
14781 MachineBasicBlock* BB,
14782 const TargetRegisterInfo* TRI) {
14783 // Scan forward through BB for a use/def of EFLAGS.
14784 MachineBasicBlock::iterator miI(llvm::next(SelectItr));
14785 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
14786 const MachineInstr& mi = *miI;
14787 if (mi.readsRegister(X86::EFLAGS))
14789 if (mi.definesRegister(X86::EFLAGS))
14790 break; // Should have kill-flag - update below.
14793 // If we hit the end of the block, check whether EFLAGS is live into a
14795 if (miI == BB->end()) {
14796 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
14797 sEnd = BB->succ_end();
14798 sItr != sEnd; ++sItr) {
14799 MachineBasicBlock* succ = *sItr;
14800 if (succ->isLiveIn(X86::EFLAGS))
14805 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
14806 // out. SelectMI should have a kill flag on EFLAGS.
14807 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
14811 MachineBasicBlock *
14812 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
14813 MachineBasicBlock *BB) const {
14814 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14815 DebugLoc DL = MI->getDebugLoc();
14817 // To "insert" a SELECT_CC instruction, we actually have to insert the
14818 // diamond control-flow pattern. The incoming instruction knows the
14819 // destination vreg to set, the condition code register to branch on, the
14820 // true/false values to select between, and a branch opcode to use.
14821 const BasicBlock *LLVM_BB = BB->getBasicBlock();
14822 MachineFunction::iterator It = BB;
14828 // cmpTY ccX, r1, r2
14830 // fallthrough --> copy0MBB
14831 MachineBasicBlock *thisMBB = BB;
14832 MachineFunction *F = BB->getParent();
14833 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
14834 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
14835 F->insert(It, copy0MBB);
14836 F->insert(It, sinkMBB);
14838 // If the EFLAGS register isn't dead in the terminator, then claim that it's
14839 // live into the sink and copy blocks.
14840 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
14841 if (!MI->killsRegister(X86::EFLAGS) &&
14842 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
14843 copy0MBB->addLiveIn(X86::EFLAGS);
14844 sinkMBB->addLiveIn(X86::EFLAGS);
14847 // Transfer the remainder of BB and its successor edges to sinkMBB.
14848 sinkMBB->splice(sinkMBB->begin(), BB,
14849 llvm::next(MachineBasicBlock::iterator(MI)),
14851 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
14853 // Add the true and fallthrough blocks as its successors.
14854 BB->addSuccessor(copy0MBB);
14855 BB->addSuccessor(sinkMBB);
14857 // Create the conditional branch instruction.
14859 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
14860 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
14863 // %FalseValue = ...
14864 // # fallthrough to sinkMBB
14865 copy0MBB->addSuccessor(sinkMBB);
14868 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
14870 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14871 TII->get(X86::PHI), MI->getOperand(0).getReg())
14872 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
14873 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
14875 MI->eraseFromParent(); // The pseudo instruction is gone now.
14879 MachineBasicBlock *
14880 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
14881 bool Is64Bit) const {
14882 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14883 DebugLoc DL = MI->getDebugLoc();
14884 MachineFunction *MF = BB->getParent();
14885 const BasicBlock *LLVM_BB = BB->getBasicBlock();
14887 assert(getTargetMachine().Options.EnableSegmentedStacks);
14889 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
14890 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
14893 // ... [Till the alloca]
14894 // If stacklet is not large enough, jump to mallocMBB
14897 // Allocate by subtracting from RSP
14898 // Jump to continueMBB
14901 // Allocate by call to runtime
14905 // [rest of original BB]
14908 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14909 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14910 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14912 MachineRegisterInfo &MRI = MF->getRegInfo();
14913 const TargetRegisterClass *AddrRegClass =
14914 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
14916 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
14917 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
14918 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
14919 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
14920 sizeVReg = MI->getOperand(1).getReg(),
14921 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
14923 MachineFunction::iterator MBBIter = BB;
14926 MF->insert(MBBIter, bumpMBB);
14927 MF->insert(MBBIter, mallocMBB);
14928 MF->insert(MBBIter, continueMBB);
14930 continueMBB->splice(continueMBB->begin(), BB, llvm::next
14931 (MachineBasicBlock::iterator(MI)), BB->end());
14932 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
14934 // Add code to the main basic block to check if the stack limit has been hit,
14935 // and if so, jump to mallocMBB otherwise to bumpMBB.
14936 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
14937 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
14938 .addReg(tmpSPVReg).addReg(sizeVReg);
14939 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
14940 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
14941 .addReg(SPLimitVReg);
14942 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
14944 // bumpMBB simply decreases the stack pointer, since we know the current
14945 // stacklet has enough space.
14946 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
14947 .addReg(SPLimitVReg);
14948 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
14949 .addReg(SPLimitVReg);
14950 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
14952 // Calls into a routine in libgcc to allocate more space from the heap.
14953 const uint32_t *RegMask =
14954 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
14956 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
14958 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
14959 .addExternalSymbol("__morestack_allocate_stack_space")
14960 .addRegMask(RegMask)
14961 .addReg(X86::RDI, RegState::Implicit)
14962 .addReg(X86::RAX, RegState::ImplicitDefine);
14964 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
14966 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
14967 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
14968 .addExternalSymbol("__morestack_allocate_stack_space")
14969 .addRegMask(RegMask)
14970 .addReg(X86::EAX, RegState::ImplicitDefine);
14974 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
14977 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
14978 .addReg(Is64Bit ? X86::RAX : X86::EAX);
14979 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
14981 // Set up the CFG correctly.
14982 BB->addSuccessor(bumpMBB);
14983 BB->addSuccessor(mallocMBB);
14984 mallocMBB->addSuccessor(continueMBB);
14985 bumpMBB->addSuccessor(continueMBB);
14987 // Take care of the PHI nodes.
14988 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
14989 MI->getOperand(0).getReg())
14990 .addReg(mallocPtrVReg).addMBB(mallocMBB)
14991 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
14993 // Delete the original pseudo instruction.
14994 MI->eraseFromParent();
14997 return continueMBB;
15000 MachineBasicBlock *
15001 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
15002 MachineBasicBlock *BB) const {
15003 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15004 DebugLoc DL = MI->getDebugLoc();
15006 assert(!Subtarget->isTargetEnvMacho());
15008 // The lowering is pretty easy: we're just emitting the call to _alloca. The
15009 // non-trivial part is impdef of ESP.
15011 if (Subtarget->isTargetWin64()) {
15012 if (Subtarget->isTargetCygMing()) {
15013 // ___chkstk(Mingw64):
15014 // Clobbers R10, R11, RAX and EFLAGS.
15016 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
15017 .addExternalSymbol("___chkstk")
15018 .addReg(X86::RAX, RegState::Implicit)
15019 .addReg(X86::RSP, RegState::Implicit)
15020 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
15021 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
15022 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15024 // __chkstk(MSVCRT): does not update stack pointer.
15025 // Clobbers R10, R11 and EFLAGS.
15026 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
15027 .addExternalSymbol("__chkstk")
15028 .addReg(X86::RAX, RegState::Implicit)
15029 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15030 // RAX has the offset to be subtracted from RSP.
15031 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
15036 const char *StackProbeSymbol =
15037 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
15039 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
15040 .addExternalSymbol(StackProbeSymbol)
15041 .addReg(X86::EAX, RegState::Implicit)
15042 .addReg(X86::ESP, RegState::Implicit)
15043 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
15044 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
15045 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15048 MI->eraseFromParent(); // The pseudo instruction is gone now.
15052 MachineBasicBlock *
15053 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
15054 MachineBasicBlock *BB) const {
15055 // This is pretty easy. We're taking the value that we received from
15056 // our load from the relocation, sticking it in either RDI (x86-64)
15057 // or EAX and doing an indirect call. The return value will then
15058 // be in the normal return register.
15059 const X86InstrInfo *TII
15060 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
15061 DebugLoc DL = MI->getDebugLoc();
15062 MachineFunction *F = BB->getParent();
15064 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
15065 assert(MI->getOperand(3).isGlobal() && "This should be a global");
15067 // Get a register mask for the lowered call.
15068 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
15069 // proper register mask.
15070 const uint32_t *RegMask =
15071 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
15072 if (Subtarget->is64Bit()) {
15073 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15074 TII->get(X86::MOV64rm), X86::RDI)
15076 .addImm(0).addReg(0)
15077 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15078 MI->getOperand(3).getTargetFlags())
15080 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
15081 addDirectMem(MIB, X86::RDI);
15082 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
15083 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
15084 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15085 TII->get(X86::MOV32rm), X86::EAX)
15087 .addImm(0).addReg(0)
15088 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15089 MI->getOperand(3).getTargetFlags())
15091 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
15092 addDirectMem(MIB, X86::EAX);
15093 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
15095 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15096 TII->get(X86::MOV32rm), X86::EAX)
15097 .addReg(TII->getGlobalBaseReg(F))
15098 .addImm(0).addReg(0)
15099 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15100 MI->getOperand(3).getTargetFlags())
15102 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
15103 addDirectMem(MIB, X86::EAX);
15104 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
15107 MI->eraseFromParent(); // The pseudo instruction is gone now.
15111 MachineBasicBlock *
15112 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
15113 MachineBasicBlock *MBB) const {
15114 DebugLoc DL = MI->getDebugLoc();
15115 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15117 MachineFunction *MF = MBB->getParent();
15118 MachineRegisterInfo &MRI = MF->getRegInfo();
15120 const BasicBlock *BB = MBB->getBasicBlock();
15121 MachineFunction::iterator I = MBB;
15124 // Memory Reference
15125 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15126 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15129 unsigned MemOpndSlot = 0;
15131 unsigned CurOp = 0;
15133 DstReg = MI->getOperand(CurOp++).getReg();
15134 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15135 assert(RC->hasType(MVT::i32) && "Invalid destination!");
15136 unsigned mainDstReg = MRI.createVirtualRegister(RC);
15137 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
15139 MemOpndSlot = CurOp;
15141 MVT PVT = getPointerTy();
15142 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
15143 "Invalid Pointer Size!");
15145 // For v = setjmp(buf), we generate
15148 // buf[LabelOffset] = restoreMBB
15149 // SjLjSetup restoreMBB
15155 // v = phi(main, restore)
15160 MachineBasicBlock *thisMBB = MBB;
15161 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15162 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15163 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
15164 MF->insert(I, mainMBB);
15165 MF->insert(I, sinkMBB);
15166 MF->push_back(restoreMBB);
15168 MachineInstrBuilder MIB;
15170 // Transfer the remainder of BB and its successor edges to sinkMBB.
15171 sinkMBB->splice(sinkMBB->begin(), MBB,
15172 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
15173 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15176 unsigned PtrStoreOpc = 0;
15177 unsigned LabelReg = 0;
15178 const int64_t LabelOffset = 1 * PVT.getStoreSize();
15179 Reloc::Model RM = getTargetMachine().getRelocationModel();
15180 bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
15181 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
15183 // Prepare IP either in reg or imm.
15184 if (!UseImmLabel) {
15185 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
15186 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
15187 LabelReg = MRI.createVirtualRegister(PtrRC);
15188 if (Subtarget->is64Bit()) {
15189 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
15193 .addMBB(restoreMBB)
15196 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
15197 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
15198 .addReg(XII->getGlobalBaseReg(MF))
15201 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
15205 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
15207 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
15208 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15209 if (i == X86::AddrDisp)
15210 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
15212 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
15215 MIB.addReg(LabelReg);
15217 MIB.addMBB(restoreMBB);
15218 MIB.setMemRefs(MMOBegin, MMOEnd);
15220 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
15221 .addMBB(restoreMBB);
15223 const X86RegisterInfo *RegInfo =
15224 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
15225 MIB.addRegMask(RegInfo->getNoPreservedMask());
15226 thisMBB->addSuccessor(mainMBB);
15227 thisMBB->addSuccessor(restoreMBB);
15231 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
15232 mainMBB->addSuccessor(sinkMBB);
15235 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15236 TII->get(X86::PHI), DstReg)
15237 .addReg(mainDstReg).addMBB(mainMBB)
15238 .addReg(restoreDstReg).addMBB(restoreMBB);
15241 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
15242 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
15243 restoreMBB->addSuccessor(sinkMBB);
15245 MI->eraseFromParent();
15249 MachineBasicBlock *
15250 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
15251 MachineBasicBlock *MBB) const {
15252 DebugLoc DL = MI->getDebugLoc();
15253 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15255 MachineFunction *MF = MBB->getParent();
15256 MachineRegisterInfo &MRI = MF->getRegInfo();
15258 // Memory Reference
15259 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15260 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15262 MVT PVT = getPointerTy();
15263 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
15264 "Invalid Pointer Size!");
15266 const TargetRegisterClass *RC =
15267 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
15268 unsigned Tmp = MRI.createVirtualRegister(RC);
15269 // Since FP is only updated here but NOT referenced, it's treated as GPR.
15270 const X86RegisterInfo *RegInfo =
15271 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
15272 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
15273 unsigned SP = RegInfo->getStackRegister();
15275 MachineInstrBuilder MIB;
15277 const int64_t LabelOffset = 1 * PVT.getStoreSize();
15278 const int64_t SPOffset = 2 * PVT.getStoreSize();
15280 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
15281 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
15284 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
15285 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
15286 MIB.addOperand(MI->getOperand(i));
15287 MIB.setMemRefs(MMOBegin, MMOEnd);
15289 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
15290 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15291 if (i == X86::AddrDisp)
15292 MIB.addDisp(MI->getOperand(i), LabelOffset);
15294 MIB.addOperand(MI->getOperand(i));
15296 MIB.setMemRefs(MMOBegin, MMOEnd);
15298 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
15299 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15300 if (i == X86::AddrDisp)
15301 MIB.addDisp(MI->getOperand(i), SPOffset);
15303 MIB.addOperand(MI->getOperand(i));
15305 MIB.setMemRefs(MMOBegin, MMOEnd);
15307 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
15309 MI->eraseFromParent();
15313 MachineBasicBlock *
15314 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
15315 MachineBasicBlock *BB) const {
15316 switch (MI->getOpcode()) {
15317 default: llvm_unreachable("Unexpected instr type to insert");
15318 case X86::TAILJMPd64:
15319 case X86::TAILJMPr64:
15320 case X86::TAILJMPm64:
15321 llvm_unreachable("TAILJMP64 would not be touched here.");
15322 case X86::TCRETURNdi64:
15323 case X86::TCRETURNri64:
15324 case X86::TCRETURNmi64:
15326 case X86::WIN_ALLOCA:
15327 return EmitLoweredWinAlloca(MI, BB);
15328 case X86::SEG_ALLOCA_32:
15329 return EmitLoweredSegAlloca(MI, BB, false);
15330 case X86::SEG_ALLOCA_64:
15331 return EmitLoweredSegAlloca(MI, BB, true);
15332 case X86::TLSCall_32:
15333 case X86::TLSCall_64:
15334 return EmitLoweredTLSCall(MI, BB);
15335 case X86::CMOV_GR8:
15336 case X86::CMOV_FR32:
15337 case X86::CMOV_FR64:
15338 case X86::CMOV_V4F32:
15339 case X86::CMOV_V2F64:
15340 case X86::CMOV_V2I64:
15341 case X86::CMOV_V8F32:
15342 case X86::CMOV_V4F64:
15343 case X86::CMOV_V4I64:
15344 case X86::CMOV_GR16:
15345 case X86::CMOV_GR32:
15346 case X86::CMOV_RFP32:
15347 case X86::CMOV_RFP64:
15348 case X86::CMOV_RFP80:
15349 return EmitLoweredSelect(MI, BB);
15351 case X86::FP32_TO_INT16_IN_MEM:
15352 case X86::FP32_TO_INT32_IN_MEM:
15353 case X86::FP32_TO_INT64_IN_MEM:
15354 case X86::FP64_TO_INT16_IN_MEM:
15355 case X86::FP64_TO_INT32_IN_MEM:
15356 case X86::FP64_TO_INT64_IN_MEM:
15357 case X86::FP80_TO_INT16_IN_MEM:
15358 case X86::FP80_TO_INT32_IN_MEM:
15359 case X86::FP80_TO_INT64_IN_MEM: {
15360 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15361 DebugLoc DL = MI->getDebugLoc();
15363 // Change the floating point control register to use "round towards zero"
15364 // mode when truncating to an integer value.
15365 MachineFunction *F = BB->getParent();
15366 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
15367 addFrameReference(BuildMI(*BB, MI, DL,
15368 TII->get(X86::FNSTCW16m)), CWFrameIdx);
15370 // Load the old value of the high byte of the control word...
15372 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
15373 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
15376 // Set the high part to be round to zero...
15377 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
15380 // Reload the modified control word now...
15381 addFrameReference(BuildMI(*BB, MI, DL,
15382 TII->get(X86::FLDCW16m)), CWFrameIdx);
15384 // Restore the memory image of control word to original value
15385 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
15388 // Get the X86 opcode to use.
15390 switch (MI->getOpcode()) {
15391 default: llvm_unreachable("illegal opcode!");
15392 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
15393 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
15394 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
15395 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
15396 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
15397 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
15398 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
15399 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
15400 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
15404 MachineOperand &Op = MI->getOperand(0);
15406 AM.BaseType = X86AddressMode::RegBase;
15407 AM.Base.Reg = Op.getReg();
15409 AM.BaseType = X86AddressMode::FrameIndexBase;
15410 AM.Base.FrameIndex = Op.getIndex();
15412 Op = MI->getOperand(1);
15414 AM.Scale = Op.getImm();
15415 Op = MI->getOperand(2);
15417 AM.IndexReg = Op.getImm();
15418 Op = MI->getOperand(3);
15419 if (Op.isGlobal()) {
15420 AM.GV = Op.getGlobal();
15422 AM.Disp = Op.getImm();
15424 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
15425 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
15427 // Reload the original control word now.
15428 addFrameReference(BuildMI(*BB, MI, DL,
15429 TII->get(X86::FLDCW16m)), CWFrameIdx);
15431 MI->eraseFromParent(); // The pseudo instruction is gone now.
15434 // String/text processing lowering.
15435 case X86::PCMPISTRM128REG:
15436 case X86::VPCMPISTRM128REG:
15437 case X86::PCMPISTRM128MEM:
15438 case X86::VPCMPISTRM128MEM:
15439 case X86::PCMPESTRM128REG:
15440 case X86::VPCMPESTRM128REG:
15441 case X86::PCMPESTRM128MEM:
15442 case X86::VPCMPESTRM128MEM:
15443 assert(Subtarget->hasSSE42() &&
15444 "Target must have SSE4.2 or AVX features enabled");
15445 return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
15447 // String/text processing lowering.
15448 case X86::PCMPISTRIREG:
15449 case X86::VPCMPISTRIREG:
15450 case X86::PCMPISTRIMEM:
15451 case X86::VPCMPISTRIMEM:
15452 case X86::PCMPESTRIREG:
15453 case X86::VPCMPESTRIREG:
15454 case X86::PCMPESTRIMEM:
15455 case X86::VPCMPESTRIMEM:
15456 assert(Subtarget->hasSSE42() &&
15457 "Target must have SSE4.2 or AVX features enabled");
15458 return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
15460 // Thread synchronization.
15462 return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
15466 return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
15468 // Atomic Lowering.
15469 case X86::ATOMAND8:
15470 case X86::ATOMAND16:
15471 case X86::ATOMAND32:
15472 case X86::ATOMAND64:
15475 case X86::ATOMOR16:
15476 case X86::ATOMOR32:
15477 case X86::ATOMOR64:
15479 case X86::ATOMXOR16:
15480 case X86::ATOMXOR8:
15481 case X86::ATOMXOR32:
15482 case X86::ATOMXOR64:
15484 case X86::ATOMNAND8:
15485 case X86::ATOMNAND16:
15486 case X86::ATOMNAND32:
15487 case X86::ATOMNAND64:
15489 case X86::ATOMMAX8:
15490 case X86::ATOMMAX16:
15491 case X86::ATOMMAX32:
15492 case X86::ATOMMAX64:
15494 case X86::ATOMMIN8:
15495 case X86::ATOMMIN16:
15496 case X86::ATOMMIN32:
15497 case X86::ATOMMIN64:
15499 case X86::ATOMUMAX8:
15500 case X86::ATOMUMAX16:
15501 case X86::ATOMUMAX32:
15502 case X86::ATOMUMAX64:
15504 case X86::ATOMUMIN8:
15505 case X86::ATOMUMIN16:
15506 case X86::ATOMUMIN32:
15507 case X86::ATOMUMIN64:
15508 return EmitAtomicLoadArith(MI, BB);
15510 // This group does 64-bit operations on a 32-bit host.
15511 case X86::ATOMAND6432:
15512 case X86::ATOMOR6432:
15513 case X86::ATOMXOR6432:
15514 case X86::ATOMNAND6432:
15515 case X86::ATOMADD6432:
15516 case X86::ATOMSUB6432:
15517 case X86::ATOMMAX6432:
15518 case X86::ATOMMIN6432:
15519 case X86::ATOMUMAX6432:
15520 case X86::ATOMUMIN6432:
15521 case X86::ATOMSWAP6432:
15522 return EmitAtomicLoadArith6432(MI, BB);
15524 case X86::VASTART_SAVE_XMM_REGS:
15525 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
15527 case X86::VAARG_64:
15528 return EmitVAARG64WithCustomInserter(MI, BB);
15530 case X86::EH_SjLj_SetJmp32:
15531 case X86::EH_SjLj_SetJmp64:
15532 return emitEHSjLjSetJmp(MI, BB);
15534 case X86::EH_SjLj_LongJmp32:
15535 case X86::EH_SjLj_LongJmp64:
15536 return emitEHSjLjLongJmp(MI, BB);
15540 //===----------------------------------------------------------------------===//
15541 // X86 Optimization Hooks
15542 //===----------------------------------------------------------------------===//
15544 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
15547 const SelectionDAG &DAG,
15548 unsigned Depth) const {
15549 unsigned BitWidth = KnownZero.getBitWidth();
15550 unsigned Opc = Op.getOpcode();
15551 assert((Opc >= ISD::BUILTIN_OP_END ||
15552 Opc == ISD::INTRINSIC_WO_CHAIN ||
15553 Opc == ISD::INTRINSIC_W_CHAIN ||
15554 Opc == ISD::INTRINSIC_VOID) &&
15555 "Should use MaskedValueIsZero if you don't know whether Op"
15556 " is a target node!");
15558 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
15572 // These nodes' second result is a boolean.
15573 if (Op.getResNo() == 0)
15576 case X86ISD::SETCC:
15577 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
15579 case ISD::INTRINSIC_WO_CHAIN: {
15580 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15581 unsigned NumLoBits = 0;
15584 case Intrinsic::x86_sse_movmsk_ps:
15585 case Intrinsic::x86_avx_movmsk_ps_256:
15586 case Intrinsic::x86_sse2_movmsk_pd:
15587 case Intrinsic::x86_avx_movmsk_pd_256:
15588 case Intrinsic::x86_mmx_pmovmskb:
15589 case Intrinsic::x86_sse2_pmovmskb_128:
15590 case Intrinsic::x86_avx2_pmovmskb: {
15591 // High bits of movmskp{s|d}, pmovmskb are known zero.
15593 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
15594 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
15595 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
15596 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
15597 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
15598 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
15599 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
15600 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
15602 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
15611 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
15612 unsigned Depth) const {
15613 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
15614 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
15615 return Op.getValueType().getScalarType().getSizeInBits();
15621 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
15622 /// node is a GlobalAddress + offset.
15623 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
15624 const GlobalValue* &GA,
15625 int64_t &Offset) const {
15626 if (N->getOpcode() == X86ISD::Wrapper) {
15627 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
15628 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
15629 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
15633 return TargetLowering::isGAPlusOffset(N, GA, Offset);
15636 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
15637 /// same as extracting the high 128-bit part of 256-bit vector and then
15638 /// inserting the result into the low part of a new 256-bit vector
15639 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
15640 EVT VT = SVOp->getValueType(0);
15641 unsigned NumElems = VT.getVectorNumElements();
15643 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
15644 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
15645 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
15646 SVOp->getMaskElt(j) >= 0)
15652 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
15653 /// same as extracting the low 128-bit part of 256-bit vector and then
15654 /// inserting the result into the high part of a new 256-bit vector
15655 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
15656 EVT VT = SVOp->getValueType(0);
15657 unsigned NumElems = VT.getVectorNumElements();
15659 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
15660 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
15661 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
15662 SVOp->getMaskElt(j) >= 0)
15668 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
15669 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
15670 TargetLowering::DAGCombinerInfo &DCI,
15671 const X86Subtarget* Subtarget) {
15673 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
15674 SDValue V1 = SVOp->getOperand(0);
15675 SDValue V2 = SVOp->getOperand(1);
15676 EVT VT = SVOp->getValueType(0);
15677 unsigned NumElems = VT.getVectorNumElements();
15679 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
15680 V2.getOpcode() == ISD::CONCAT_VECTORS) {
15684 // V UNDEF BUILD_VECTOR UNDEF
15686 // CONCAT_VECTOR CONCAT_VECTOR
15689 // RESULT: V + zero extended
15691 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
15692 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
15693 V1.getOperand(1).getOpcode() != ISD::UNDEF)
15696 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
15699 // To match the shuffle mask, the first half of the mask should
15700 // be exactly the first vector, and all the rest a splat with the
15701 // first element of the second one.
15702 for (unsigned i = 0; i != NumElems/2; ++i)
15703 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
15704 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
15707 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
15708 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
15709 if (Ld->hasNUsesOfValue(1, 0)) {
15710 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
15711 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
15713 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
15714 array_lengthof(Ops),
15716 Ld->getPointerInfo(),
15717 Ld->getAlignment(),
15718 false/*isVolatile*/, true/*ReadMem*/,
15719 false/*WriteMem*/);
15721 // Make sure the newly-created LOAD is in the same position as Ld in
15722 // terms of dependency. We create a TokenFactor for Ld and ResNode,
15723 // and update uses of Ld's output chain to use the TokenFactor.
15724 if (Ld->hasAnyUseOfValue(1)) {
15725 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
15726 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
15727 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
15728 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
15729 SDValue(ResNode.getNode(), 1));
15732 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
15736 // Emit a zeroed vector and insert the desired subvector on its
15738 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15739 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
15740 return DCI.CombineTo(N, InsV);
15743 //===--------------------------------------------------------------------===//
15744 // Combine some shuffles into subvector extracts and inserts:
15747 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
15748 if (isShuffleHigh128VectorInsertLow(SVOp)) {
15749 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
15750 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
15751 return DCI.CombineTo(N, InsV);
15754 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
15755 if (isShuffleLow128VectorInsertHigh(SVOp)) {
15756 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
15757 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
15758 return DCI.CombineTo(N, InsV);
15764 /// PerformShuffleCombine - Performs several different shuffle combines.
15765 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
15766 TargetLowering::DAGCombinerInfo &DCI,
15767 const X86Subtarget *Subtarget) {
15769 EVT VT = N->getValueType(0);
15771 // Don't create instructions with illegal types after legalize types has run.
15772 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15773 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
15776 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
15777 if (Subtarget->hasFp256() && VT.is256BitVector() &&
15778 N->getOpcode() == ISD::VECTOR_SHUFFLE)
15779 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
15781 // Only handle 128 wide vector from here on.
15782 if (!VT.is128BitVector())
15785 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
15786 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
15787 // consecutive, non-overlapping, and in the right order.
15788 SmallVector<SDValue, 16> Elts;
15789 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
15790 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
15792 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
15795 /// PerformTruncateCombine - Converts truncate operation to
15796 /// a sequence of vector shuffle operations.
15797 /// It is possible when we truncate 256-bit vector to 128-bit vector
15798 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
15799 TargetLowering::DAGCombinerInfo &DCI,
15800 const X86Subtarget *Subtarget) {
15804 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
15805 /// specific shuffle of a load can be folded into a single element load.
15806 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
15807 /// shuffles have been customed lowered so we need to handle those here.
15808 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
15809 TargetLowering::DAGCombinerInfo &DCI) {
15810 if (DCI.isBeforeLegalizeOps())
15813 SDValue InVec = N->getOperand(0);
15814 SDValue EltNo = N->getOperand(1);
15816 if (!isa<ConstantSDNode>(EltNo))
15819 EVT VT = InVec.getValueType();
15821 bool HasShuffleIntoBitcast = false;
15822 if (InVec.getOpcode() == ISD::BITCAST) {
15823 // Don't duplicate a load with other uses.
15824 if (!InVec.hasOneUse())
15826 EVT BCVT = InVec.getOperand(0).getValueType();
15827 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
15829 InVec = InVec.getOperand(0);
15830 HasShuffleIntoBitcast = true;
15833 if (!isTargetShuffle(InVec.getOpcode()))
15836 // Don't duplicate a load with other uses.
15837 if (!InVec.hasOneUse())
15840 SmallVector<int, 16> ShuffleMask;
15842 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
15846 // Select the input vector, guarding against out of range extract vector.
15847 unsigned NumElems = VT.getVectorNumElements();
15848 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
15849 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
15850 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
15851 : InVec.getOperand(1);
15853 // If inputs to shuffle are the same for both ops, then allow 2 uses
15854 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
15856 if (LdNode.getOpcode() == ISD::BITCAST) {
15857 // Don't duplicate a load with other uses.
15858 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
15861 AllowedUses = 1; // only allow 1 load use if we have a bitcast
15862 LdNode = LdNode.getOperand(0);
15865 if (!ISD::isNormalLoad(LdNode.getNode()))
15868 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
15870 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
15873 if (HasShuffleIntoBitcast) {
15874 // If there's a bitcast before the shuffle, check if the load type and
15875 // alignment is valid.
15876 unsigned Align = LN0->getAlignment();
15877 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15878 unsigned NewAlign = TLI.getDataLayout()->
15879 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
15881 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
15885 // All checks match so transform back to vector_shuffle so that DAG combiner
15886 // can finish the job
15889 // Create shuffle node taking into account the case that its a unary shuffle
15890 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
15891 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
15892 InVec.getOperand(0), Shuffle,
15894 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
15895 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
15899 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
15900 /// generation and convert it from being a bunch of shuffles and extracts
15901 /// to a simple store and scalar loads to extract the elements.
15902 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
15903 TargetLowering::DAGCombinerInfo &DCI) {
15904 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
15905 if (NewOp.getNode())
15908 SDValue InputVector = N->getOperand(0);
15909 // Detect whether we are trying to convert from mmx to i32 and the bitcast
15910 // from mmx to v2i32 has a single usage.
15911 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
15912 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
15913 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
15914 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
15915 N->getValueType(0),
15916 InputVector.getNode()->getOperand(0));
15918 // Only operate on vectors of 4 elements, where the alternative shuffling
15919 // gets to be more expensive.
15920 if (InputVector.getValueType() != MVT::v4i32)
15923 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
15924 // single use which is a sign-extend or zero-extend, and all elements are
15926 SmallVector<SDNode *, 4> Uses;
15927 unsigned ExtractedElements = 0;
15928 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
15929 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
15930 if (UI.getUse().getResNo() != InputVector.getResNo())
15933 SDNode *Extract = *UI;
15934 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
15937 if (Extract->getValueType(0) != MVT::i32)
15939 if (!Extract->hasOneUse())
15941 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
15942 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
15944 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
15947 // Record which element was extracted.
15948 ExtractedElements |=
15949 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
15951 Uses.push_back(Extract);
15954 // If not all the elements were used, this may not be worthwhile.
15955 if (ExtractedElements != 15)
15958 // Ok, we've now decided to do the transformation.
15959 SDLoc dl(InputVector);
15961 // Store the value to a temporary stack slot.
15962 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
15963 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
15964 MachinePointerInfo(), false, false, 0);
15966 // Replace each use (extract) with a load of the appropriate element.
15967 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
15968 UE = Uses.end(); UI != UE; ++UI) {
15969 SDNode *Extract = *UI;
15971 // cOMpute the element's address.
15972 SDValue Idx = Extract->getOperand(1);
15974 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
15975 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
15976 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15977 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
15979 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
15980 StackPtr, OffsetVal);
15982 // Load the scalar.
15983 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
15984 ScalarAddr, MachinePointerInfo(),
15985 false, false, false, 0);
15987 // Replace the exact with the load.
15988 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
15991 // The replacement was made in place; don't return anything.
15995 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
15996 static unsigned matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS,
15997 SDValue RHS, SelectionDAG &DAG,
15998 const X86Subtarget *Subtarget) {
15999 if (!VT.isVector())
16002 switch (VT.getSimpleVT().SimpleTy) {
16007 if (!Subtarget->hasAVX2())
16012 if (!Subtarget->hasSSE2())
16016 // SSE2 has only a small subset of the operations.
16017 bool hasUnsigned = Subtarget->hasSSE41() ||
16018 (Subtarget->hasSSE2() && VT == MVT::v16i8);
16019 bool hasSigned = Subtarget->hasSSE41() ||
16020 (Subtarget->hasSSE2() && VT == MVT::v8i16);
16022 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16024 // Check for x CC y ? x : y.
16025 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
16026 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
16031 return hasUnsigned ? X86ISD::UMIN : 0;
16034 return hasUnsigned ? X86ISD::UMAX : 0;
16037 return hasSigned ? X86ISD::SMIN : 0;
16040 return hasSigned ? X86ISD::SMAX : 0;
16042 // Check for x CC y ? y : x -- a min/max with reversed arms.
16043 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
16044 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
16049 return hasUnsigned ? X86ISD::UMAX : 0;
16052 return hasUnsigned ? X86ISD::UMIN : 0;
16055 return hasSigned ? X86ISD::SMAX : 0;
16058 return hasSigned ? X86ISD::SMIN : 0;
16065 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
16067 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
16068 TargetLowering::DAGCombinerInfo &DCI,
16069 const X86Subtarget *Subtarget) {
16071 SDValue Cond = N->getOperand(0);
16072 // Get the LHS/RHS of the select.
16073 SDValue LHS = N->getOperand(1);
16074 SDValue RHS = N->getOperand(2);
16075 EVT VT = LHS.getValueType();
16077 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
16078 // instructions match the semantics of the common C idiom x<y?x:y but not
16079 // x<=y?x:y, because of how they handle negative zero (which can be
16080 // ignored in unsafe-math mode).
16081 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
16082 VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
16083 (Subtarget->hasSSE2() ||
16084 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
16085 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16087 unsigned Opcode = 0;
16088 // Check for x CC y ? x : y.
16089 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
16090 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
16094 // Converting this to a min would handle NaNs incorrectly, and swapping
16095 // the operands would cause it to handle comparisons between positive
16096 // and negative zero incorrectly.
16097 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
16098 if (!DAG.getTarget().Options.UnsafeFPMath &&
16099 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
16101 std::swap(LHS, RHS);
16103 Opcode = X86ISD::FMIN;
16106 // Converting this to a min would handle comparisons between positive
16107 // and negative zero incorrectly.
16108 if (!DAG.getTarget().Options.UnsafeFPMath &&
16109 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
16111 Opcode = X86ISD::FMIN;
16114 // Converting this to a min would handle both negative zeros and NaNs
16115 // incorrectly, but we can swap the operands to fix both.
16116 std::swap(LHS, RHS);
16120 Opcode = X86ISD::FMIN;
16124 // Converting this to a max would handle comparisons between positive
16125 // and negative zero incorrectly.
16126 if (!DAG.getTarget().Options.UnsafeFPMath &&
16127 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
16129 Opcode = X86ISD::FMAX;
16132 // Converting this to a max would handle NaNs incorrectly, and swapping
16133 // the operands would cause it to handle comparisons between positive
16134 // and negative zero incorrectly.
16135 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
16136 if (!DAG.getTarget().Options.UnsafeFPMath &&
16137 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
16139 std::swap(LHS, RHS);
16141 Opcode = X86ISD::FMAX;
16144 // Converting this to a max would handle both negative zeros and NaNs
16145 // incorrectly, but we can swap the operands to fix both.
16146 std::swap(LHS, RHS);
16150 Opcode = X86ISD::FMAX;
16153 // Check for x CC y ? y : x -- a min/max with reversed arms.
16154 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
16155 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
16159 // Converting this to a min would handle comparisons between positive
16160 // and negative zero incorrectly, and swapping the operands would
16161 // cause it to handle NaNs incorrectly.
16162 if (!DAG.getTarget().Options.UnsafeFPMath &&
16163 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
16164 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
16166 std::swap(LHS, RHS);
16168 Opcode = X86ISD::FMIN;
16171 // Converting this to a min would handle NaNs incorrectly.
16172 if (!DAG.getTarget().Options.UnsafeFPMath &&
16173 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
16175 Opcode = X86ISD::FMIN;
16178 // Converting this to a min would handle both negative zeros and NaNs
16179 // incorrectly, but we can swap the operands to fix both.
16180 std::swap(LHS, RHS);
16184 Opcode = X86ISD::FMIN;
16188 // Converting this to a max would handle NaNs incorrectly.
16189 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
16191 Opcode = X86ISD::FMAX;
16194 // Converting this to a max would handle comparisons between positive
16195 // and negative zero incorrectly, and swapping the operands would
16196 // cause it to handle NaNs incorrectly.
16197 if (!DAG.getTarget().Options.UnsafeFPMath &&
16198 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
16199 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
16201 std::swap(LHS, RHS);
16203 Opcode = X86ISD::FMAX;
16206 // Converting this to a max would handle both negative zeros and NaNs
16207 // incorrectly, but we can swap the operands to fix both.
16208 std::swap(LHS, RHS);
16212 Opcode = X86ISD::FMAX;
16218 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
16221 // If this is a select between two integer constants, try to do some
16223 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
16224 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
16225 // Don't do this for crazy integer types.
16226 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
16227 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
16228 // so that TrueC (the true value) is larger than FalseC.
16229 bool NeedsCondInvert = false;
16231 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
16232 // Efficiently invertible.
16233 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
16234 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
16235 isa<ConstantSDNode>(Cond.getOperand(1))))) {
16236 NeedsCondInvert = true;
16237 std::swap(TrueC, FalseC);
16240 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
16241 if (FalseC->getAPIntValue() == 0 &&
16242 TrueC->getAPIntValue().isPowerOf2()) {
16243 if (NeedsCondInvert) // Invert the condition if needed.
16244 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
16245 DAG.getConstant(1, Cond.getValueType()));
16247 // Zero extend the condition if needed.
16248 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
16250 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
16251 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
16252 DAG.getConstant(ShAmt, MVT::i8));
16255 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
16256 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
16257 if (NeedsCondInvert) // Invert the condition if needed.
16258 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
16259 DAG.getConstant(1, Cond.getValueType()));
16261 // Zero extend the condition if needed.
16262 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
16263 FalseC->getValueType(0), Cond);
16264 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16265 SDValue(FalseC, 0));
16268 // Optimize cases that will turn into an LEA instruction. This requires
16269 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
16270 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
16271 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
16272 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
16274 bool isFastMultiplier = false;
16276 switch ((unsigned char)Diff) {
16278 case 1: // result = add base, cond
16279 case 2: // result = lea base( , cond*2)
16280 case 3: // result = lea base(cond, cond*2)
16281 case 4: // result = lea base( , cond*4)
16282 case 5: // result = lea base(cond, cond*4)
16283 case 8: // result = lea base( , cond*8)
16284 case 9: // result = lea base(cond, cond*8)
16285 isFastMultiplier = true;
16290 if (isFastMultiplier) {
16291 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
16292 if (NeedsCondInvert) // Invert the condition if needed.
16293 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
16294 DAG.getConstant(1, Cond.getValueType()));
16296 // Zero extend the condition if needed.
16297 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
16299 // Scale the condition by the difference.
16301 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
16302 DAG.getConstant(Diff, Cond.getValueType()));
16304 // Add the base if non-zero.
16305 if (FalseC->getAPIntValue() != 0)
16306 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16307 SDValue(FalseC, 0));
16314 // Canonicalize max and min:
16315 // (x > y) ? x : y -> (x >= y) ? x : y
16316 // (x < y) ? x : y -> (x <= y) ? x : y
16317 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
16318 // the need for an extra compare
16319 // against zero. e.g.
16320 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
16322 // testl %edi, %edi
16324 // cmovgl %edi, %eax
16328 // cmovsl %eax, %edi
16329 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
16330 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
16331 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
16332 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16337 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
16338 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
16339 Cond.getOperand(0), Cond.getOperand(1), NewCC);
16340 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
16345 // Match VSELECTs into subs with unsigned saturation.
16346 if (!DCI.isBeforeLegalize() &&
16347 N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
16348 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
16349 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
16350 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
16351 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16353 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
16354 // left side invert the predicate to simplify logic below.
16356 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
16358 CC = ISD::getSetCCInverse(CC, true);
16359 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
16363 if (Other.getNode() && Other->getNumOperands() == 2 &&
16364 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
16365 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
16366 SDValue CondRHS = Cond->getOperand(1);
16368 // Look for a general sub with unsigned saturation first.
16369 // x >= y ? x-y : 0 --> subus x, y
16370 // x > y ? x-y : 0 --> subus x, y
16371 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
16372 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
16373 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
16375 // If the RHS is a constant we have to reverse the const canonicalization.
16376 // x > C-1 ? x+-C : 0 --> subus x, C
16377 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
16378 isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
16379 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
16380 if (CondRHS.getConstantOperandVal(0) == -A-1)
16381 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
16382 DAG.getConstant(-A, VT));
16385 // Another special case: If C was a sign bit, the sub has been
16386 // canonicalized into a xor.
16387 // FIXME: Would it be better to use ComputeMaskedBits to determine whether
16388 // it's safe to decanonicalize the xor?
16389 // x s< 0 ? x^C : 0 --> subus x, C
16390 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
16391 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
16392 isSplatVector(OpRHS.getNode())) {
16393 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
16395 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
16400 // Try to match a min/max vector operation.
16401 if (!DCI.isBeforeLegalize() &&
16402 N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC)
16403 if (unsigned Op = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget))
16404 return DAG.getNode(Op, DL, N->getValueType(0), LHS, RHS);
16406 // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
16407 if (!DCI.isBeforeLegalize() && N->getOpcode() == ISD::VSELECT &&
16408 Cond.getOpcode() == ISD::SETCC) {
16410 assert(Cond.getValueType().isVector() &&
16411 "vector select expects a vector selector!");
16413 EVT IntVT = Cond.getValueType();
16414 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
16415 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
16417 if (!TValIsAllOnes && !FValIsAllZeros) {
16418 // Try invert the condition if true value is not all 1s and false value
16420 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
16421 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
16423 if (TValIsAllZeros || FValIsAllOnes) {
16424 SDValue CC = Cond.getOperand(2);
16425 ISD::CondCode NewCC =
16426 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
16427 Cond.getOperand(0).getValueType().isInteger());
16428 Cond = DAG.getSetCC(DL, IntVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
16429 std::swap(LHS, RHS);
16430 TValIsAllOnes = FValIsAllOnes;
16431 FValIsAllZeros = TValIsAllZeros;
16435 if (TValIsAllOnes || FValIsAllZeros) {
16438 if (TValIsAllOnes && FValIsAllZeros)
16440 else if (TValIsAllOnes)
16441 Ret = DAG.getNode(ISD::OR, DL, IntVT, Cond,
16442 DAG.getNode(ISD::BITCAST, DL, IntVT, RHS));
16443 else if (FValIsAllZeros)
16444 Ret = DAG.getNode(ISD::AND, DL, IntVT, Cond,
16445 DAG.getNode(ISD::BITCAST, DL, IntVT, LHS));
16447 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
16451 // If we know that this node is legal then we know that it is going to be
16452 // matched by one of the SSE/AVX BLEND instructions. These instructions only
16453 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
16454 // to simplify previous instructions.
16455 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16456 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
16457 !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
16458 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
16460 // Don't optimize vector selects that map to mask-registers.
16464 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
16465 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
16467 APInt KnownZero, KnownOne;
16468 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
16469 DCI.isBeforeLegalizeOps());
16470 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
16471 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
16472 DCI.CommitTargetLoweringOpt(TLO);
16478 // Check whether a boolean test is testing a boolean value generated by
16479 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
16482 // Simplify the following patterns:
16483 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
16484 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
16485 // to (Op EFLAGS Cond)
16487 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
16488 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
16489 // to (Op EFLAGS !Cond)
16491 // where Op could be BRCOND or CMOV.
16493 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
16494 // Quit if not CMP and SUB with its value result used.
16495 if (Cmp.getOpcode() != X86ISD::CMP &&
16496 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
16499 // Quit if not used as a boolean value.
16500 if (CC != X86::COND_E && CC != X86::COND_NE)
16503 // Check CMP operands. One of them should be 0 or 1 and the other should be
16504 // an SetCC or extended from it.
16505 SDValue Op1 = Cmp.getOperand(0);
16506 SDValue Op2 = Cmp.getOperand(1);
16509 const ConstantSDNode* C = 0;
16510 bool needOppositeCond = (CC == X86::COND_E);
16511 bool checkAgainstTrue = false; // Is it a comparison against 1?
16513 if ((C = dyn_cast<ConstantSDNode>(Op1)))
16515 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
16517 else // Quit if all operands are not constants.
16520 if (C->getZExtValue() == 1) {
16521 needOppositeCond = !needOppositeCond;
16522 checkAgainstTrue = true;
16523 } else if (C->getZExtValue() != 0)
16524 // Quit if the constant is neither 0 or 1.
16527 bool truncatedToBoolWithAnd = false;
16528 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
16529 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
16530 SetCC.getOpcode() == ISD::TRUNCATE ||
16531 SetCC.getOpcode() == ISD::AND) {
16532 if (SetCC.getOpcode() == ISD::AND) {
16534 ConstantSDNode *CS;
16535 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
16536 CS->getZExtValue() == 1)
16538 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
16539 CS->getZExtValue() == 1)
16543 SetCC = SetCC.getOperand(OpIdx);
16544 truncatedToBoolWithAnd = true;
16546 SetCC = SetCC.getOperand(0);
16549 switch (SetCC.getOpcode()) {
16550 case X86ISD::SETCC_CARRY:
16551 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
16552 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
16553 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
16554 // truncated to i1 using 'and'.
16555 if (checkAgainstTrue && !truncatedToBoolWithAnd)
16557 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
16558 "Invalid use of SETCC_CARRY!");
16560 case X86ISD::SETCC:
16561 // Set the condition code or opposite one if necessary.
16562 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
16563 if (needOppositeCond)
16564 CC = X86::GetOppositeBranchCondition(CC);
16565 return SetCC.getOperand(1);
16566 case X86ISD::CMOV: {
16567 // Check whether false/true value has canonical one, i.e. 0 or 1.
16568 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
16569 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
16570 // Quit if true value is not a constant.
16573 // Quit if false value is not a constant.
16575 SDValue Op = SetCC.getOperand(0);
16576 // Skip 'zext' or 'trunc' node.
16577 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
16578 Op.getOpcode() == ISD::TRUNCATE)
16579 Op = Op.getOperand(0);
16580 // A special case for rdrand/rdseed, where 0 is set if false cond is
16582 if ((Op.getOpcode() != X86ISD::RDRAND &&
16583 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
16586 // Quit if false value is not the constant 0 or 1.
16587 bool FValIsFalse = true;
16588 if (FVal && FVal->getZExtValue() != 0) {
16589 if (FVal->getZExtValue() != 1)
16591 // If FVal is 1, opposite cond is needed.
16592 needOppositeCond = !needOppositeCond;
16593 FValIsFalse = false;
16595 // Quit if TVal is not the constant opposite of FVal.
16596 if (FValIsFalse && TVal->getZExtValue() != 1)
16598 if (!FValIsFalse && TVal->getZExtValue() != 0)
16600 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
16601 if (needOppositeCond)
16602 CC = X86::GetOppositeBranchCondition(CC);
16603 return SetCC.getOperand(3);
16610 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
16611 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
16612 TargetLowering::DAGCombinerInfo &DCI,
16613 const X86Subtarget *Subtarget) {
16616 // If the flag operand isn't dead, don't touch this CMOV.
16617 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
16620 SDValue FalseOp = N->getOperand(0);
16621 SDValue TrueOp = N->getOperand(1);
16622 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
16623 SDValue Cond = N->getOperand(3);
16625 if (CC == X86::COND_E || CC == X86::COND_NE) {
16626 switch (Cond.getOpcode()) {
16630 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
16631 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
16632 return (CC == X86::COND_E) ? FalseOp : TrueOp;
16638 Flags = checkBoolTestSetCCCombine(Cond, CC);
16639 if (Flags.getNode() &&
16640 // Extra check as FCMOV only supports a subset of X86 cond.
16641 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
16642 SDValue Ops[] = { FalseOp, TrueOp,
16643 DAG.getConstant(CC, MVT::i8), Flags };
16644 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
16645 Ops, array_lengthof(Ops));
16648 // If this is a select between two integer constants, try to do some
16649 // optimizations. Note that the operands are ordered the opposite of SELECT
16651 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
16652 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
16653 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
16654 // larger than FalseC (the false value).
16655 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
16656 CC = X86::GetOppositeBranchCondition(CC);
16657 std::swap(TrueC, FalseC);
16658 std::swap(TrueOp, FalseOp);
16661 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
16662 // This is efficient for any integer data type (including i8/i16) and
16664 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
16665 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16666 DAG.getConstant(CC, MVT::i8), Cond);
16668 // Zero extend the condition if needed.
16669 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
16671 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
16672 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
16673 DAG.getConstant(ShAmt, MVT::i8));
16674 if (N->getNumValues() == 2) // Dead flag value?
16675 return DCI.CombineTo(N, Cond, SDValue());
16679 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
16680 // for any integer data type, including i8/i16.
16681 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
16682 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16683 DAG.getConstant(CC, MVT::i8), Cond);
16685 // Zero extend the condition if needed.
16686 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
16687 FalseC->getValueType(0), Cond);
16688 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16689 SDValue(FalseC, 0));
16691 if (N->getNumValues() == 2) // Dead flag value?
16692 return DCI.CombineTo(N, Cond, SDValue());
16696 // Optimize cases that will turn into an LEA instruction. This requires
16697 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
16698 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
16699 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
16700 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
16702 bool isFastMultiplier = false;
16704 switch ((unsigned char)Diff) {
16706 case 1: // result = add base, cond
16707 case 2: // result = lea base( , cond*2)
16708 case 3: // result = lea base(cond, cond*2)
16709 case 4: // result = lea base( , cond*4)
16710 case 5: // result = lea base(cond, cond*4)
16711 case 8: // result = lea base( , cond*8)
16712 case 9: // result = lea base(cond, cond*8)
16713 isFastMultiplier = true;
16718 if (isFastMultiplier) {
16719 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
16720 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16721 DAG.getConstant(CC, MVT::i8), Cond);
16722 // Zero extend the condition if needed.
16723 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
16725 // Scale the condition by the difference.
16727 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
16728 DAG.getConstant(Diff, Cond.getValueType()));
16730 // Add the base if non-zero.
16731 if (FalseC->getAPIntValue() != 0)
16732 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16733 SDValue(FalseC, 0));
16734 if (N->getNumValues() == 2) // Dead flag value?
16735 return DCI.CombineTo(N, Cond, SDValue());
16742 // Handle these cases:
16743 // (select (x != c), e, c) -> select (x != c), e, x),
16744 // (select (x == c), c, e) -> select (x == c), x, e)
16745 // where the c is an integer constant, and the "select" is the combination
16746 // of CMOV and CMP.
16748 // The rationale for this change is that the conditional-move from a constant
16749 // needs two instructions, however, conditional-move from a register needs
16750 // only one instruction.
16752 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
16753 // some instruction-combining opportunities. This opt needs to be
16754 // postponed as late as possible.
16756 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
16757 // the DCI.xxxx conditions are provided to postpone the optimization as
16758 // late as possible.
16760 ConstantSDNode *CmpAgainst = 0;
16761 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
16762 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
16763 !isa<ConstantSDNode>(Cond.getOperand(0))) {
16765 if (CC == X86::COND_NE &&
16766 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
16767 CC = X86::GetOppositeBranchCondition(CC);
16768 std::swap(TrueOp, FalseOp);
16771 if (CC == X86::COND_E &&
16772 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
16773 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
16774 DAG.getConstant(CC, MVT::i8), Cond };
16775 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
16776 array_lengthof(Ops));
16784 /// PerformMulCombine - Optimize a single multiply with constant into two
16785 /// in order to implement it with two cheaper instructions, e.g.
16786 /// LEA + SHL, LEA + LEA.
16787 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
16788 TargetLowering::DAGCombinerInfo &DCI) {
16789 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
16792 EVT VT = N->getValueType(0);
16793 if (VT != MVT::i64)
16796 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
16799 uint64_t MulAmt = C->getZExtValue();
16800 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
16803 uint64_t MulAmt1 = 0;
16804 uint64_t MulAmt2 = 0;
16805 if ((MulAmt % 9) == 0) {
16807 MulAmt2 = MulAmt / 9;
16808 } else if ((MulAmt % 5) == 0) {
16810 MulAmt2 = MulAmt / 5;
16811 } else if ((MulAmt % 3) == 0) {
16813 MulAmt2 = MulAmt / 3;
16816 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
16819 if (isPowerOf2_64(MulAmt2) &&
16820 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
16821 // If second multiplifer is pow2, issue it first. We want the multiply by
16822 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
16824 std::swap(MulAmt1, MulAmt2);
16827 if (isPowerOf2_64(MulAmt1))
16828 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16829 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
16831 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
16832 DAG.getConstant(MulAmt1, VT));
16834 if (isPowerOf2_64(MulAmt2))
16835 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
16836 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
16838 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
16839 DAG.getConstant(MulAmt2, VT));
16841 // Do not add new nodes to DAG combiner worklist.
16842 DCI.CombineTo(N, NewMul, false);
16847 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
16848 SDValue N0 = N->getOperand(0);
16849 SDValue N1 = N->getOperand(1);
16850 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
16851 EVT VT = N0.getValueType();
16853 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
16854 // since the result of setcc_c is all zero's or all ones.
16855 if (VT.isInteger() && !VT.isVector() &&
16856 N1C && N0.getOpcode() == ISD::AND &&
16857 N0.getOperand(1).getOpcode() == ISD::Constant) {
16858 SDValue N00 = N0.getOperand(0);
16859 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
16860 ((N00.getOpcode() == ISD::ANY_EXTEND ||
16861 N00.getOpcode() == ISD::ZERO_EXTEND) &&
16862 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
16863 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
16864 APInt ShAmt = N1C->getAPIntValue();
16865 Mask = Mask.shl(ShAmt);
16867 return DAG.getNode(ISD::AND, SDLoc(N), VT,
16868 N00, DAG.getConstant(Mask, VT));
16872 // Hardware support for vector shifts is sparse which makes us scalarize the
16873 // vector operations in many cases. Also, on sandybridge ADD is faster than
16875 // (shl V, 1) -> add V,V
16876 if (isSplatVector(N1.getNode())) {
16877 assert(N0.getValueType().isVector() && "Invalid vector shift type");
16878 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
16879 // We shift all of the values by one. In many cases we do not have
16880 // hardware support for this operation. This is better expressed as an ADD
16882 if (N1C && (1 == N1C->getZExtValue())) {
16883 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
16890 /// \brief Returns a vector of 0s if the node in input is a vector logical
16891 /// shift by a constant amount which is known to be bigger than or equal
16892 /// to the vector element size in bits.
16893 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
16894 const X86Subtarget *Subtarget) {
16895 EVT VT = N->getValueType(0);
16897 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
16898 (!Subtarget->hasInt256() ||
16899 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
16902 SDValue Amt = N->getOperand(1);
16904 if (isSplatVector(Amt.getNode())) {
16905 SDValue SclrAmt = Amt->getOperand(0);
16906 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
16907 APInt ShiftAmt = C->getAPIntValue();
16908 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
16910 // SSE2/AVX2 logical shifts always return a vector of 0s
16911 // if the shift amount is bigger than or equal to
16912 // the element size. The constant shift amount will be
16913 // encoded as a 8-bit immediate.
16914 if (ShiftAmt.trunc(8).uge(MaxAmount))
16915 return getZeroVector(VT, Subtarget, DAG, DL);
16922 /// PerformShiftCombine - Combine shifts.
16923 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
16924 TargetLowering::DAGCombinerInfo &DCI,
16925 const X86Subtarget *Subtarget) {
16926 if (N->getOpcode() == ISD::SHL) {
16927 SDValue V = PerformSHLCombine(N, DAG);
16928 if (V.getNode()) return V;
16931 if (N->getOpcode() != ISD::SRA) {
16932 // Try to fold this logical shift into a zero vector.
16933 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
16934 if (V.getNode()) return V;
16940 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
16941 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
16942 // and friends. Likewise for OR -> CMPNEQSS.
16943 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
16944 TargetLowering::DAGCombinerInfo &DCI,
16945 const X86Subtarget *Subtarget) {
16948 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
16949 // we're requiring SSE2 for both.
16950 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
16951 SDValue N0 = N->getOperand(0);
16952 SDValue N1 = N->getOperand(1);
16953 SDValue CMP0 = N0->getOperand(1);
16954 SDValue CMP1 = N1->getOperand(1);
16957 // The SETCCs should both refer to the same CMP.
16958 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
16961 SDValue CMP00 = CMP0->getOperand(0);
16962 SDValue CMP01 = CMP0->getOperand(1);
16963 EVT VT = CMP00.getValueType();
16965 if (VT == MVT::f32 || VT == MVT::f64) {
16966 bool ExpectingFlags = false;
16967 // Check for any users that want flags:
16968 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
16969 !ExpectingFlags && UI != UE; ++UI)
16970 switch (UI->getOpcode()) {
16975 ExpectingFlags = true;
16977 case ISD::CopyToReg:
16978 case ISD::SIGN_EXTEND:
16979 case ISD::ZERO_EXTEND:
16980 case ISD::ANY_EXTEND:
16984 if (!ExpectingFlags) {
16985 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
16986 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
16988 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
16989 X86::CondCode tmp = cc0;
16994 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
16995 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
16996 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
16997 X86ISD::NodeType NTOperator = is64BitFP ?
16998 X86ISD::FSETCCsd : X86ISD::FSETCCss;
16999 // FIXME: need symbolic constants for these magic numbers.
17000 // See X86ATTInstPrinter.cpp:printSSECC().
17001 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
17002 SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
17003 DAG.getConstant(x86cc, MVT::i8));
17004 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
17006 SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
17007 DAG.getConstant(1, MVT::i32));
17008 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
17009 return OneBitOfTruth;
17017 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
17018 /// so it can be folded inside ANDNP.
17019 static bool CanFoldXORWithAllOnes(const SDNode *N) {
17020 EVT VT = N->getValueType(0);
17022 // Match direct AllOnes for 128 and 256-bit vectors
17023 if (ISD::isBuildVectorAllOnes(N))
17026 // Look through a bit convert.
17027 if (N->getOpcode() == ISD::BITCAST)
17028 N = N->getOperand(0).getNode();
17030 // Sometimes the operand may come from a insert_subvector building a 256-bit
17032 if (VT.is256BitVector() &&
17033 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
17034 SDValue V1 = N->getOperand(0);
17035 SDValue V2 = N->getOperand(1);
17037 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
17038 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
17039 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
17040 ISD::isBuildVectorAllOnes(V2.getNode()))
17047 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
17048 // register. In most cases we actually compare or select YMM-sized registers
17049 // and mixing the two types creates horrible code. This method optimizes
17050 // some of the transition sequences.
17051 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
17052 TargetLowering::DAGCombinerInfo &DCI,
17053 const X86Subtarget *Subtarget) {
17054 EVT VT = N->getValueType(0);
17055 if (!VT.is256BitVector())
17058 assert((N->getOpcode() == ISD::ANY_EXTEND ||
17059 N->getOpcode() == ISD::ZERO_EXTEND ||
17060 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
17062 SDValue Narrow = N->getOperand(0);
17063 EVT NarrowVT = Narrow->getValueType(0);
17064 if (!NarrowVT.is128BitVector())
17067 if (Narrow->getOpcode() != ISD::XOR &&
17068 Narrow->getOpcode() != ISD::AND &&
17069 Narrow->getOpcode() != ISD::OR)
17072 SDValue N0 = Narrow->getOperand(0);
17073 SDValue N1 = Narrow->getOperand(1);
17076 // The Left side has to be a trunc.
17077 if (N0.getOpcode() != ISD::TRUNCATE)
17080 // The type of the truncated inputs.
17081 EVT WideVT = N0->getOperand(0)->getValueType(0);
17085 // The right side has to be a 'trunc' or a constant vector.
17086 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
17087 bool RHSConst = (isSplatVector(N1.getNode()) &&
17088 isa<ConstantSDNode>(N1->getOperand(0)));
17089 if (!RHSTrunc && !RHSConst)
17092 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17094 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
17097 // Set N0 and N1 to hold the inputs to the new wide operation.
17098 N0 = N0->getOperand(0);
17100 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
17101 N1->getOperand(0));
17102 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
17103 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
17104 } else if (RHSTrunc) {
17105 N1 = N1->getOperand(0);
17108 // Generate the wide operation.
17109 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
17110 unsigned Opcode = N->getOpcode();
17112 case ISD::ANY_EXTEND:
17114 case ISD::ZERO_EXTEND: {
17115 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
17116 APInt Mask = APInt::getAllOnesValue(InBits);
17117 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
17118 return DAG.getNode(ISD::AND, DL, VT,
17119 Op, DAG.getConstant(Mask, VT));
17121 case ISD::SIGN_EXTEND:
17122 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
17123 Op, DAG.getValueType(NarrowVT));
17125 llvm_unreachable("Unexpected opcode");
17129 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
17130 TargetLowering::DAGCombinerInfo &DCI,
17131 const X86Subtarget *Subtarget) {
17132 EVT VT = N->getValueType(0);
17133 if (DCI.isBeforeLegalizeOps())
17136 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
17140 // Create BLSI, and BLSR instructions
17141 // BLSI is X & (-X)
17142 // BLSR is X & (X-1)
17143 if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
17144 SDValue N0 = N->getOperand(0);
17145 SDValue N1 = N->getOperand(1);
17148 // Check LHS for neg
17149 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
17150 isZero(N0.getOperand(0)))
17151 return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
17153 // Check RHS for neg
17154 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
17155 isZero(N1.getOperand(0)))
17156 return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
17158 // Check LHS for X-1
17159 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
17160 isAllOnes(N0.getOperand(1)))
17161 return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
17163 // Check RHS for X-1
17164 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
17165 isAllOnes(N1.getOperand(1)))
17166 return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
17171 // Want to form ANDNP nodes:
17172 // 1) In the hopes of then easily combining them with OR and AND nodes
17173 // to form PBLEND/PSIGN.
17174 // 2) To match ANDN packed intrinsics
17175 if (VT != MVT::v2i64 && VT != MVT::v4i64)
17178 SDValue N0 = N->getOperand(0);
17179 SDValue N1 = N->getOperand(1);
17182 // Check LHS for vnot
17183 if (N0.getOpcode() == ISD::XOR &&
17184 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
17185 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
17186 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
17188 // Check RHS for vnot
17189 if (N1.getOpcode() == ISD::XOR &&
17190 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
17191 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
17192 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
17197 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
17198 TargetLowering::DAGCombinerInfo &DCI,
17199 const X86Subtarget *Subtarget) {
17200 EVT VT = N->getValueType(0);
17201 if (DCI.isBeforeLegalizeOps())
17204 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
17208 SDValue N0 = N->getOperand(0);
17209 SDValue N1 = N->getOperand(1);
17211 // look for psign/blend
17212 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
17213 if (!Subtarget->hasSSSE3() ||
17214 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
17217 // Canonicalize pandn to RHS
17218 if (N0.getOpcode() == X86ISD::ANDNP)
17220 // or (and (m, y), (pandn m, x))
17221 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
17222 SDValue Mask = N1.getOperand(0);
17223 SDValue X = N1.getOperand(1);
17225 if (N0.getOperand(0) == Mask)
17226 Y = N0.getOperand(1);
17227 if (N0.getOperand(1) == Mask)
17228 Y = N0.getOperand(0);
17230 // Check to see if the mask appeared in both the AND and ANDNP and
17234 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
17235 // Look through mask bitcast.
17236 if (Mask.getOpcode() == ISD::BITCAST)
17237 Mask = Mask.getOperand(0);
17238 if (X.getOpcode() == ISD::BITCAST)
17239 X = X.getOperand(0);
17240 if (Y.getOpcode() == ISD::BITCAST)
17241 Y = Y.getOperand(0);
17243 EVT MaskVT = Mask.getValueType();
17245 // Validate that the Mask operand is a vector sra node.
17246 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
17247 // there is no psrai.b
17248 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
17249 unsigned SraAmt = ~0;
17250 if (Mask.getOpcode() == ISD::SRA) {
17251 SDValue Amt = Mask.getOperand(1);
17252 if (isSplatVector(Amt.getNode())) {
17253 SDValue SclrAmt = Amt->getOperand(0);
17254 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
17255 SraAmt = C->getZExtValue();
17257 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
17258 SDValue SraC = Mask.getOperand(1);
17259 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
17261 if ((SraAmt + 1) != EltBits)
17266 // Now we know we at least have a plendvb with the mask val. See if
17267 // we can form a psignb/w/d.
17268 // psign = x.type == y.type == mask.type && y = sub(0, x);
17269 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
17270 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
17271 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
17272 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
17273 "Unsupported VT for PSIGN");
17274 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
17275 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
17277 // PBLENDVB only available on SSE 4.1
17278 if (!Subtarget->hasSSE41())
17281 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
17283 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
17284 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
17285 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
17286 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
17287 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
17291 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
17294 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
17295 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
17297 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
17299 if (!N0.hasOneUse() || !N1.hasOneUse())
17302 SDValue ShAmt0 = N0.getOperand(1);
17303 if (ShAmt0.getValueType() != MVT::i8)
17305 SDValue ShAmt1 = N1.getOperand(1);
17306 if (ShAmt1.getValueType() != MVT::i8)
17308 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
17309 ShAmt0 = ShAmt0.getOperand(0);
17310 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
17311 ShAmt1 = ShAmt1.getOperand(0);
17314 unsigned Opc = X86ISD::SHLD;
17315 SDValue Op0 = N0.getOperand(0);
17316 SDValue Op1 = N1.getOperand(0);
17317 if (ShAmt0.getOpcode() == ISD::SUB) {
17318 Opc = X86ISD::SHRD;
17319 std::swap(Op0, Op1);
17320 std::swap(ShAmt0, ShAmt1);
17323 unsigned Bits = VT.getSizeInBits();
17324 if (ShAmt1.getOpcode() == ISD::SUB) {
17325 SDValue Sum = ShAmt1.getOperand(0);
17326 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
17327 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
17328 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
17329 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
17330 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
17331 return DAG.getNode(Opc, DL, VT,
17333 DAG.getNode(ISD::TRUNCATE, DL,
17336 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
17337 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
17339 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
17340 return DAG.getNode(Opc, DL, VT,
17341 N0.getOperand(0), N1.getOperand(0),
17342 DAG.getNode(ISD::TRUNCATE, DL,
17349 // Generate NEG and CMOV for integer abs.
17350 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
17351 EVT VT = N->getValueType(0);
17353 // Since X86 does not have CMOV for 8-bit integer, we don't convert
17354 // 8-bit integer abs to NEG and CMOV.
17355 if (VT.isInteger() && VT.getSizeInBits() == 8)
17358 SDValue N0 = N->getOperand(0);
17359 SDValue N1 = N->getOperand(1);
17362 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
17363 // and change it to SUB and CMOV.
17364 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
17365 N0.getOpcode() == ISD::ADD &&
17366 N0.getOperand(1) == N1 &&
17367 N1.getOpcode() == ISD::SRA &&
17368 N1.getOperand(0) == N0.getOperand(0))
17369 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
17370 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
17371 // Generate SUB & CMOV.
17372 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
17373 DAG.getConstant(0, VT), N0.getOperand(0));
17375 SDValue Ops[] = { N0.getOperand(0), Neg,
17376 DAG.getConstant(X86::COND_GE, MVT::i8),
17377 SDValue(Neg.getNode(), 1) };
17378 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
17379 Ops, array_lengthof(Ops));
17384 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
17385 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
17386 TargetLowering::DAGCombinerInfo &DCI,
17387 const X86Subtarget *Subtarget) {
17388 EVT VT = N->getValueType(0);
17389 if (DCI.isBeforeLegalizeOps())
17392 if (Subtarget->hasCMov()) {
17393 SDValue RV = performIntegerAbsCombine(N, DAG);
17398 // Try forming BMI if it is available.
17399 if (!Subtarget->hasBMI())
17402 if (VT != MVT::i32 && VT != MVT::i64)
17405 assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
17407 // Create BLSMSK instructions by finding X ^ (X-1)
17408 SDValue N0 = N->getOperand(0);
17409 SDValue N1 = N->getOperand(1);
17412 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
17413 isAllOnes(N0.getOperand(1)))
17414 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
17416 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
17417 isAllOnes(N1.getOperand(1)))
17418 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
17423 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
17424 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
17425 TargetLowering::DAGCombinerInfo &DCI,
17426 const X86Subtarget *Subtarget) {
17427 LoadSDNode *Ld = cast<LoadSDNode>(N);
17428 EVT RegVT = Ld->getValueType(0);
17429 EVT MemVT = Ld->getMemoryVT();
17431 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17432 unsigned RegSz = RegVT.getSizeInBits();
17434 // On Sandybridge unaligned 256bit loads are inefficient.
17435 ISD::LoadExtType Ext = Ld->getExtensionType();
17436 unsigned Alignment = Ld->getAlignment();
17437 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
17438 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
17439 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
17440 unsigned NumElems = RegVT.getVectorNumElements();
17444 SDValue Ptr = Ld->getBasePtr();
17445 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
17447 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
17449 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
17450 Ld->getPointerInfo(), Ld->isVolatile(),
17451 Ld->isNonTemporal(), Ld->isInvariant(),
17453 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
17454 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
17455 Ld->getPointerInfo(), Ld->isVolatile(),
17456 Ld->isNonTemporal(), Ld->isInvariant(),
17457 std::min(16U, Alignment));
17458 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17460 Load2.getValue(1));
17462 SDValue NewVec = DAG.getUNDEF(RegVT);
17463 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
17464 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
17465 return DCI.CombineTo(N, NewVec, TF, true);
17468 // If this is a vector EXT Load then attempt to optimize it using a
17469 // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
17470 // expansion is still better than scalar code.
17471 // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
17472 // emit a shuffle and a arithmetic shift.
17473 // TODO: It is possible to support ZExt by zeroing the undef values
17474 // during the shuffle phase or after the shuffle.
17475 if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
17476 (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
17477 assert(MemVT != RegVT && "Cannot extend to the same type");
17478 assert(MemVT.isVector() && "Must load a vector from memory");
17480 unsigned NumElems = RegVT.getVectorNumElements();
17481 unsigned MemSz = MemVT.getSizeInBits();
17482 assert(RegSz > MemSz && "Register size must be greater than the mem size");
17484 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
17487 // All sizes must be a power of two.
17488 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
17491 // Attempt to load the original value using scalar loads.
17492 // Find the largest scalar type that divides the total loaded size.
17493 MVT SclrLoadTy = MVT::i8;
17494 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
17495 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
17496 MVT Tp = (MVT::SimpleValueType)tp;
17497 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
17502 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
17503 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
17505 SclrLoadTy = MVT::f64;
17507 // Calculate the number of scalar loads that we need to perform
17508 // in order to load our vector from memory.
17509 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
17510 if (Ext == ISD::SEXTLOAD && NumLoads > 1)
17513 unsigned loadRegZize = RegSz;
17514 if (Ext == ISD::SEXTLOAD && RegSz == 256)
17517 // Represent our vector as a sequence of elements which are the
17518 // largest scalar that we can load.
17519 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
17520 loadRegZize/SclrLoadTy.getSizeInBits());
17522 // Represent the data using the same element type that is stored in
17523 // memory. In practice, we ''widen'' MemVT.
17525 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
17526 loadRegZize/MemVT.getScalarType().getSizeInBits());
17528 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
17529 "Invalid vector type");
17531 // We can't shuffle using an illegal type.
17532 if (!TLI.isTypeLegal(WideVecVT))
17535 SmallVector<SDValue, 8> Chains;
17536 SDValue Ptr = Ld->getBasePtr();
17537 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
17538 TLI.getPointerTy());
17539 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
17541 for (unsigned i = 0; i < NumLoads; ++i) {
17542 // Perform a single load.
17543 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
17544 Ptr, Ld->getPointerInfo(),
17545 Ld->isVolatile(), Ld->isNonTemporal(),
17546 Ld->isInvariant(), Ld->getAlignment());
17547 Chains.push_back(ScalarLoad.getValue(1));
17548 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
17549 // another round of DAGCombining.
17551 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
17553 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
17554 ScalarLoad, DAG.getIntPtrConstant(i));
17556 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
17559 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
17562 // Bitcast the loaded value to a vector of the original element type, in
17563 // the size of the target vector type.
17564 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
17565 unsigned SizeRatio = RegSz/MemSz;
17567 if (Ext == ISD::SEXTLOAD) {
17568 // If we have SSE4.1 we can directly emit a VSEXT node.
17569 if (Subtarget->hasSSE41()) {
17570 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
17571 return DCI.CombineTo(N, Sext, TF, true);
17574 // Otherwise we'll shuffle the small elements in the high bits of the
17575 // larger type and perform an arithmetic shift. If the shift is not legal
17576 // it's better to scalarize.
17577 if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
17580 // Redistribute the loaded elements into the different locations.
17581 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
17582 for (unsigned i = 0; i != NumElems; ++i)
17583 ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
17585 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
17586 DAG.getUNDEF(WideVecVT),
17589 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
17591 // Build the arithmetic shift.
17592 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
17593 MemVT.getVectorElementType().getSizeInBits();
17594 Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
17595 DAG.getConstant(Amt, RegVT));
17597 return DCI.CombineTo(N, Shuff, TF, true);
17600 // Redistribute the loaded elements into the different locations.
17601 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
17602 for (unsigned i = 0; i != NumElems; ++i)
17603 ShuffleVec[i*SizeRatio] = i;
17605 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
17606 DAG.getUNDEF(WideVecVT),
17609 // Bitcast to the requested type.
17610 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
17611 // Replace the original load with the new sequence
17612 // and return the new chain.
17613 return DCI.CombineTo(N, Shuff, TF, true);
17619 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
17620 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
17621 const X86Subtarget *Subtarget) {
17622 StoreSDNode *St = cast<StoreSDNode>(N);
17623 EVT VT = St->getValue().getValueType();
17624 EVT StVT = St->getMemoryVT();
17626 SDValue StoredVal = St->getOperand(1);
17627 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17629 // If we are saving a concatenation of two XMM registers, perform two stores.
17630 // On Sandy Bridge, 256-bit memory operations are executed by two
17631 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
17632 // memory operation.
17633 unsigned Alignment = St->getAlignment();
17634 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
17635 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
17636 StVT == VT && !IsAligned) {
17637 unsigned NumElems = VT.getVectorNumElements();
17641 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
17642 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
17644 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
17645 SDValue Ptr0 = St->getBasePtr();
17646 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
17648 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
17649 St->getPointerInfo(), St->isVolatile(),
17650 St->isNonTemporal(), Alignment);
17651 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
17652 St->getPointerInfo(), St->isVolatile(),
17653 St->isNonTemporal(),
17654 std::min(16U, Alignment));
17655 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
17658 // Optimize trunc store (of multiple scalars) to shuffle and store.
17659 // First, pack all of the elements in one place. Next, store to memory
17660 // in fewer chunks.
17661 if (St->isTruncatingStore() && VT.isVector()) {
17662 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17663 unsigned NumElems = VT.getVectorNumElements();
17664 assert(StVT != VT && "Cannot truncate to the same type");
17665 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
17666 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
17668 // From, To sizes and ElemCount must be pow of two
17669 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
17670 // We are going to use the original vector elt for storing.
17671 // Accumulated smaller vector elements must be a multiple of the store size.
17672 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
17674 unsigned SizeRatio = FromSz / ToSz;
17676 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
17678 // Create a type on which we perform the shuffle
17679 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
17680 StVT.getScalarType(), NumElems*SizeRatio);
17682 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
17684 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
17685 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
17686 for (unsigned i = 0; i != NumElems; ++i)
17687 ShuffleVec[i] = i * SizeRatio;
17689 // Can't shuffle using an illegal type.
17690 if (!TLI.isTypeLegal(WideVecVT))
17693 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
17694 DAG.getUNDEF(WideVecVT),
17696 // At this point all of the data is stored at the bottom of the
17697 // register. We now need to save it to mem.
17699 // Find the largest store unit
17700 MVT StoreType = MVT::i8;
17701 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
17702 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
17703 MVT Tp = (MVT::SimpleValueType)tp;
17704 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
17708 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
17709 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
17710 (64 <= NumElems * ToSz))
17711 StoreType = MVT::f64;
17713 // Bitcast the original vector into a vector of store-size units
17714 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
17715 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
17716 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
17717 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
17718 SmallVector<SDValue, 8> Chains;
17719 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
17720 TLI.getPointerTy());
17721 SDValue Ptr = St->getBasePtr();
17723 // Perform one or more big stores into memory.
17724 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
17725 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
17726 StoreType, ShuffWide,
17727 DAG.getIntPtrConstant(i));
17728 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
17729 St->getPointerInfo(), St->isVolatile(),
17730 St->isNonTemporal(), St->getAlignment());
17731 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
17732 Chains.push_back(Ch);
17735 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
17739 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
17740 // the FP state in cases where an emms may be missing.
17741 // A preferable solution to the general problem is to figure out the right
17742 // places to insert EMMS. This qualifies as a quick hack.
17744 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
17745 if (VT.getSizeInBits() != 64)
17748 const Function *F = DAG.getMachineFunction().getFunction();
17749 bool NoImplicitFloatOps = F->getAttributes().
17750 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
17751 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
17752 && Subtarget->hasSSE2();
17753 if ((VT.isVector() ||
17754 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
17755 isa<LoadSDNode>(St->getValue()) &&
17756 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
17757 St->getChain().hasOneUse() && !St->isVolatile()) {
17758 SDNode* LdVal = St->getValue().getNode();
17759 LoadSDNode *Ld = 0;
17760 int TokenFactorIndex = -1;
17761 SmallVector<SDValue, 8> Ops;
17762 SDNode* ChainVal = St->getChain().getNode();
17763 // Must be a store of a load. We currently handle two cases: the load
17764 // is a direct child, and it's under an intervening TokenFactor. It is
17765 // possible to dig deeper under nested TokenFactors.
17766 if (ChainVal == LdVal)
17767 Ld = cast<LoadSDNode>(St->getChain());
17768 else if (St->getValue().hasOneUse() &&
17769 ChainVal->getOpcode() == ISD::TokenFactor) {
17770 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
17771 if (ChainVal->getOperand(i).getNode() == LdVal) {
17772 TokenFactorIndex = i;
17773 Ld = cast<LoadSDNode>(St->getValue());
17775 Ops.push_back(ChainVal->getOperand(i));
17779 if (!Ld || !ISD::isNormalLoad(Ld))
17782 // If this is not the MMX case, i.e. we are just turning i64 load/store
17783 // into f64 load/store, avoid the transformation if there are multiple
17784 // uses of the loaded value.
17785 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
17790 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
17791 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
17793 if (Subtarget->is64Bit() || F64IsLegal) {
17794 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
17795 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
17796 Ld->getPointerInfo(), Ld->isVolatile(),
17797 Ld->isNonTemporal(), Ld->isInvariant(),
17798 Ld->getAlignment());
17799 SDValue NewChain = NewLd.getValue(1);
17800 if (TokenFactorIndex != -1) {
17801 Ops.push_back(NewChain);
17802 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
17805 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
17806 St->getPointerInfo(),
17807 St->isVolatile(), St->isNonTemporal(),
17808 St->getAlignment());
17811 // Otherwise, lower to two pairs of 32-bit loads / stores.
17812 SDValue LoAddr = Ld->getBasePtr();
17813 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
17814 DAG.getConstant(4, MVT::i32));
17816 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
17817 Ld->getPointerInfo(),
17818 Ld->isVolatile(), Ld->isNonTemporal(),
17819 Ld->isInvariant(), Ld->getAlignment());
17820 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
17821 Ld->getPointerInfo().getWithOffset(4),
17822 Ld->isVolatile(), Ld->isNonTemporal(),
17824 MinAlign(Ld->getAlignment(), 4));
17826 SDValue NewChain = LoLd.getValue(1);
17827 if (TokenFactorIndex != -1) {
17828 Ops.push_back(LoLd);
17829 Ops.push_back(HiLd);
17830 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
17834 LoAddr = St->getBasePtr();
17835 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
17836 DAG.getConstant(4, MVT::i32));
17838 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
17839 St->getPointerInfo(),
17840 St->isVolatile(), St->isNonTemporal(),
17841 St->getAlignment());
17842 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
17843 St->getPointerInfo().getWithOffset(4),
17845 St->isNonTemporal(),
17846 MinAlign(St->getAlignment(), 4));
17847 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
17852 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
17853 /// and return the operands for the horizontal operation in LHS and RHS. A
17854 /// horizontal operation performs the binary operation on successive elements
17855 /// of its first operand, then on successive elements of its second operand,
17856 /// returning the resulting values in a vector. For example, if
17857 /// A = < float a0, float a1, float a2, float a3 >
17859 /// B = < float b0, float b1, float b2, float b3 >
17860 /// then the result of doing a horizontal operation on A and B is
17861 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
17862 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
17863 /// A horizontal-op B, for some already available A and B, and if so then LHS is
17864 /// set to A, RHS to B, and the routine returns 'true'.
17865 /// Note that the binary operation should have the property that if one of the
17866 /// operands is UNDEF then the result is UNDEF.
17867 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
17868 // Look for the following pattern: if
17869 // A = < float a0, float a1, float a2, float a3 >
17870 // B = < float b0, float b1, float b2, float b3 >
17872 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
17873 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
17874 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
17875 // which is A horizontal-op B.
17877 // At least one of the operands should be a vector shuffle.
17878 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
17879 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
17882 MVT VT = LHS.getValueType().getSimpleVT();
17884 assert((VT.is128BitVector() || VT.is256BitVector()) &&
17885 "Unsupported vector type for horizontal add/sub");
17887 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
17888 // operate independently on 128-bit lanes.
17889 unsigned NumElts = VT.getVectorNumElements();
17890 unsigned NumLanes = VT.getSizeInBits()/128;
17891 unsigned NumLaneElts = NumElts / NumLanes;
17892 assert((NumLaneElts % 2 == 0) &&
17893 "Vector type should have an even number of elements in each lane");
17894 unsigned HalfLaneElts = NumLaneElts/2;
17896 // View LHS in the form
17897 // LHS = VECTOR_SHUFFLE A, B, LMask
17898 // If LHS is not a shuffle then pretend it is the shuffle
17899 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
17900 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
17903 SmallVector<int, 16> LMask(NumElts);
17904 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
17905 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
17906 A = LHS.getOperand(0);
17907 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
17908 B = LHS.getOperand(1);
17909 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
17910 std::copy(Mask.begin(), Mask.end(), LMask.begin());
17912 if (LHS.getOpcode() != ISD::UNDEF)
17914 for (unsigned i = 0; i != NumElts; ++i)
17918 // Likewise, view RHS in the form
17919 // RHS = VECTOR_SHUFFLE C, D, RMask
17921 SmallVector<int, 16> RMask(NumElts);
17922 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
17923 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
17924 C = RHS.getOperand(0);
17925 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
17926 D = RHS.getOperand(1);
17927 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
17928 std::copy(Mask.begin(), Mask.end(), RMask.begin());
17930 if (RHS.getOpcode() != ISD::UNDEF)
17932 for (unsigned i = 0; i != NumElts; ++i)
17936 // Check that the shuffles are both shuffling the same vectors.
17937 if (!(A == C && B == D) && !(A == D && B == C))
17940 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
17941 if (!A.getNode() && !B.getNode())
17944 // If A and B occur in reverse order in RHS, then "swap" them (which means
17945 // rewriting the mask).
17947 CommuteVectorShuffleMask(RMask, NumElts);
17949 // At this point LHS and RHS are equivalent to
17950 // LHS = VECTOR_SHUFFLE A, B, LMask
17951 // RHS = VECTOR_SHUFFLE A, B, RMask
17952 // Check that the masks correspond to performing a horizontal operation.
17953 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
17954 for (unsigned i = 0; i != NumLaneElts; ++i) {
17955 int LIdx = LMask[i+l], RIdx = RMask[i+l];
17957 // Ignore any UNDEF components.
17958 if (LIdx < 0 || RIdx < 0 ||
17959 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
17960 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
17963 // Check that successive elements are being operated on. If not, this is
17964 // not a horizontal operation.
17965 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
17966 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
17967 if (!(LIdx == Index && RIdx == Index + 1) &&
17968 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
17973 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
17974 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
17978 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
17979 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
17980 const X86Subtarget *Subtarget) {
17981 EVT VT = N->getValueType(0);
17982 SDValue LHS = N->getOperand(0);
17983 SDValue RHS = N->getOperand(1);
17985 // Try to synthesize horizontal adds from adds of shuffles.
17986 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
17987 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
17988 isHorizontalBinOp(LHS, RHS, true))
17989 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
17993 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
17994 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
17995 const X86Subtarget *Subtarget) {
17996 EVT VT = N->getValueType(0);
17997 SDValue LHS = N->getOperand(0);
17998 SDValue RHS = N->getOperand(1);
18000 // Try to synthesize horizontal subs from subs of shuffles.
18001 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
18002 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
18003 isHorizontalBinOp(LHS, RHS, false))
18004 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
18008 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
18009 /// X86ISD::FXOR nodes.
18010 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
18011 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
18012 // F[X]OR(0.0, x) -> x
18013 // F[X]OR(x, 0.0) -> x
18014 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
18015 if (C->getValueAPF().isPosZero())
18016 return N->getOperand(1);
18017 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
18018 if (C->getValueAPF().isPosZero())
18019 return N->getOperand(0);
18023 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
18024 /// X86ISD::FMAX nodes.
18025 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
18026 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
18028 // Only perform optimizations if UnsafeMath is used.
18029 if (!DAG.getTarget().Options.UnsafeFPMath)
18032 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
18033 // into FMINC and FMAXC, which are Commutative operations.
18034 unsigned NewOp = 0;
18035 switch (N->getOpcode()) {
18036 default: llvm_unreachable("unknown opcode");
18037 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
18038 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
18041 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
18042 N->getOperand(0), N->getOperand(1));
18045 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
18046 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
18047 // FAND(0.0, x) -> 0.0
18048 // FAND(x, 0.0) -> 0.0
18049 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
18050 if (C->getValueAPF().isPosZero())
18051 return N->getOperand(0);
18052 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
18053 if (C->getValueAPF().isPosZero())
18054 return N->getOperand(1);
18058 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
18059 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
18060 // FANDN(x, 0.0) -> 0.0
18061 // FANDN(0.0, x) -> x
18062 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
18063 if (C->getValueAPF().isPosZero())
18064 return N->getOperand(1);
18065 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
18066 if (C->getValueAPF().isPosZero())
18067 return N->getOperand(1);
18071 static SDValue PerformBTCombine(SDNode *N,
18073 TargetLowering::DAGCombinerInfo &DCI) {
18074 // BT ignores high bits in the bit index operand.
18075 SDValue Op1 = N->getOperand(1);
18076 if (Op1.hasOneUse()) {
18077 unsigned BitWidth = Op1.getValueSizeInBits();
18078 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
18079 APInt KnownZero, KnownOne;
18080 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
18081 !DCI.isBeforeLegalizeOps());
18082 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18083 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
18084 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
18085 DCI.CommitTargetLoweringOpt(TLO);
18090 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
18091 SDValue Op = N->getOperand(0);
18092 if (Op.getOpcode() == ISD::BITCAST)
18093 Op = Op.getOperand(0);
18094 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
18095 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
18096 VT.getVectorElementType().getSizeInBits() ==
18097 OpVT.getVectorElementType().getSizeInBits()) {
18098 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
18103 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
18104 const X86Subtarget *Subtarget) {
18105 EVT VT = N->getValueType(0);
18106 if (!VT.isVector())
18109 SDValue N0 = N->getOperand(0);
18110 SDValue N1 = N->getOperand(1);
18111 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
18114 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
18115 // both SSE and AVX2 since there is no sign-extended shift right
18116 // operation on a vector with 64-bit elements.
18117 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
18118 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
18119 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
18120 N0.getOpcode() == ISD::SIGN_EXTEND)) {
18121 SDValue N00 = N0.getOperand(0);
18123 // EXTLOAD has a better solution on AVX2,
18124 // it may be replaced with X86ISD::VSEXT node.
18125 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
18126 if (!ISD::isNormalLoad(N00.getNode()))
18129 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
18130 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
18132 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
18138 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
18139 TargetLowering::DAGCombinerInfo &DCI,
18140 const X86Subtarget *Subtarget) {
18141 if (!DCI.isBeforeLegalizeOps())
18144 if (!Subtarget->hasFp256())
18147 EVT VT = N->getValueType(0);
18148 if (VT.isVector() && VT.getSizeInBits() == 256) {
18149 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
18157 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
18158 const X86Subtarget* Subtarget) {
18160 EVT VT = N->getValueType(0);
18162 // Let legalize expand this if it isn't a legal type yet.
18163 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
18166 EVT ScalarVT = VT.getScalarType();
18167 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
18168 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
18171 SDValue A = N->getOperand(0);
18172 SDValue B = N->getOperand(1);
18173 SDValue C = N->getOperand(2);
18175 bool NegA = (A.getOpcode() == ISD::FNEG);
18176 bool NegB = (B.getOpcode() == ISD::FNEG);
18177 bool NegC = (C.getOpcode() == ISD::FNEG);
18179 // Negative multiplication when NegA xor NegB
18180 bool NegMul = (NegA != NegB);
18182 A = A.getOperand(0);
18184 B = B.getOperand(0);
18186 C = C.getOperand(0);
18190 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
18192 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
18194 return DAG.getNode(Opcode, dl, VT, A, B, C);
18197 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
18198 TargetLowering::DAGCombinerInfo &DCI,
18199 const X86Subtarget *Subtarget) {
18200 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
18201 // (and (i32 x86isd::setcc_carry), 1)
18202 // This eliminates the zext. This transformation is necessary because
18203 // ISD::SETCC is always legalized to i8.
18205 SDValue N0 = N->getOperand(0);
18206 EVT VT = N->getValueType(0);
18208 if (N0.getOpcode() == ISD::AND &&
18210 N0.getOperand(0).hasOneUse()) {
18211 SDValue N00 = N0.getOperand(0);
18212 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
18213 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
18214 if (!C || C->getZExtValue() != 1)
18216 return DAG.getNode(ISD::AND, dl, VT,
18217 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
18218 N00.getOperand(0), N00.getOperand(1)),
18219 DAG.getConstant(1, VT));
18223 if (VT.is256BitVector()) {
18224 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
18232 // Optimize x == -y --> x+y == 0
18233 // x != -y --> x+y != 0
18234 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
18235 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
18236 SDValue LHS = N->getOperand(0);
18237 SDValue RHS = N->getOperand(1);
18239 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
18240 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
18241 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
18242 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
18243 LHS.getValueType(), RHS, LHS.getOperand(1));
18244 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
18245 addV, DAG.getConstant(0, addV.getValueType()), CC);
18247 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
18248 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
18249 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
18250 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
18251 RHS.getValueType(), LHS, RHS.getOperand(1));
18252 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
18253 addV, DAG.getConstant(0, addV.getValueType()), CC);
18258 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
18259 // as "sbb reg,reg", since it can be extended without zext and produces
18260 // an all-ones bit which is more useful than 0/1 in some cases.
18261 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG) {
18262 return DAG.getNode(ISD::AND, DL, MVT::i8,
18263 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
18264 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
18265 DAG.getConstant(1, MVT::i8));
18268 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
18269 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
18270 TargetLowering::DAGCombinerInfo &DCI,
18271 const X86Subtarget *Subtarget) {
18273 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
18274 SDValue EFLAGS = N->getOperand(1);
18276 if (CC == X86::COND_A) {
18277 // Try to convert COND_A into COND_B in an attempt to facilitate
18278 // materializing "setb reg".
18280 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
18281 // cannot take an immediate as its first operand.
18283 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
18284 EFLAGS.getValueType().isInteger() &&
18285 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
18286 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
18287 EFLAGS.getNode()->getVTList(),
18288 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
18289 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
18290 return MaterializeSETB(DL, NewEFLAGS, DAG);
18294 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
18295 // a zext and produces an all-ones bit which is more useful than 0/1 in some
18297 if (CC == X86::COND_B)
18298 return MaterializeSETB(DL, EFLAGS, DAG);
18302 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
18303 if (Flags.getNode()) {
18304 SDValue Cond = DAG.getConstant(CC, MVT::i8);
18305 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
18311 // Optimize branch condition evaluation.
18313 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
18314 TargetLowering::DAGCombinerInfo &DCI,
18315 const X86Subtarget *Subtarget) {
18317 SDValue Chain = N->getOperand(0);
18318 SDValue Dest = N->getOperand(1);
18319 SDValue EFLAGS = N->getOperand(3);
18320 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
18324 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
18325 if (Flags.getNode()) {
18326 SDValue Cond = DAG.getConstant(CC, MVT::i8);
18327 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
18334 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
18335 const X86TargetLowering *XTLI) {
18336 SDValue Op0 = N->getOperand(0);
18337 EVT InVT = Op0->getValueType(0);
18339 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
18340 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
18342 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
18343 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
18344 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
18347 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
18348 // a 32-bit target where SSE doesn't support i64->FP operations.
18349 if (Op0.getOpcode() == ISD::LOAD) {
18350 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
18351 EVT VT = Ld->getValueType(0);
18352 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
18353 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
18354 !XTLI->getSubtarget()->is64Bit() &&
18355 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
18356 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
18357 Ld->getChain(), Op0, DAG);
18358 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
18365 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
18366 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
18367 X86TargetLowering::DAGCombinerInfo &DCI) {
18368 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
18369 // the result is either zero or one (depending on the input carry bit).
18370 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
18371 if (X86::isZeroNode(N->getOperand(0)) &&
18372 X86::isZeroNode(N->getOperand(1)) &&
18373 // We don't have a good way to replace an EFLAGS use, so only do this when
18375 SDValue(N, 1).use_empty()) {
18377 EVT VT = N->getValueType(0);
18378 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
18379 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
18380 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
18381 DAG.getConstant(X86::COND_B,MVT::i8),
18383 DAG.getConstant(1, VT));
18384 return DCI.CombineTo(N, Res1, CarryOut);
18390 // fold (add Y, (sete X, 0)) -> adc 0, Y
18391 // (add Y, (setne X, 0)) -> sbb -1, Y
18392 // (sub (sete X, 0), Y) -> sbb 0, Y
18393 // (sub (setne X, 0), Y) -> adc -1, Y
18394 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
18397 // Look through ZExts.
18398 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
18399 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
18402 SDValue SetCC = Ext.getOperand(0);
18403 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
18406 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
18407 if (CC != X86::COND_E && CC != X86::COND_NE)
18410 SDValue Cmp = SetCC.getOperand(1);
18411 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
18412 !X86::isZeroNode(Cmp.getOperand(1)) ||
18413 !Cmp.getOperand(0).getValueType().isInteger())
18416 SDValue CmpOp0 = Cmp.getOperand(0);
18417 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
18418 DAG.getConstant(1, CmpOp0.getValueType()));
18420 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
18421 if (CC == X86::COND_NE)
18422 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
18423 DL, OtherVal.getValueType(), OtherVal,
18424 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
18425 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
18426 DL, OtherVal.getValueType(), OtherVal,
18427 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
18430 /// PerformADDCombine - Do target-specific dag combines on integer adds.
18431 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
18432 const X86Subtarget *Subtarget) {
18433 EVT VT = N->getValueType(0);
18434 SDValue Op0 = N->getOperand(0);
18435 SDValue Op1 = N->getOperand(1);
18437 // Try to synthesize horizontal adds from adds of shuffles.
18438 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
18439 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
18440 isHorizontalBinOp(Op0, Op1, true))
18441 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
18443 return OptimizeConditionalInDecrement(N, DAG);
18446 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
18447 const X86Subtarget *Subtarget) {
18448 SDValue Op0 = N->getOperand(0);
18449 SDValue Op1 = N->getOperand(1);
18451 // X86 can't encode an immediate LHS of a sub. See if we can push the
18452 // negation into a preceding instruction.
18453 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
18454 // If the RHS of the sub is a XOR with one use and a constant, invert the
18455 // immediate. Then add one to the LHS of the sub so we can turn
18456 // X-Y -> X+~Y+1, saving one register.
18457 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
18458 isa<ConstantSDNode>(Op1.getOperand(1))) {
18459 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
18460 EVT VT = Op0.getValueType();
18461 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
18463 DAG.getConstant(~XorC, VT));
18464 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
18465 DAG.getConstant(C->getAPIntValue()+1, VT));
18469 // Try to synthesize horizontal adds from adds of shuffles.
18470 EVT VT = N->getValueType(0);
18471 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
18472 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
18473 isHorizontalBinOp(Op0, Op1, true))
18474 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
18476 return OptimizeConditionalInDecrement(N, DAG);
18479 /// performVZEXTCombine - Performs build vector combines
18480 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
18481 TargetLowering::DAGCombinerInfo &DCI,
18482 const X86Subtarget *Subtarget) {
18483 // (vzext (bitcast (vzext (x)) -> (vzext x)
18484 SDValue In = N->getOperand(0);
18485 while (In.getOpcode() == ISD::BITCAST)
18486 In = In.getOperand(0);
18488 if (In.getOpcode() != X86ISD::VZEXT)
18491 return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
18495 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
18496 DAGCombinerInfo &DCI) const {
18497 SelectionDAG &DAG = DCI.DAG;
18498 switch (N->getOpcode()) {
18500 case ISD::EXTRACT_VECTOR_ELT:
18501 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
18503 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
18504 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
18505 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
18506 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
18507 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
18508 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
18511 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
18512 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
18513 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
18514 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
18515 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
18516 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
18517 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
18518 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
18519 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
18521 case X86ISD::FOR: return PerformFORCombine(N, DAG);
18523 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
18524 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
18525 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
18526 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
18527 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
18528 case ISD::ANY_EXTEND:
18529 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
18530 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
18531 case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
18532 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
18533 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG);
18534 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
18535 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
18536 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
18537 case X86ISD::SHUFP: // Handle all target specific shuffles
18538 case X86ISD::PALIGNR:
18539 case X86ISD::UNPCKH:
18540 case X86ISD::UNPCKL:
18541 case X86ISD::MOVHLPS:
18542 case X86ISD::MOVLHPS:
18543 case X86ISD::PSHUFD:
18544 case X86ISD::PSHUFHW:
18545 case X86ISD::PSHUFLW:
18546 case X86ISD::MOVSS:
18547 case X86ISD::MOVSD:
18548 case X86ISD::VPERMILP:
18549 case X86ISD::VPERM2X128:
18550 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
18551 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
18557 /// isTypeDesirableForOp - Return true if the target has native support for
18558 /// the specified value type and it is 'desirable' to use the type for the
18559 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
18560 /// instruction encodings are longer and some i16 instructions are slow.
18561 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
18562 if (!isTypeLegal(VT))
18564 if (VT != MVT::i16)
18571 case ISD::SIGN_EXTEND:
18572 case ISD::ZERO_EXTEND:
18573 case ISD::ANY_EXTEND:
18586 /// IsDesirableToPromoteOp - This method query the target whether it is
18587 /// beneficial for dag combiner to promote the specified node. If true, it
18588 /// should return the desired promotion type by reference.
18589 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
18590 EVT VT = Op.getValueType();
18591 if (VT != MVT::i16)
18594 bool Promote = false;
18595 bool Commute = false;
18596 switch (Op.getOpcode()) {
18599 LoadSDNode *LD = cast<LoadSDNode>(Op);
18600 // If the non-extending load has a single use and it's not live out, then it
18601 // might be folded.
18602 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
18603 Op.hasOneUse()*/) {
18604 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
18605 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
18606 // The only case where we'd want to promote LOAD (rather then it being
18607 // promoted as an operand is when it's only use is liveout.
18608 if (UI->getOpcode() != ISD::CopyToReg)
18615 case ISD::SIGN_EXTEND:
18616 case ISD::ZERO_EXTEND:
18617 case ISD::ANY_EXTEND:
18622 SDValue N0 = Op.getOperand(0);
18623 // Look out for (store (shl (load), x)).
18624 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
18637 SDValue N0 = Op.getOperand(0);
18638 SDValue N1 = Op.getOperand(1);
18639 if (!Commute && MayFoldLoad(N1))
18641 // Avoid disabling potential load folding opportunities.
18642 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
18644 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
18654 //===----------------------------------------------------------------------===//
18655 // X86 Inline Assembly Support
18656 //===----------------------------------------------------------------------===//
18659 // Helper to match a string separated by whitespace.
18660 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
18661 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
18663 for (unsigned i = 0, e = args.size(); i != e; ++i) {
18664 StringRef piece(*args[i]);
18665 if (!s.startswith(piece)) // Check if the piece matches.
18668 s = s.substr(piece.size());
18669 StringRef::size_type pos = s.find_first_not_of(" \t");
18670 if (pos == 0) // We matched a prefix.
18678 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
18681 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
18682 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
18684 std::string AsmStr = IA->getAsmString();
18686 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
18687 if (!Ty || Ty->getBitWidth() % 16 != 0)
18690 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
18691 SmallVector<StringRef, 4> AsmPieces;
18692 SplitString(AsmStr, AsmPieces, ";\n");
18694 switch (AsmPieces.size()) {
18695 default: return false;
18697 // FIXME: this should verify that we are targeting a 486 or better. If not,
18698 // we will turn this bswap into something that will be lowered to logical
18699 // ops instead of emitting the bswap asm. For now, we don't support 486 or
18700 // lower so don't worry about this.
18702 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
18703 matchAsm(AsmPieces[0], "bswapl", "$0") ||
18704 matchAsm(AsmPieces[0], "bswapq", "$0") ||
18705 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
18706 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
18707 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
18708 // No need to check constraints, nothing other than the equivalent of
18709 // "=r,0" would be valid here.
18710 return IntrinsicLowering::LowerToByteSwap(CI);
18713 // rorw $$8, ${0:w} --> llvm.bswap.i16
18714 if (CI->getType()->isIntegerTy(16) &&
18715 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
18716 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
18717 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
18719 const std::string &ConstraintsStr = IA->getConstraintString();
18720 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
18721 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
18722 if (AsmPieces.size() == 4 &&
18723 AsmPieces[0] == "~{cc}" &&
18724 AsmPieces[1] == "~{dirflag}" &&
18725 AsmPieces[2] == "~{flags}" &&
18726 AsmPieces[3] == "~{fpsr}")
18727 return IntrinsicLowering::LowerToByteSwap(CI);
18731 if (CI->getType()->isIntegerTy(32) &&
18732 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
18733 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
18734 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
18735 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
18737 const std::string &ConstraintsStr = IA->getConstraintString();
18738 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
18739 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
18740 if (AsmPieces.size() == 4 &&
18741 AsmPieces[0] == "~{cc}" &&
18742 AsmPieces[1] == "~{dirflag}" &&
18743 AsmPieces[2] == "~{flags}" &&
18744 AsmPieces[3] == "~{fpsr}")
18745 return IntrinsicLowering::LowerToByteSwap(CI);
18748 if (CI->getType()->isIntegerTy(64)) {
18749 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
18750 if (Constraints.size() >= 2 &&
18751 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
18752 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
18753 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
18754 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
18755 matchAsm(AsmPieces[1], "bswap", "%edx") &&
18756 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
18757 return IntrinsicLowering::LowerToByteSwap(CI);
18765 /// getConstraintType - Given a constraint letter, return the type of
18766 /// constraint it is for this target.
18767 X86TargetLowering::ConstraintType
18768 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
18769 if (Constraint.size() == 1) {
18770 switch (Constraint[0]) {
18781 return C_RegisterClass;
18805 return TargetLowering::getConstraintType(Constraint);
18808 /// Examine constraint type and operand type and determine a weight value.
18809 /// This object must already have been set up with the operand type
18810 /// and the current alternative constraint selected.
18811 TargetLowering::ConstraintWeight
18812 X86TargetLowering::getSingleConstraintMatchWeight(
18813 AsmOperandInfo &info, const char *constraint) const {
18814 ConstraintWeight weight = CW_Invalid;
18815 Value *CallOperandVal = info.CallOperandVal;
18816 // If we don't have a value, we can't do a match,
18817 // but allow it at the lowest weight.
18818 if (CallOperandVal == NULL)
18820 Type *type = CallOperandVal->getType();
18821 // Look at the constraint type.
18822 switch (*constraint) {
18824 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
18835 if (CallOperandVal->getType()->isIntegerTy())
18836 weight = CW_SpecificReg;
18841 if (type->isFloatingPointTy())
18842 weight = CW_SpecificReg;
18845 if (type->isX86_MMXTy() && Subtarget->hasMMX())
18846 weight = CW_SpecificReg;
18850 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
18851 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
18852 weight = CW_Register;
18855 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
18856 if (C->getZExtValue() <= 31)
18857 weight = CW_Constant;
18861 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18862 if (C->getZExtValue() <= 63)
18863 weight = CW_Constant;
18867 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18868 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
18869 weight = CW_Constant;
18873 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18874 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
18875 weight = CW_Constant;
18879 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18880 if (C->getZExtValue() <= 3)
18881 weight = CW_Constant;
18885 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18886 if (C->getZExtValue() <= 0xff)
18887 weight = CW_Constant;
18892 if (dyn_cast<ConstantFP>(CallOperandVal)) {
18893 weight = CW_Constant;
18897 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18898 if ((C->getSExtValue() >= -0x80000000LL) &&
18899 (C->getSExtValue() <= 0x7fffffffLL))
18900 weight = CW_Constant;
18904 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18905 if (C->getZExtValue() <= 0xffffffff)
18906 weight = CW_Constant;
18913 /// LowerXConstraint - try to replace an X constraint, which matches anything,
18914 /// with another that has more specific requirements based on the type of the
18915 /// corresponding operand.
18916 const char *X86TargetLowering::
18917 LowerXConstraint(EVT ConstraintVT) const {
18918 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
18919 // 'f' like normal targets.
18920 if (ConstraintVT.isFloatingPoint()) {
18921 if (Subtarget->hasSSE2())
18923 if (Subtarget->hasSSE1())
18927 return TargetLowering::LowerXConstraint(ConstraintVT);
18930 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
18931 /// vector. If it is invalid, don't add anything to Ops.
18932 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
18933 std::string &Constraint,
18934 std::vector<SDValue>&Ops,
18935 SelectionDAG &DAG) const {
18936 SDValue Result(0, 0);
18938 // Only support length 1 constraints for now.
18939 if (Constraint.length() > 1) return;
18941 char ConstraintLetter = Constraint[0];
18942 switch (ConstraintLetter) {
18945 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18946 if (C->getZExtValue() <= 31) {
18947 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18953 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18954 if (C->getZExtValue() <= 63) {
18955 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18961 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18962 if (isInt<8>(C->getSExtValue())) {
18963 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18969 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18970 if (C->getZExtValue() <= 255) {
18971 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18977 // 32-bit signed value
18978 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18979 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
18980 C->getSExtValue())) {
18981 // Widen to 64 bits here to get it sign extended.
18982 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
18985 // FIXME gcc accepts some relocatable values here too, but only in certain
18986 // memory models; it's complicated.
18991 // 32-bit unsigned value
18992 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18993 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
18994 C->getZExtValue())) {
18995 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18999 // FIXME gcc accepts some relocatable values here too, but only in certain
19000 // memory models; it's complicated.
19004 // Literal immediates are always ok.
19005 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
19006 // Widen to 64 bits here to get it sign extended.
19007 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
19011 // In any sort of PIC mode addresses need to be computed at runtime by
19012 // adding in a register or some sort of table lookup. These can't
19013 // be used as immediates.
19014 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
19017 // If we are in non-pic codegen mode, we allow the address of a global (with
19018 // an optional displacement) to be used with 'i'.
19019 GlobalAddressSDNode *GA = 0;
19020 int64_t Offset = 0;
19022 // Match either (GA), (GA+C), (GA+C1+C2), etc.
19024 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
19025 Offset += GA->getOffset();
19027 } else if (Op.getOpcode() == ISD::ADD) {
19028 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
19029 Offset += C->getZExtValue();
19030 Op = Op.getOperand(0);
19033 } else if (Op.getOpcode() == ISD::SUB) {
19034 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
19035 Offset += -C->getZExtValue();
19036 Op = Op.getOperand(0);
19041 // Otherwise, this isn't something we can handle, reject it.
19045 const GlobalValue *GV = GA->getGlobal();
19046 // If we require an extra load to get this address, as in PIC mode, we
19047 // can't accept it.
19048 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
19049 getTargetMachine())))
19052 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
19053 GA->getValueType(0), Offset);
19058 if (Result.getNode()) {
19059 Ops.push_back(Result);
19062 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
19065 std::pair<unsigned, const TargetRegisterClass*>
19066 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
19068 // First, see if this is a constraint that directly corresponds to an LLVM
19070 if (Constraint.size() == 1) {
19071 // GCC Constraint Letters
19072 switch (Constraint[0]) {
19074 // TODO: Slight differences here in allocation order and leaving
19075 // RIP in the class. Do they matter any more here than they do
19076 // in the normal allocation?
19077 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
19078 if (Subtarget->is64Bit()) {
19079 if (VT == MVT::i32 || VT == MVT::f32)
19080 return std::make_pair(0U, &X86::GR32RegClass);
19081 if (VT == MVT::i16)
19082 return std::make_pair(0U, &X86::GR16RegClass);
19083 if (VT == MVT::i8 || VT == MVT::i1)
19084 return std::make_pair(0U, &X86::GR8RegClass);
19085 if (VT == MVT::i64 || VT == MVT::f64)
19086 return std::make_pair(0U, &X86::GR64RegClass);
19089 // 32-bit fallthrough
19090 case 'Q': // Q_REGS
19091 if (VT == MVT::i32 || VT == MVT::f32)
19092 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
19093 if (VT == MVT::i16)
19094 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
19095 if (VT == MVT::i8 || VT == MVT::i1)
19096 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
19097 if (VT == MVT::i64)
19098 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
19100 case 'r': // GENERAL_REGS
19101 case 'l': // INDEX_REGS
19102 if (VT == MVT::i8 || VT == MVT::i1)
19103 return std::make_pair(0U, &X86::GR8RegClass);
19104 if (VT == MVT::i16)
19105 return std::make_pair(0U, &X86::GR16RegClass);
19106 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
19107 return std::make_pair(0U, &X86::GR32RegClass);
19108 return std::make_pair(0U, &X86::GR64RegClass);
19109 case 'R': // LEGACY_REGS
19110 if (VT == MVT::i8 || VT == MVT::i1)
19111 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
19112 if (VT == MVT::i16)
19113 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
19114 if (VT == MVT::i32 || !Subtarget->is64Bit())
19115 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
19116 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
19117 case 'f': // FP Stack registers.
19118 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
19119 // value to the correct fpstack register class.
19120 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
19121 return std::make_pair(0U, &X86::RFP32RegClass);
19122 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
19123 return std::make_pair(0U, &X86::RFP64RegClass);
19124 return std::make_pair(0U, &X86::RFP80RegClass);
19125 case 'y': // MMX_REGS if MMX allowed.
19126 if (!Subtarget->hasMMX()) break;
19127 return std::make_pair(0U, &X86::VR64RegClass);
19128 case 'Y': // SSE_REGS if SSE2 allowed
19129 if (!Subtarget->hasSSE2()) break;
19131 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
19132 if (!Subtarget->hasSSE1()) break;
19134 switch (VT.SimpleTy) {
19136 // Scalar SSE types.
19139 return std::make_pair(0U, &X86::FR32RegClass);
19142 return std::make_pair(0U, &X86::FR64RegClass);
19150 return std::make_pair(0U, &X86::VR128RegClass);
19158 return std::make_pair(0U, &X86::VR256RegClass);
19163 return std::make_pair(0U, &X86::VR512RegClass);
19169 // Use the default implementation in TargetLowering to convert the register
19170 // constraint into a member of a register class.
19171 std::pair<unsigned, const TargetRegisterClass*> Res;
19172 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
19174 // Not found as a standard register?
19175 if (Res.second == 0) {
19176 // Map st(0) -> st(7) -> ST0
19177 if (Constraint.size() == 7 && Constraint[0] == '{' &&
19178 tolower(Constraint[1]) == 's' &&
19179 tolower(Constraint[2]) == 't' &&
19180 Constraint[3] == '(' &&
19181 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
19182 Constraint[5] == ')' &&
19183 Constraint[6] == '}') {
19185 Res.first = X86::ST0+Constraint[4]-'0';
19186 Res.second = &X86::RFP80RegClass;
19190 // GCC allows "st(0)" to be called just plain "st".
19191 if (StringRef("{st}").equals_lower(Constraint)) {
19192 Res.first = X86::ST0;
19193 Res.second = &X86::RFP80RegClass;
19198 if (StringRef("{flags}").equals_lower(Constraint)) {
19199 Res.first = X86::EFLAGS;
19200 Res.second = &X86::CCRRegClass;
19204 // 'A' means EAX + EDX.
19205 if (Constraint == "A") {
19206 Res.first = X86::EAX;
19207 Res.second = &X86::GR32_ADRegClass;
19213 // Otherwise, check to see if this is a register class of the wrong value
19214 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
19215 // turn into {ax},{dx}.
19216 if (Res.second->hasType(VT))
19217 return Res; // Correct type already, nothing to do.
19219 // All of the single-register GCC register classes map their values onto
19220 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
19221 // really want an 8-bit or 32-bit register, map to the appropriate register
19222 // class and return the appropriate register.
19223 if (Res.second == &X86::GR16RegClass) {
19224 if (VT == MVT::i8 || VT == MVT::i1) {
19225 unsigned DestReg = 0;
19226 switch (Res.first) {
19228 case X86::AX: DestReg = X86::AL; break;
19229 case X86::DX: DestReg = X86::DL; break;
19230 case X86::CX: DestReg = X86::CL; break;
19231 case X86::BX: DestReg = X86::BL; break;
19234 Res.first = DestReg;
19235 Res.second = &X86::GR8RegClass;
19237 } else if (VT == MVT::i32 || VT == MVT::f32) {
19238 unsigned DestReg = 0;
19239 switch (Res.first) {
19241 case X86::AX: DestReg = X86::EAX; break;
19242 case X86::DX: DestReg = X86::EDX; break;
19243 case X86::CX: DestReg = X86::ECX; break;
19244 case X86::BX: DestReg = X86::EBX; break;
19245 case X86::SI: DestReg = X86::ESI; break;
19246 case X86::DI: DestReg = X86::EDI; break;
19247 case X86::BP: DestReg = X86::EBP; break;
19248 case X86::SP: DestReg = X86::ESP; break;
19251 Res.first = DestReg;
19252 Res.second = &X86::GR32RegClass;
19254 } else if (VT == MVT::i64 || VT == MVT::f64) {
19255 unsigned DestReg = 0;
19256 switch (Res.first) {
19258 case X86::AX: DestReg = X86::RAX; break;
19259 case X86::DX: DestReg = X86::RDX; break;
19260 case X86::CX: DestReg = X86::RCX; break;
19261 case X86::BX: DestReg = X86::RBX; break;
19262 case X86::SI: DestReg = X86::RSI; break;
19263 case X86::DI: DestReg = X86::RDI; break;
19264 case X86::BP: DestReg = X86::RBP; break;
19265 case X86::SP: DestReg = X86::RSP; break;
19268 Res.first = DestReg;
19269 Res.second = &X86::GR64RegClass;
19272 } else if (Res.second == &X86::FR32RegClass ||
19273 Res.second == &X86::FR64RegClass ||
19274 Res.second == &X86::VR128RegClass ||
19275 Res.second == &X86::VR256RegClass ||
19276 Res.second == &X86::FR32XRegClass ||
19277 Res.second == &X86::FR64XRegClass ||
19278 Res.second == &X86::VR128XRegClass ||
19279 Res.second == &X86::VR256XRegClass ||
19280 Res.second == &X86::VR512RegClass) {
19281 // Handle references to XMM physical registers that got mapped into the
19282 // wrong class. This can happen with constraints like {xmm0} where the
19283 // target independent register mapper will just pick the first match it can
19284 // find, ignoring the required type.
19286 if (VT == MVT::f32 || VT == MVT::i32)
19287 Res.second = &X86::FR32RegClass;
19288 else if (VT == MVT::f64 || VT == MVT::i64)
19289 Res.second = &X86::FR64RegClass;
19290 else if (X86::VR128RegClass.hasType(VT))
19291 Res.second = &X86::VR128RegClass;
19292 else if (X86::VR256RegClass.hasType(VT))
19293 Res.second = &X86::VR256RegClass;
19294 else if (X86::VR512RegClass.hasType(VT))
19295 Res.second = &X86::VR512RegClass;